[
  {
    "path": ".github/FUNDING.yml",
    "content": "github: tondrej"
  },
  {
    "path": ".gitignore",
    "content": "# Uncomment these types if you want even more clean repository. But be careful.\n# It can make harm to an existing project source. Read explanations below.\n#\n# Resource files are binaries containing manifest, project icon and version info.\n# They can not be viewed as text or compared by diff-tools. Consider replacing them with .rc files.\n#*.res\n#\n# Type library file (binary). In old Delphi versions it should be stored.\n# Since Delphi 2009 it is produced from .ridl file and can safely be ignored.\n#*.tlb\n#\n# Diagram Portfolio file. Used by the diagram editor up to Delphi 7.\n# Uncomment this if you are not using diagrams or use newer Delphi version.\n#*.ddp\n#\n# Visual LiveBindings file. Added in Delphi XE2.\n# Uncomment this if you are not using LiveBindings Designer.\n#*.vlb\n#\n# Deployment Manager configuration file for your project. Added in Delphi XE2.\n# Uncomment this if it is not mobile development and you do not use remote debug feature.\n#*.deployproj\n# \n# C++ object files produced when C/C++ Output file generation is configured.\n# Uncomment this if you are not using external objects (zlib library for example).\n#*.obj\n#\n\n# Delphi compiler-generated binaries (safe to delete)\n*.exe\n*.dll\n*.bpl\n*.bpi\n*.dcp\n*.so\n*.apk\n*.drc\n*.map\n*.dres\n*.rsm\n*.tds\n*.dcu\n*.lib\n*.a\n*.o\n*.ocx\n*.otares\n\n# Delphi autogenerated files (duplicated info)\n*.cfg\n*.ddp\n*.hpp\n*Resource.rc\n\n# Delphi local files (user-specific info)\n*.local\n*.identcache\n*.projdata\n*.tvsconfig\n*.dsk\n\n# Delphi history and backups\n__history/\n__recovery/\n*.~*\n\n# Castalia statistics file (since XE7 Castalia is distributed with Delphi)\n*.stat\n\n# FPC local files (user-specific info)\n*.lps\n\n# chakracore-delphi-specific paths\n/bin\n/lib\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"ext/jedi\"]\n\tpath = ext/jedi\n\turl = https://github.com/tondrej/jedi\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# chakracore-delphi\n\n[![Licensed under the MIT License](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/tondrej/chakracore-delphi/blob/master/LICENSE)\n![PR's Welcome](https://img.shields.io/badge/PRs%20-welcome-brightgreen.svg)\n\n[Delphi](https://www.embarcadero.com/products/delphi) and [Free Pascal](https://www.freepascal.org) bindings and classes for Microsoft's [ChakraCore](https://github.com/Microsoft/ChakraCore) library.\n\nChakraCore version: **1.11.24**\n\nSupported compilers:\n- Delphi 7 or newer\n- Free Pascal 3.0.4 or newer\n\nSupported target platforms:\n- i386-win32 (Delphi 7 or newer, Free Pascal)\n- x86_64-win64 (Delphi XE2 or newer, Free Pascal)\n- x86_64-linux (Free Pascal)\n- x86_64-darwin (Free Pascal)\n\nInstallation:\n\n1. Clone this repository:\n```bash\ngit clone https://github.com/tondrej/chakracore-delphi.git\ncd chakracore-delphi\ngit submodule update --init\n```\nor\n```bash\ngit clone --recurse-submodules https://github.com/tondrej/chakracore-delphi.git\n```\n2. Download the binaries from the ChakraCore [Release](https://github.com/Microsoft/ChakraCore/releases/tag/v1.11.24) page\n3. Enjoy!\n"
  },
  {
    "path": "include/ChakraCommon.h",
    "content": "//-------------------------------------------------------------------------------------------------------\n// Copyright (C) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n//-------------------------------------------------------------------------------------------------------\n/// \\mainpage Chakra Hosting API Reference\n///\n/// Chakra is Microsoft's JavaScript engine. It is an integral part of Internet Explorer but can\n/// also be hosted independently by other applications. This reference describes the APIs available\n/// to applications to host Chakra.\n///\n/// This file contains the common API set shared among all Chakra releases.  For Windows-specific\n/// releases, see chakrart.h.\n\n/// \\file\n/// \\brief The base Chakra hosting API.\n///\n/// This file contains a flat C API layer. This is the API exported by chakra.dll.\n\n#ifdef _MSC_VER\n#pragma once\n#endif  // _MSC_VER\n\n#ifndef _CHAKRACOMMON_H_\n#define _CHAKRACOMMON_H_\n\n// Platform specific code\n#if defined(_WIN32) && defined(_MSC_VER)\n#include <oaidl.h>\n\n// Header macros\n#define CHAKRA_CALLBACK CALLBACK\n#define CHAKRA_API STDAPI_(JsErrorCode)\n\ntypedef DWORD_PTR ChakraCookie;\ntypedef BYTE* ChakraBytePtr;\n#else // Non-Windows VC++\n\n// SAL compat\n#define _Return_type_success_(x)\n#define _In_\n#define _In_z_\n#define _In_opt_\n#define _Inout_\n#define _Out_\n#define _Out_opt_\n#define _In_reads_(x)\n#define _Pre_maybenull_\n#define _Pre_writable_byte_size_(byteLength)\n#define _Outptr_result_buffer_(byteLength)\n#define _Outptr_result_bytebuffer_(byteLength)\n#define _Outptr_result_maybenull_\n#define _Outptr_result_z_\n#define _Ret_maybenull_\n#define _Out_writes_(size)\n#define _Out_writes_to_opt_(byteLength, byteLength2)\n\n// Header macros\n#ifdef __i386___\n#define CHAKRA_CALLBACK __attribute__((cdecl))\n#else // non-32 bit x86 doesn't have cdecl support\n#define CHAKRA_CALLBACK\n#endif // __i386__\n\n#ifndef _WIN32\n#define SET_API_VISIBILITY __attribute__((visibility(\"default\")))\n#else\n#define SET_API_VISIBILITY\n#endif\n\n#ifdef __cplusplus\n#define CHAKRA_API extern \"C\" SET_API_VISIBILITY JsErrorCode\n#else\n#define CHAKRA_API extern     SET_API_VISIBILITY JsErrorCode\n#include <stdbool.h>\n#endif\n\n#include <stddef.h>  // for size_t\n#include <stdint.h>  // for uintptr_t\ntypedef uintptr_t ChakraCookie;\ntypedef unsigned char* ChakraBytePtr;\n\n// xplat-todo: try reduce usage of following types\n#if !defined(__MSTYPES_DEFINED)\ntypedef uint32_t UINT32;\ntypedef int64_t INT64;\ntypedef void* HANDLE;\ntypedef unsigned char BYTE;\ntypedef BYTE byte;\ntypedef UINT32 DWORD;\ntypedef unsigned short WCHAR;\n#endif\n\n#endif //  defined(_WIN32) && defined(_MSC_VER)\n\n#if (defined(_MSC_VER) && _MSC_VER <= 1900) || (!defined(_MSC_VER) && __cplusplus <= 199711L) // !C++11\ntypedef unsigned short uint16_t;\n#else\n#include <stdint.h>\n#endif\n\n    /// <summary>\n    ///     An error code returned from a Chakra hosting API.\n    /// </summary>\n    typedef _Return_type_success_(return == 0) enum _JsErrorCode\n    {\n        /// <summary>\n        ///     Success error code.\n        /// </summary>\n        JsNoError = 0,\n\n        /// <summary>\n        ///     Category of errors that relates to incorrect usage of the API itself.\n        /// </summary>\n        JsErrorCategoryUsage = 0x10000,\n        /// <summary>\n        ///     An argument to a hosting API was invalid.\n        /// </summary>\n        JsErrorInvalidArgument,\n        /// <summary>\n        ///     An argument to a hosting API was null in a context where null is not allowed.\n        /// </summary>\n        JsErrorNullArgument,\n        /// <summary>\n        ///     The hosting API requires that a context be current, but there is no current context.\n        /// </summary>\n        JsErrorNoCurrentContext,\n        /// <summary>\n        ///     The engine is in an exception state and no APIs can be called until the exception is\n        ///     cleared.\n        /// </summary>\n        JsErrorInExceptionState,\n        /// <summary>\n        ///     A hosting API is not yet implemented.\n        /// </summary>\n        JsErrorNotImplemented,\n        /// <summary>\n        ///     A hosting API was called on the wrong thread.\n        /// </summary>\n        JsErrorWrongThread,\n        /// <summary>\n        ///     A runtime that is still in use cannot be disposed.\n        /// </summary>\n        JsErrorRuntimeInUse,\n        /// <summary>\n        ///     A bad serialized script was used, or the serialized script was serialized by a\n        ///     different version of the Chakra engine.\n        /// </summary>\n        JsErrorBadSerializedScript,\n        /// <summary>\n        ///     The runtime is in a disabled state.\n        /// </summary>\n        JsErrorInDisabledState,\n        /// <summary>\n        ///     Runtime does not support reliable script interruption.\n        /// </summary>\n        JsErrorCannotDisableExecution,\n        /// <summary>\n        ///     A heap enumeration is currently underway in the script context.\n        /// </summary>\n        JsErrorHeapEnumInProgress,\n        /// <summary>\n        ///     A hosting API that operates on object values was called with a non-object value.\n        /// </summary>\n        JsErrorArgumentNotObject,\n        /// <summary>\n        ///     A script context is in the middle of a profile callback.\n        /// </summary>\n        JsErrorInProfileCallback,\n        /// <summary>\n        ///     A thread service callback is currently underway.\n        /// </summary>\n        JsErrorInThreadServiceCallback,\n        /// <summary>\n        ///     Scripts cannot be serialized in debug contexts.\n        /// </summary>\n        JsErrorCannotSerializeDebugScript,\n        /// <summary>\n        ///     The context cannot be put into a debug state because it is already in a debug state.\n        /// </summary>\n        JsErrorAlreadyDebuggingContext,\n        /// <summary>\n        ///     The context cannot start profiling because it is already profiling.\n        /// </summary>\n        JsErrorAlreadyProfilingContext,\n        /// <summary>\n        ///     Idle notification given when the host did not enable idle processing.\n        /// </summary>\n        JsErrorIdleNotEnabled,\n        /// <summary>\n        ///     The context did not accept the enqueue callback.\n        /// </summary>\n        JsCannotSetProjectionEnqueueCallback,\n        /// <summary>\n        ///     Failed to start projection.\n        /// </summary>\n        JsErrorCannotStartProjection,\n        /// <summary>\n        ///     The operation is not supported in an object before collect callback.\n        /// </summary>\n        JsErrorInObjectBeforeCollectCallback,\n        /// <summary>\n        ///     Object cannot be unwrapped to IInspectable pointer.\n        /// </summary>\n        JsErrorObjectNotInspectable,\n        /// <summary>\n        ///     A hosting API that operates on symbol property ids but was called with a non-symbol property id.\n        ///     The error code is returned by JsGetSymbolFromPropertyId if the function is called with non-symbol property id.\n        /// </summary>\n        JsErrorPropertyNotSymbol,\n        /// <summary>\n        ///     A hosting API that operates on string property ids but was called with a non-string property id.\n        ///     The error code is returned by existing JsGetPropertyNamefromId if the function is called with non-string property id.\n        /// </summary>\n        JsErrorPropertyNotString,\n        /// <summary>\n        ///     Module evaluation is called in wrong context.\n        /// </summary>\n        JsErrorInvalidContext,\n        /// <summary>\n        ///     Module evaluation is called in wrong context.\n        /// </summary>\n        JsInvalidModuleHostInfoKind,\n        /// <summary>\n        ///     Module was parsed already when JsParseModuleSource is called.\n        /// </summary>\n        JsErrorModuleParsed,\n        /// <summary>\n        ///     Argument passed to JsCreateWeakReference is a primitive that is not managed by the GC.\n        ///     No weak reference is required, the value will never be collected.\n        /// </summary>\n        JsNoWeakRefRequired,\n        /// <summary>\n        ///     The <c>Promise</c> object is still in the pending state.\n        /// </summary>\n        JsErrorPromisePending,\n        /// <summary>\n        ///     Module was not yet evaluated when JsGetModuleNamespace was called.\n        /// </summary>\n        JsErrorModuleNotEvaluated,\n        /// <summary>\n        ///     Category of errors that relates to errors occurring within the engine itself.\n        /// </summary>\n        JsErrorCategoryEngine = 0x20000,\n        /// <summary>\n        ///     The Chakra engine has run out of memory.\n        /// </summary>\n        JsErrorOutOfMemory,\n        /// <summary>\n        ///     The Chakra engine failed to set the Floating Point Unit state.\n        /// </summary>\n        JsErrorBadFPUState,\n\n        /// <summary>\n        ///     Category of errors that relates to errors in a script.\n        /// </summary>\n        JsErrorCategoryScript = 0x30000,\n        /// <summary>\n        ///     A JavaScript exception occurred while running a script.\n        /// </summary>\n        JsErrorScriptException,\n        /// <summary>\n        ///     JavaScript failed to compile.\n        /// </summary>\n        JsErrorScriptCompile,\n        /// <summary>\n        ///     A script was terminated due to a request to suspend a runtime.\n        /// </summary>\n        JsErrorScriptTerminated,\n        /// <summary>\n        ///     A script was terminated because it tried to use <c>eval</c> or <c>function</c> and eval\n        ///     was disabled.\n        /// </summary>\n        JsErrorScriptEvalDisabled,\n\n        /// <summary>\n        ///     Category of errors that are fatal and signify failure of the engine.\n        /// </summary>\n        JsErrorCategoryFatal = 0x40000,\n        /// <summary>\n        ///     A fatal error in the engine has occurred.\n        /// </summary>\n        JsErrorFatal,\n        /// <summary>\n        ///     A hosting API was called with object created on different javascript runtime.\n        /// </summary>\n        JsErrorWrongRuntime,\n\n        /// <summary>\n        ///     Category of errors that are related to failures during diagnostic operations.\n        /// </summary>\n        JsErrorCategoryDiagError = 0x50000,\n        /// <summary>\n        ///     The object for which the debugging API was called was not found\n        /// </summary>\n        JsErrorDiagAlreadyInDebugMode,\n        /// <summary>\n        ///     The debugging API can only be called when VM is in debug mode\n        /// </summary>\n        JsErrorDiagNotInDebugMode,\n        /// <summary>\n        ///     The debugging API can only be called when VM is at a break\n        /// </summary>\n        JsErrorDiagNotAtBreak,\n        /// <summary>\n        ///     Debugging API was called with an invalid handle.\n        /// </summary>\n        JsErrorDiagInvalidHandle,\n        /// <summary>\n        ///     The object for which the debugging API was called was not found\n        /// </summary>\n        JsErrorDiagObjectNotFound,\n        /// <summary>\n        ///     VM was unable to perform the request action\n        /// </summary>\n        JsErrorDiagUnableToPerformAction,\n    } JsErrorCode;\n\n    /// <summary>\n    ///     A handle to a Chakra runtime.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     Each Chakra runtime has its own independent execution engine, JIT compiler, and garbage\n    ///     collected heap. As such, each runtime is completely isolated from other runtimes.\n    ///     </para>\n    ///     <para>\n    ///     Runtimes can be used on any thread, but only one thread can call into a runtime at any\n    ///     time.\n    ///     </para>\n    ///     <para>\n    ///     NOTE: A <c>JsRuntimeHandle</c>, unlike other object references in the Chakra hosting API,\n    ///     is not garbage collected since it contains the garbage collected heap itself. A runtime\n    ///     will continue to exist until <c>JsDisposeRuntime</c> is called.\n    ///     </para>\n    /// </remarks>\n    typedef void *JsRuntimeHandle;\n\n    /// <summary>\n    ///     An invalid runtime handle.\n    /// </summary>\n#ifdef __cplusplus\n    const JsRuntimeHandle JS_INVALID_RUNTIME_HANDLE = 0;\n#else\n    #define JS_INVALID_RUNTIME_HANDLE (JsRuntimeHandle)0\n#endif\n\n    /// <summary>\n    ///     A reference to an object owned by the Chakra garbage collector.\n    /// </summary>\n    /// <remarks>\n    ///     A Chakra runtime will automatically track <c>JsRef</c> references as long as they are\n    ///     stored in local variables or in parameters (i.e. on the stack). Storing a <c>JsRef</c>\n    ///     somewhere other than on the stack requires calling <c>JsAddRef</c> and <c>JsRelease</c> to\n    ///     manage the lifetime of the object, otherwise the garbage collector may free the object\n    ///     while it is still in use.\n    /// </remarks>\n    typedef void *JsRef;\n\n    /// <summary>\n    ///     An invalid reference.\n    /// </summary>\n#ifdef __cplusplus\n    const JsRef JS_INVALID_REFERENCE = 0;\n#else\n    #define JS_INVALID_REFERENCE (JsRef)0\n#endif\n\n    /// <summary>\n    ///     A reference to a script context.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     Each script context contains its own global object, distinct from the global object in\n    ///     other script contexts.\n    ///     </para>\n    ///     <para>\n    ///     Many Chakra hosting APIs require an \"active\" script context, which can be set using\n    ///     <c>JsSetCurrentContext</c>. Chakra hosting APIs that require a current context to be set\n    ///     will note that explicitly in their documentation.\n    ///     </para>\n    /// </remarks>\n    typedef JsRef JsContextRef;\n\n    /// <summary>\n    ///     A reference to a JavaScript value.\n    /// </summary>\n    /// <remarks>\n    ///     A JavaScript value is one of the following types of values: undefined, null, Boolean,\n    ///     string, number, or object.\n    /// </remarks>\n    typedef JsRef JsValueRef;\n\n    /// <summary>\n    ///     A cookie that identifies a script for debugging purposes.\n    /// </summary>\n    typedef ChakraCookie JsSourceContext;\n\n    /// <summary>\n    ///     An empty source context.\n    /// </summary>\n#ifdef __cplusplus\n    const JsSourceContext JS_SOURCE_CONTEXT_NONE = (JsSourceContext)-1;\n#else\n    #define JS_SOURCE_CONTEXT_NONE (JsSourceContext)-1\n#endif\n\n    /// <summary>\n    ///     A property identifier.\n    /// </summary>\n    /// <remarks>\n    ///     Property identifiers are used to refer to properties of JavaScript objects instead of using\n    ///     strings.\n    /// </remarks>\n    typedef JsRef JsPropertyIdRef;\n\n    /// <summary>\n    ///     Attributes of a runtime.\n    /// </summary>\n    typedef enum _JsRuntimeAttributes\n    {\n        /// <summary>\n        ///     No special attributes.\n        /// </summary>\n        JsRuntimeAttributeNone = 0x00000000,\n        /// <summary>\n        ///     The runtime will not do any work (such as garbage collection) on background threads.\n        /// </summary>\n        JsRuntimeAttributeDisableBackgroundWork = 0x00000001,\n        /// <summary>\n        ///     The runtime should support reliable script interruption. This increases the number of\n        ///     places where the runtime will check for a script interrupt request at the cost of a\n        ///     small amount of runtime performance.\n        /// </summary>\n        JsRuntimeAttributeAllowScriptInterrupt = 0x00000002,\n        /// <summary>\n        ///     Host will call <c>JsIdle</c>, so enable idle processing. Otherwise, the runtime will\n        ///     manage memory slightly more aggressively.\n        /// </summary>\n        JsRuntimeAttributeEnableIdleProcessing = 0x00000004,\n        /// <summary>\n        ///     Runtime will not generate native code.\n        /// </summary>\n        JsRuntimeAttributeDisableNativeCodeGeneration = 0x00000008,\n        /// <summary>\n        ///     Using <c>eval</c> or <c>function</c> constructor will throw an exception.\n        /// </summary>\n        JsRuntimeAttributeDisableEval = 0x00000010,\n        /// <summary>\n        ///     Runtime will enable all experimental features.\n        /// </summary>\n        JsRuntimeAttributeEnableExperimentalFeatures = 0x00000020,\n        /// <summary>\n        ///     Calling <c>JsSetException</c> will also dispatch the exception to the script debugger\n        ///     (if any) giving the debugger a chance to break on the exception.\n        /// </summary>\n        JsRuntimeAttributeDispatchSetExceptionsToDebugger = 0x00000040,\n        /// <summary>\n        ///     Disable Failfast fatal error on OOM\n        /// </summary>\n        JsRuntimeAttributeDisableFatalOnOOM = 0x00000080,\n        /// <summary>\n        ///     Runtime will not allocate executable code pages\n        ///     This also implies that Native Code generation will be turned off\n        ///     Note that this will break JavaScript stack decoding in tools\n        //      like WPA since they rely on allocation of unique thunks to\n        //      interpret each function and allocation of those thunks will be\n        //      disabled as well\n        /// </summary>\n        JsRuntimeAttributeDisableExecutablePageAllocation = 0x00000100,\n\n    } JsRuntimeAttributes;\n\n    /// <summary>\n    ///     The type of a typed JavaScript array.\n    /// </summary>\n    typedef enum _JsTypedArrayType\n    {\n        /// <summary>\n        ///     An int8 array.\n        /// </summary>\n        JsArrayTypeInt8,\n        /// <summary>\n        ///     An uint8 array.\n        /// </summary>\n        JsArrayTypeUint8,\n        /// <summary>\n        ///     An uint8 clamped array.\n        /// </summary>\n        JsArrayTypeUint8Clamped,\n        /// <summary>\n        ///     An int16 array.\n        /// </summary>\n        JsArrayTypeInt16,\n        /// <summary>\n        ///     An uint16 array.\n        /// </summary>\n        JsArrayTypeUint16,\n        /// <summary>\n        ///     An int32 array.\n        /// </summary>\n        JsArrayTypeInt32,\n        /// <summary>\n        ///     An uint32 array.\n        /// </summary>\n        JsArrayTypeUint32,\n        /// <summary>\n        ///     A float32 array.\n        /// </summary>\n        JsArrayTypeFloat32,\n        /// <summary>\n        ///     A float64 array.\n        /// </summary>\n        JsArrayTypeFloat64\n    } JsTypedArrayType;\n\n    /// <summary>\n    ///     Allocation callback event type.\n    /// </summary>\n    typedef enum _JsMemoryEventType\n    {\n        /// <summary>\n        ///     Indicates a request for memory allocation.\n        /// </summary>\n        JsMemoryAllocate = 0,\n        /// <summary>\n        ///     Indicates a memory freeing event.\n        /// </summary>\n        JsMemoryFree = 1,\n        /// <summary>\n        ///     Indicates a failed allocation event.\n        /// </summary>\n        JsMemoryFailure = 2\n    } JsMemoryEventType;\n\n    /// <summary>\n    ///     Attribute mask for JsParseScriptWithAttributes\n    /// </summary>\n    typedef enum _JsParseScriptAttributes {\n        /// <summary>\n        ///     Default attribute\n        /// </summary>\n        JsParseScriptAttributeNone = 0x0,\n        /// <summary>\n        ///     Specified script is internal and non-user code. Hidden from debugger\n        /// </summary>\n        JsParseScriptAttributeLibraryCode = 0x1,\n        /// <summary>\n        ///     ChakraCore assumes ExternalArrayBuffer is Utf8 by default.\n        ///     This one needs to be set for Utf16\n        /// </summary>\n        JsParseScriptAttributeArrayBufferIsUtf16Encoded = 0x2,\n    } JsParseScriptAttributes;\n\n    /// <summary>\n    ///     Type enumeration of a JavaScript property\n    /// </summary>\n    typedef enum _JsPropertyIdType {\n        /// <summary>\n        ///     Type enumeration of a JavaScript string property\n        /// </summary>\n        JsPropertyIdTypeString,\n        /// <summary>\n        ///     Type enumeration of a JavaScript symbol property\n        /// </summary>\n        JsPropertyIdTypeSymbol\n    } JsPropertyIdType;\n\n    /// <summary>\n    ///     The JavaScript type of a JsValueRef.\n    /// </summary>\n    typedef enum _JsValueType\n    {\n        /// <summary>\n        ///     The value is the <c>undefined</c> value.\n        /// </summary>\n        JsUndefined = 0,\n        /// <summary>\n        ///     The value is the <c>null</c> value.\n        /// </summary>\n        JsNull = 1,\n        /// <summary>\n        ///     The value is a JavaScript number value.\n        /// </summary>\n        JsNumber = 2,\n        /// <summary>\n        ///     The value is a JavaScript string value.\n        /// </summary>\n        JsString = 3,\n        /// <summary>\n        ///     The value is a JavaScript Boolean value.\n        /// </summary>\n        JsBoolean = 4,\n        /// <summary>\n        ///     The value is a JavaScript object value.\n        /// </summary>\n        JsObject = 5,\n        /// <summary>\n        ///     The value is a JavaScript function object value.\n        /// </summary>\n        JsFunction = 6,\n        /// <summary>\n        ///     The value is a JavaScript error object value.\n        /// </summary>\n        JsError = 7,\n        /// <summary>\n        ///     The value is a JavaScript array object value.\n        /// </summary>\n        JsArray = 8,\n        /// <summary>\n        ///     The value is a JavaScript symbol value.\n        /// </summary>\n        JsSymbol = 9,\n        /// <summary>\n        ///     The value is a JavaScript ArrayBuffer object value.\n        /// </summary>\n        JsArrayBuffer = 10,\n        /// <summary>\n        ///     The value is a JavaScript typed array object value.\n        /// </summary>\n        JsTypedArray = 11,\n        /// <summary>\n        ///     The value is a JavaScript DataView object value.\n        /// </summary>\n        JsDataView = 12,\n    } JsValueType;\n\n    /// <summary>\n    ///     User implemented callback routine for memory allocation events\n    /// </summary>\n    /// <remarks>\n    ///     Use <c>JsSetRuntimeMemoryAllocationCallback</c> to register this callback.\n    /// </remarks>\n    /// <param name=\"callbackState\">\n    ///     The state passed to <c>JsSetRuntimeMemoryAllocationCallback</c>.\n    /// </param>\n    /// <param name=\"allocationEvent\">The type of type allocation event.</param>\n    /// <param name=\"allocationSize\">The size of the allocation.</param>\n    /// <returns>\n    ///     For the <c>JsMemoryAllocate</c> event, returning <c>true</c> allows the runtime to continue\n    ///     with the allocation. Returning false indicates the allocation request is rejected. The\n    ///     return value is ignored for other allocation events.\n    /// </returns>\n    typedef bool (CHAKRA_CALLBACK * JsMemoryAllocationCallback)(_In_opt_ void *callbackState, _In_ JsMemoryEventType allocationEvent, _In_ size_t allocationSize);\n\n    /// <summary>\n    ///     A callback called before collection.\n    /// </summary>\n    /// <remarks>\n    ///     Use <c>JsSetBeforeCollectCallback</c> to register this callback.\n    /// </remarks>\n    /// <param name=\"callbackState\">The state passed to <c>JsSetBeforeCollectCallback</c>.</param>\n    typedef void (CHAKRA_CALLBACK *JsBeforeCollectCallback)(_In_opt_ void *callbackState);\n\n    /// <summary>\n    ///     A callback called before collecting an object.\n    /// </summary>\n    /// <remarks>\n    ///     Use <c>JsSetObjectBeforeCollectCallback</c> to register this callback.\n    /// </remarks>\n    /// <param name=\"ref\">The object to be collected.</param>\n    /// <param name=\"callbackState\">The state passed to <c>JsSetObjectBeforeCollectCallback</c>.</param>\n    typedef void (CHAKRA_CALLBACK *JsObjectBeforeCollectCallback)(_In_ JsRef ref, _In_opt_ void *callbackState);\n\n    /// <summary>\n    ///     A background work item callback.\n    /// </summary>\n    /// <remarks>\n    ///     This is passed to the host's thread service (if provided) to allow the host to\n    ///     invoke the work item callback on the background thread of its choice.\n    /// </remarks>\n    /// <param name=\"callbackState\">Data argument passed to the thread service.</param>\n    typedef void (CHAKRA_CALLBACK *JsBackgroundWorkItemCallback)(_In_opt_ void *callbackState);\n\n    /// <summary>\n    ///     A thread service callback.\n    /// </summary>\n    /// <remarks>\n    ///     The host can specify a background thread service when calling <c>JsCreateRuntime</c>. If\n    ///     specified, then background work items will be passed to the host using this callback. The\n    ///     host is expected to either begin executing the background work item immediately and return\n    ///     true or return false and the runtime will handle the work item in-thread.\n    /// </remarks>\n    /// <param name=\"callback\">The callback for the background work item.</param>\n    /// <param name=\"callbackState\">The data argument to be passed to the callback.</param>\n    typedef bool (CHAKRA_CALLBACK *JsThreadServiceCallback)(_In_ JsBackgroundWorkItemCallback callback, _In_opt_ void *callbackState);\n\n    /// <summary>\n    ///     Called by the runtime when it is finished with all resources related to the script execution.\n    ///     The caller should free the source if loaded, the byte code, and the context at this time.\n    /// </summary>\n    /// <param name=\"sourceContext\">The context passed to Js[Parse|Run]SerializedScriptWithCallback</param>\n    typedef void (CHAKRA_CALLBACK * JsSerializedScriptUnloadCallback)(_In_ JsSourceContext sourceContext);\n\n    /// <summary>\n    ///     A finalizer callback.\n    /// </summary>\n    /// <param name=\"data\">\n    ///     The external data that was passed in when creating the object being finalized.\n    /// </param>\n    typedef void (CHAKRA_CALLBACK *JsFinalizeCallback)(_In_opt_ void *data);\n\n    /// <summary>\n    ///     A function callback.\n    /// </summary>\n    /// <param name=\"callee\">\n    ///     A function object that represents the function being invoked.\n    /// </param>\n    /// <param name=\"isConstructCall\">Indicates whether this is a regular call or a 'new' call.</param>\n    /// <param name=\"arguments\">The arguments to the call.</param>\n    /// <param name=\"argumentCount\">The number of arguments.</param>\n    /// <param name=\"callbackState\">\n    ///     The state passed to <c>JsCreateFunction</c>.\n    /// </param>\n    /// <returns>The result of the call, if any.</returns>\n    typedef _Ret_maybenull_ JsValueRef(CHAKRA_CALLBACK * JsNativeFunction)(_In_ JsValueRef callee, _In_ bool isConstructCall, _In_ JsValueRef *arguments, _In_ unsigned short argumentCount, _In_opt_ void *callbackState);\n\n    /// <summary>\n    ///     A promise continuation callback.\n    /// </summary>\n    /// <remarks>\n    ///     The host can specify a promise continuation callback in <c>JsSetPromiseContinuationCallback</c>. If\n    ///     a script creates a task to be run later, then the promise continuation callback will be called with\n    ///     the task and the task should be put in a FIFO queue, to be run when the current script is\n    ///     done executing.\n    /// </remarks>\n    /// <param name=\"task\">The task, represented as a JavaScript function.</param>\n    /// <param name=\"callbackState\">The data argument to be passed to the callback.</param>\n    typedef void (CHAKRA_CALLBACK *JsPromiseContinuationCallback)(_In_ JsValueRef task, _In_opt_ void *callbackState);\n\n    /// <summary>\n    ///     Creates a new runtime.\n    /// </summary>\n    /// <param name=\"attributes\">The attributes of the runtime to be created.</param>\n    /// <param name=\"threadService\">The thread service for the runtime. Can be null.</param>\n    /// <param name=\"runtime\">The runtime created.</param>\n    /// <remarks>In the edge-mode binary, chakra.dll, this function lacks the <c>runtimeVersion</c>\n    /// parameter (compare to jsrt9.h).</remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateRuntime(\n            _In_ JsRuntimeAttributes attributes,\n            _In_opt_ JsThreadServiceCallback threadService,\n            _Out_ JsRuntimeHandle *runtime);\n\n    /// <summary>\n    ///     Performs a full garbage collection.\n    /// </summary>\n    /// <param name=\"runtime\">The runtime in which the garbage collection will be performed.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCollectGarbage(\n            _In_ JsRuntimeHandle runtime);\n\n    /// <summary>\n    ///     Disposes a runtime.\n    /// </summary>\n    /// <remarks>\n    ///     Once a runtime has been disposed, all resources owned by it are invalid and cannot be used.\n    ///     If the runtime is active (i.e. it is set to be current on a particular thread), it cannot\n    ///     be disposed.\n    /// </remarks>\n    /// <param name=\"runtime\">The runtime to dispose.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsDisposeRuntime(\n            _In_ JsRuntimeHandle runtime);\n\n    /// <summary>\n    ///     Gets the current memory usage for a runtime.\n    /// </summary>\n    /// <remarks>\n    ///     Memory usage can be always be retrieved, regardless of whether or not the runtime is active\n    ///     on another thread.\n    /// </remarks>\n    /// <param name=\"runtime\">The runtime whose memory usage is to be retrieved.</param>\n    /// <param name=\"memoryUsage\">The runtime's current memory usage, in bytes.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetRuntimeMemoryUsage(\n            _In_ JsRuntimeHandle runtime,\n            _Out_ size_t *memoryUsage);\n\n    /// <summary>\n    ///     Gets the current memory limit for a runtime.\n    /// </summary>\n    /// <remarks>\n    ///     The memory limit of a runtime can be always be retrieved, regardless of whether or not the\n    ///     runtime is active on another thread.\n    /// </remarks>\n    /// <param name=\"runtime\">The runtime whose memory limit is to be retrieved.</param>\n    /// <param name=\"memoryLimit\">\n    ///     The runtime's current memory limit, in bytes, or -1 if no limit has been set.\n    /// </param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetRuntimeMemoryLimit(\n            _In_ JsRuntimeHandle runtime,\n            _Out_ size_t *memoryLimit);\n\n    /// <summary>\n    ///     Sets the current memory limit for a runtime.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     A memory limit will cause any operation which exceeds the limit to fail with an \"out of\n    ///     memory\" error. Setting a runtime's memory limit to -1 means that the runtime has no memory\n    ///     limit. New runtimes  default to having no memory limit. If the new memory limit exceeds\n    ///     current usage, the call will succeed and any future allocations in this runtime will fail\n    ///     until the runtime's memory usage drops below the limit.\n    ///     </para>\n    ///     <para>\n    ///     A runtime's memory limit can be always be set, regardless of whether or not the runtime is\n    ///     active on another thread.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"runtime\">The runtime whose memory limit is to be set.</param>\n    /// <param name=\"memoryLimit\">\n    ///     The new runtime memory limit, in bytes, or -1 for no memory limit.\n    /// </param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetRuntimeMemoryLimit(\n            _In_ JsRuntimeHandle runtime,\n            _In_ size_t memoryLimit);\n\n    /// <summary>\n    ///     Sets a memory allocation callback for specified runtime\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     Registering a memory allocation callback will cause the runtime to call back to the host\n    ///     whenever it acquires memory from, or releases memory to, the OS. The callback routine is\n    ///     called before the runtime memory manager allocates a block of memory. The allocation will\n    ///     be rejected if the callback returns false. The runtime memory manager will also invoke the\n    ///     callback routine after freeing a block of memory, as well as after allocation failures.\n    ///     </para>\n    ///     <para>\n    ///     The callback is invoked on the current runtime execution thread, therefore execution is\n    ///     blocked until the callback completes.\n    ///     </para>\n    ///     <para>\n    ///     The return value of the callback is not stored; previously rejected allocations will not\n    ///     prevent the runtime from invoking the callback again later for new memory allocations.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"runtime\">The runtime for which to register the allocation callback.</param>\n    /// <param name=\"callbackState\">\n    ///     User provided state that will be passed back to the callback.\n    /// </param>\n    /// <param name=\"allocationCallback\">\n    ///     Memory allocation callback to be called for memory allocation events.\n    /// </param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetRuntimeMemoryAllocationCallback(\n            _In_ JsRuntimeHandle runtime,\n            _In_opt_ void *callbackState,\n            _In_ JsMemoryAllocationCallback allocationCallback);\n\n    /// <summary>\n    ///     Sets a callback function that is called by the runtime before garbage collection.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     The callback is invoked on the current runtime execution thread, therefore execution is\n    ///     blocked until the callback completes.\n    ///     </para>\n    ///     <para>\n    ///     The callback can be used by hosts to prepare for garbage collection. For example, by\n    ///     releasing unnecessary references on Chakra objects.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"runtime\">The runtime for which to register the allocation callback.</param>\n    /// <param name=\"callbackState\">\n    ///     User provided state that will be passed back to the callback.\n    /// </param>\n    /// <param name=\"beforeCollectCallback\">The callback function being set.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetRuntimeBeforeCollectCallback(\n            _In_ JsRuntimeHandle runtime,\n            _In_opt_ void *callbackState,\n            _In_ JsBeforeCollectCallback beforeCollectCallback);\n\n    /// <summary>\n    ///     Adds a reference to a garbage collected object.\n    /// </summary>\n    /// <remarks>\n    ///     This only needs to be called on <c>JsRef</c> handles that are not going to be stored\n    ///     somewhere on the stack. Calling <c>JsAddRef</c> ensures that the object the <c>JsRef</c>\n    ///     refers to will not be freed until <c>JsRelease</c> is called.\n    /// </remarks>\n    /// <param name=\"ref\">The object to add a reference to.</param>\n    /// <param name=\"count\">The object's new reference count (can pass in null).</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsAddRef(\n            _In_ JsRef ref,\n            _Out_opt_ unsigned int *count);\n\n    /// <summary>\n    ///     Releases a reference to a garbage collected object.\n    /// </summary>\n    /// <remarks>\n    ///     Removes a reference to a <c>JsRef</c> handle that was created by <c>JsAddRef</c>.\n    /// </remarks>\n    /// <param name=\"ref\">The object to add a reference to.</param>\n    /// <param name=\"count\">The object's new reference count (can pass in null).</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsRelease(\n            _In_ JsRef ref,\n            _Out_opt_ unsigned int *count);\n\n    /// <summary>\n    ///     Sets a callback function that is called by the runtime before garbage collection of\n    ///     an object.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     The callback is invoked on the current runtime execution thread, therefore execution is\n    ///     blocked until the callback completes.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"ref\">The object for which to register the callback.</param>\n    /// <param name=\"callbackState\">\n    ///     User provided state that will be passed back to the callback.\n    /// </param>\n    /// <param name=\"objectBeforeCollectCallback\">The callback function being set. Use null to clear\n    ///     previously registered callback.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetObjectBeforeCollectCallback(\n            _In_ JsRef ref,\n            _In_opt_ void *callbackState,\n            _In_ JsObjectBeforeCollectCallback objectBeforeCollectCallback);\n\n    /// <summary>\n    ///     Creates a script context for running scripts.\n    /// </summary>\n    /// <remarks>\n    ///     Each script context has its own global object that is isolated from all other script\n    ///     contexts.\n    /// </remarks>\n    /// <param name=\"runtime\">The runtime the script context is being created in.</param>\n    /// <param name=\"newContext\">The created script context.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateContext(\n            _In_ JsRuntimeHandle runtime,\n            _Out_ JsContextRef *newContext);\n\n    /// <summary>\n    ///     Gets the current script context on the thread.\n    /// </summary>\n    /// <param name=\"currentContext\">\n    ///     The current script context on the thread, null if there is no current script context.\n    /// </param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetCurrentContext(\n            _Out_ JsContextRef *currentContext);\n\n    /// <summary>\n    ///     Sets the current script context on the thread.\n    /// </summary>\n    /// <param name=\"context\">The script context to make current.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetCurrentContext(\n            _In_ JsContextRef context);\n\n    /// <summary>\n    ///     Gets the script context that the object belongs to.\n    /// </summary>\n    /// <param name=\"object\">The object to get the context from.</param>\n    /// <param name=\"context\">The context the object belongs to.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetContextOfObject(\n            _In_ JsValueRef object,\n            _Out_ JsContextRef *context);\n\n    /// <summary>\n    ///     Gets the internal data set on JsrtContext.\n    /// </summary>\n    /// <param name=\"context\">The context to get the data from.</param>\n    /// <param name=\"data\">The pointer to the data where data will be returned.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetContextData(\n            _In_ JsContextRef context,\n            _Out_ void **data);\n\n    /// <summary>\n    ///     Sets the internal data of JsrtContext.\n    /// </summary>\n    /// <param name=\"context\">The context to set the data to.</param>\n    /// <param name=\"data\">The pointer to the data to be set.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetContextData(\n            _In_ JsContextRef context,\n            _In_ void *data);\n\n    /// <summary>\n    ///     Gets the runtime that the context belongs to.\n    /// </summary>\n    /// <param name=\"context\">The context to get the runtime from.</param>\n    /// <param name=\"runtime\">The runtime the context belongs to.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetRuntime(\n            _In_ JsContextRef context,\n            _Out_ JsRuntimeHandle *runtime);\n\n    /// <summary>\n    ///     Tells the runtime to do any idle processing it need to do.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     If idle processing has been enabled for the current runtime, calling <c>JsIdle</c> will\n    ///     inform the current runtime that the host is idle and that the runtime can perform\n    ///     memory cleanup tasks.\n    ///     </para>\n    ///     <para>\n    ///     <c>JsIdle</c> can also return the number of system ticks until there will be more idle work\n    ///     for the runtime to do. Calling <c>JsIdle</c> before this number of ticks has passed will do\n    ///     no work.\n    ///     </para>\n    ///     <para>\n    ///     Requires an active script context.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"nextIdleTick\">\n    ///     The next system tick when there will be more idle work to do. Can be null. Returns the\n    ///     maximum number of ticks if there no upcoming idle work to do.\n    /// </param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsIdle(\n            _Out_opt_ unsigned int *nextIdleTick);\n\n    /// <summary>\n    ///     Gets the symbol associated with the property ID.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     Requires an active script context.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"propertyId\">The property ID to get the symbol of.</param>\n    /// <param name=\"symbol\">The symbol associated with the property ID.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetSymbolFromPropertyId(\n            _In_ JsPropertyIdRef propertyId,\n            _Out_ JsValueRef *symbol);\n\n    /// <summary>\n    ///     Gets the type of property\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     Requires an active script context.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"propertyId\">The property ID to get the type of.</param>\n    /// <param name=\"propertyIdType\">The JsPropertyIdType of the given property ID</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetPropertyIdType(\n            _In_ JsPropertyIdRef propertyId,\n            _Out_ JsPropertyIdType* propertyIdType);\n\n\n    /// <summary>\n    ///     Gets the property ID associated with the symbol.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     Property IDs are specific to a context and cannot be used across contexts.\n    ///     </para>\n    ///     <para>\n    ///     Requires an active script context.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"symbol\">\n    ///     The symbol whose property ID is being retrieved.\n    /// </param>\n    /// <param name=\"propertyId\">The property ID for the given symbol.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetPropertyIdFromSymbol(\n            _In_ JsValueRef symbol,\n            _Out_ JsPropertyIdRef *propertyId);\n\n    /// <summary>\n    ///     Creates a Javascript symbol.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"description\">The string description of the symbol. Can be null.</param>\n    /// <param name=\"result\">The new symbol.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateSymbol(\n            _In_ JsValueRef description,\n            _Out_ JsValueRef *result);\n\n    /// <summary>\n    ///     Gets the list of all symbol properties on the object.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object from which to get the property symbols.</param>\n    /// <param name=\"propertySymbols\">An array of property symbols.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetOwnPropertySymbols(\n            _In_ JsValueRef object,\n            _Out_ JsValueRef *propertySymbols);\n\n    /// <summary>\n    ///     Gets the value of <c>undefined</c> in the current script context.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"undefinedValue\">The <c>undefined</c> value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetUndefinedValue(\n            _Out_ JsValueRef *undefinedValue);\n\n    /// <summary>\n    ///     Gets the value of <c>null</c> in the current script context.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"nullValue\">The <c>null</c> value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetNullValue(\n            _Out_ JsValueRef *nullValue);\n\n    /// <summary>\n    ///     Gets the value of <c>true</c> in the current script context.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"trueValue\">The <c>true</c> value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetTrueValue(\n            _Out_ JsValueRef *trueValue);\n\n    /// <summary>\n    ///     Gets the value of <c>false</c> in the current script context.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"falseValue\">The <c>false</c> value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetFalseValue(\n            _Out_ JsValueRef *falseValue);\n\n    /// <summary>\n    ///     Creates a Boolean value from a <c>bool</c> value.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"value\">The value to be converted.</param>\n    /// <param name=\"booleanValue\">The converted value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsBoolToBoolean(\n            _In_ bool value,\n            _Out_ JsValueRef *booleanValue);\n\n    /// <summary>\n    ///     Retrieves the <c>bool</c> value of a Boolean value.\n    /// </summary>\n    /// <param name=\"value\">The value to be converted.</param>\n    /// <param name=\"boolValue\">The converted value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsBooleanToBool(\n            _In_ JsValueRef value,\n            _Out_ bool *boolValue);\n\n    /// <summary>\n    ///     Converts the value to Boolean using standard JavaScript semantics.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"value\">The value to be converted.</param>\n    /// <param name=\"booleanValue\">The converted value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsConvertValueToBoolean(\n            _In_ JsValueRef value,\n            _Out_ JsValueRef *booleanValue);\n\n\n    /// <summary>\n    ///     Gets the JavaScript type of a JsValueRef.\n    /// </summary>\n    /// <param name=\"value\">The value whose type is to be returned.</param>\n    /// <param name=\"type\">The type of the value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetValueType(\n            _In_ JsValueRef value,\n            _Out_ JsValueType *type);\n\n    /// <summary>\n    ///     Creates a number value from a <c>double</c> value.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"doubleValue\">The <c>double</c> to convert to a number value.</param>\n    /// <param name=\"value\">The new number value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsDoubleToNumber(\n            _In_ double doubleValue,\n            _Out_ JsValueRef *value);\n\n    /// <summary>\n    ///     Creates a number value from an <c>int</c> value.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"intValue\">The <c>int</c> to convert to a number value.</param>\n    /// <param name=\"value\">The new number value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsIntToNumber(\n            _In_ int intValue,\n            _Out_ JsValueRef *value);\n\n    /// <summary>\n    ///     Retrieves the <c>double</c> value of a number value.\n    /// </summary>\n    /// <remarks>\n    ///     This function retrieves the value of a number value. It will fail with\n    ///     <c>JsErrorInvalidArgument</c> if the type of the value is not number.\n    /// </remarks>\n    /// <param name=\"value\">The number value to convert to a <c>double</c> value.</param>\n    /// <param name=\"doubleValue\">The <c>double</c> value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsNumberToDouble(\n            _In_ JsValueRef value,\n            _Out_ double *doubleValue);\n\n    /// <summary>\n    ///     Retrieves the <c>int</c> value of a number value.\n    /// </summary>\n    /// <remarks>\n    ///     This function retrieves the value of a number value and converts to an <c>int</c> value.\n    ///     It will fail with <c>JsErrorInvalidArgument</c> if the type of the value is not number.\n    /// </remarks>\n    /// <param name=\"value\">The number value to convert to an <c>int</c> value.</param>\n    /// <param name=\"intValue\">The <c>int</c> value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsNumberToInt(\n            _In_ JsValueRef value,\n            _Out_ int *intValue);\n\n    /// <summary>\n    ///     Converts the value to number using standard JavaScript semantics.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"value\">The value to be converted.</param>\n    /// <param name=\"numberValue\">The converted value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsConvertValueToNumber(\n            _In_ JsValueRef value,\n            _Out_ JsValueRef *numberValue);\n\n    /// <summary>\n    ///     Gets the length of a string value.\n    /// </summary>\n    /// <param name=\"stringValue\">The string value to get the length of.</param>\n    /// <param name=\"length\">The length of the string.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetStringLength(\n            _In_ JsValueRef stringValue,\n            _Out_ int *length);\n\n    /// <summary>\n    ///     Converts the value to string using standard JavaScript semantics.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"value\">The value to be converted.</param>\n    /// <param name=\"stringValue\">The converted value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsConvertValueToString(\n            _In_ JsValueRef value,\n            _Out_ JsValueRef *stringValue);\n\n    /// <summary>\n    ///     Gets the global object in the current script context.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"globalObject\">The global object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetGlobalObject(\n            _Out_ JsValueRef *globalObject);\n\n    /// <summary>\n    ///     Creates a new object.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The new object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateObject(\n            _Out_ JsValueRef *object);\n\n    /// <summary>\n    ///     Creates a new object that stores some external data.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"data\">External data that the object will represent. May be null.</param>\n    /// <param name=\"finalizeCallback\">\n    ///     A callback for when the object is finalized. May be null.\n    /// </param>\n    /// <param name=\"object\">The new object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateExternalObject(\n            _In_opt_ void *data,\n            _In_opt_ JsFinalizeCallback finalizeCallback,\n            _Out_ JsValueRef *object);\n\n    /// <summary>\n    ///     Converts the value to object using standard JavaScript semantics.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"value\">The value to be converted.</param>\n    /// <param name=\"object\">The converted value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsConvertValueToObject(\n            _In_ JsValueRef value,\n            _Out_ JsValueRef *object);\n\n    /// <summary>\n    ///     Returns the prototype of an object.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object whose prototype is to be returned.</param>\n    /// <param name=\"prototypeObject\">The object's prototype.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetPrototype(\n            _In_ JsValueRef object,\n            _Out_ JsValueRef *prototypeObject);\n\n    /// <summary>\n    ///     Sets the prototype of an object.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object whose prototype is to be changed.</param>\n    /// <param name=\"prototypeObject\">The object's new prototype.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetPrototype(\n            _In_ JsValueRef object,\n            _In_ JsValueRef prototypeObject);\n\n    /// <summary>\n    ///     Performs JavaScript \"instanceof\" operator test.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object to test.</param>\n    /// <param name=\"constructor\">The constructor function to test against.</param>\n    /// <param name=\"result\">Whether \"object instanceof constructor\" is true.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsInstanceOf(\n            _In_ JsValueRef object,\n            _In_ JsValueRef constructor,\n            _Out_ bool *result);\n\n    /// <summary>\n    ///     Returns a value that indicates whether an object is extensible or not.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object to test.</param>\n    /// <param name=\"value\">Whether the object is extensible or not.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetExtensionAllowed(\n            _In_ JsValueRef object,\n            _Out_ bool *value);\n\n    /// <summary>\n    ///     Makes an object non-extensible.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object to make non-extensible.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsPreventExtension(\n            _In_ JsValueRef object);\n\n    /// <summary>\n    ///     Gets an object's property.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object that contains the property.</param>\n    /// <param name=\"propertyId\">The ID of the property.</param>\n    /// <param name=\"value\">The value of the property.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetProperty(\n            _In_ JsValueRef object,\n            _In_ JsPropertyIdRef propertyId,\n            _Out_ JsValueRef *value);\n\n    /// <summary>\n    ///     Gets a property descriptor for an object's own property.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object that has the property.</param>\n    /// <param name=\"propertyId\">The ID of the property.</param>\n    /// <param name=\"propertyDescriptor\">The property descriptor.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetOwnPropertyDescriptor(\n            _In_ JsValueRef object,\n            _In_ JsPropertyIdRef propertyId,\n            _Out_ JsValueRef *propertyDescriptor);\n\n    /// <summary>\n    ///     Gets the list of all properties on the object.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object from which to get the property names.</param>\n    /// <param name=\"propertyNames\">An array of property names.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetOwnPropertyNames(\n            _In_ JsValueRef object,\n            _Out_ JsValueRef *propertyNames);\n\n    /// <summary>\n    ///     Puts an object's property.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object that contains the property.</param>\n    /// <param name=\"propertyId\">The ID of the property.</param>\n    /// <param name=\"value\">The new value of the property.</param>\n    /// <param name=\"useStrictRules\">The property set should follow strict mode rules.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetProperty(\n            _In_ JsValueRef object,\n            _In_ JsPropertyIdRef propertyId,\n            _In_ JsValueRef value,\n            _In_ bool useStrictRules);\n\n    /// <summary>\n    ///     Determines whether an object has a property.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object that may contain the property.</param>\n    /// <param name=\"propertyId\">The ID of the property.</param>\n    /// <param name=\"hasProperty\">Whether the object (or a prototype) has the property.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsHasProperty(\n            _In_ JsValueRef object,\n            _In_ JsPropertyIdRef propertyId,\n            _Out_ bool *hasProperty);\n\n    /// <summary>\n    ///     Deletes an object's property.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object that contains the property.</param>\n    /// <param name=\"propertyId\">The ID of the property.</param>\n    /// <param name=\"useStrictRules\">The property set should follow strict mode rules.</param>\n    /// <param name=\"result\">Whether the property was deleted.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsDeleteProperty(\n            _In_ JsValueRef object,\n            _In_ JsPropertyIdRef propertyId,\n            _In_ bool useStrictRules,\n            _Out_ JsValueRef *result);\n\n    /// <summary>\n    ///     Defines a new object's own property from a property descriptor.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object that has the property.</param>\n    /// <param name=\"propertyId\">The ID of the property.</param>\n    /// <param name=\"propertyDescriptor\">The property descriptor.</param>\n    /// <param name=\"result\">Whether the property was defined.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsDefineProperty(\n            _In_ JsValueRef object,\n            _In_ JsPropertyIdRef propertyId,\n            _In_ JsValueRef propertyDescriptor,\n            _Out_ bool *result);\n\n    /// <summary>\n    ///     Tests whether an object has a value at the specified index.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object to operate on.</param>\n    /// <param name=\"index\">The index to test.</param>\n    /// <param name=\"result\">Whether the object has a value at the specified index.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsHasIndexedProperty(\n            _In_ JsValueRef object,\n            _In_ JsValueRef index,\n            _Out_ bool *result);\n\n    /// <summary>\n    ///     Retrieve the value at the specified index of an object.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object to operate on.</param>\n    /// <param name=\"index\">The index to retrieve.</param>\n    /// <param name=\"result\">The retrieved value.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetIndexedProperty(\n            _In_ JsValueRef object,\n            _In_ JsValueRef index,\n            _Out_ JsValueRef *result);\n\n    /// <summary>\n    ///     Set the value at the specified index of an object.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object to operate on.</param>\n    /// <param name=\"index\">The index to set.</param>\n    /// <param name=\"value\">The value to set.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetIndexedProperty(\n            _In_ JsValueRef object,\n            _In_ JsValueRef index,\n            _In_ JsValueRef value);\n\n    /// <summary>\n    ///     Delete the value at the specified index of an object.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object to operate on.</param>\n    /// <param name=\"index\">The index to delete.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsDeleteIndexedProperty(\n            _In_ JsValueRef object,\n            _In_ JsValueRef index);\n\n    /// <summary>\n    ///     Determines whether an object has its indexed properties in external data.\n    /// </summary>\n    /// <param name=\"object\">The object.</param>\n    /// <param name=\"value\">Whether the object has its indexed properties in external data.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsHasIndexedPropertiesExternalData(\n            _In_ JsValueRef object,\n            _Out_ bool* value);\n\n    /// <summary>\n    ///     Retrieves an object's indexed properties external data information.\n    /// </summary>\n    /// <param name=\"object\">The object.</param>\n    /// <param name=\"data\">The external data back store for the object's indexed properties.</param>\n    /// <param name=\"arrayType\">The array element type in external data.</param>\n    /// <param name=\"elementLength\">The number of array elements in external data.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetIndexedPropertiesExternalData(\n            _In_ JsValueRef object,\n            _Out_ void** data,\n            _Out_ JsTypedArrayType* arrayType,\n            _Out_ unsigned int* elementLength);\n\n    /// <summary>\n    ///     Sets an object's indexed properties to external data. The external data will be used as back\n    ///     store for the object's indexed properties and accessed like a typed array.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"object\">The object to operate on.</param>\n    /// <param name=\"data\">The external data to be used as back store for the object's indexed properties.</param>\n    /// <param name=\"arrayType\">The array element type in external data.</param>\n    /// <param name=\"elementLength\">The number of array elements in external data.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetIndexedPropertiesToExternalData(\n            _In_ JsValueRef object,\n            _In_ void* data,\n            _In_ JsTypedArrayType arrayType,\n            _In_ unsigned int elementLength);\n\n    /// <summary>\n    ///     Compare two JavaScript values for equality.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     This function is equivalent to the <c>==</c> operator in Javascript.\n    ///     </para>\n    ///     <para>\n    ///     Requires an active script context.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"object1\">The first object to compare.</param>\n    /// <param name=\"object2\">The second object to compare.</param>\n    /// <param name=\"result\">Whether the values are equal.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsEquals(\n            _In_ JsValueRef object1,\n            _In_ JsValueRef object2,\n            _Out_ bool *result);\n\n    /// <summary>\n    ///     Compare two JavaScript values for strict equality.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     This function is equivalent to the <c>===</c> operator in Javascript.\n    ///     </para>\n    ///     <para>\n    ///     Requires an active script context.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"object1\">The first object to compare.</param>\n    /// <param name=\"object2\">The second object to compare.</param>\n    /// <param name=\"result\">Whether the values are strictly equal.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsStrictEquals(\n            _In_ JsValueRef object1,\n            _In_ JsValueRef object2,\n            _Out_ bool *result);\n\n    /// <summary>\n    ///     Determines whether an object is an external object.\n    /// </summary>\n    /// <param name=\"object\">The object.</param>\n    /// <param name=\"value\">Whether the object is an external object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsHasExternalData(\n            _In_ JsValueRef object,\n            _Out_ bool *value);\n\n    /// <summary>\n    ///     Retrieves the data from an external object.\n    /// </summary>\n    /// <param name=\"object\">The external object.</param>\n    /// <param name=\"externalData\">\n    ///     The external data stored in the object. Can be null if no external data is stored in the\n    ///     object.\n    /// </param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetExternalData(\n            _In_ JsValueRef object,\n            _Out_ void **externalData);\n\n    /// <summary>\n    ///     Sets the external data on an external object.\n    /// </summary>\n    /// <param name=\"object\">The external object.</param>\n    /// <param name=\"externalData\">\n    ///     The external data to be stored in the object. Can be null if no external data is\n    ///     to be stored in the object.\n    /// </param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetExternalData(\n            _In_ JsValueRef object,\n            _In_opt_ void *externalData);\n\n    /// <summary>\n    ///     Creates a Javascript array object.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"length\">The initial length of the array.</param>\n    /// <param name=\"result\">The new array object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateArray(\n            _In_ unsigned int length,\n            _Out_ JsValueRef *result);\n\n    /// <summary>\n    ///     Creates a Javascript ArrayBuffer object.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"byteLength\">\n    ///     The number of bytes in the ArrayBuffer.\n    /// </param>\n    /// <param name=\"result\">The new ArrayBuffer object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateArrayBuffer(\n            _In_ unsigned int byteLength,\n            _Out_ JsValueRef *result);\n\n    /// <summary>\n    ///     Creates a Javascript ArrayBuffer object to access external memory.\n    /// </summary>\n    /// <remarks>Requires an active script context.</remarks>\n    /// <param name=\"data\">A pointer to the external memory.</param>\n    /// <param name=\"byteLength\">The number of bytes in the external memory.</param>\n    /// <param name=\"finalizeCallback\">A callback for when the object is finalized. May be null.</param>\n    /// <param name=\"callbackState\">User provided state that will be passed back to finalizeCallback.</param>\n    /// <param name=\"result\">The new ArrayBuffer object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateExternalArrayBuffer(\n            _Pre_maybenull_ _Pre_writable_byte_size_(byteLength) void *data,\n            _In_ unsigned int byteLength,\n            _In_opt_ JsFinalizeCallback finalizeCallback,\n            _In_opt_ void *callbackState,\n            _Out_ JsValueRef *result);\n\n    /// <summary>\n    ///     Creates a Javascript typed array object.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     The <c>baseArray</c> can be an <c>ArrayBuffer</c>, another typed array, or a JavaScript\n    ///     <c>Array</c>. The returned typed array will use the baseArray if it is an ArrayBuffer, or\n    ///     otherwise create and use a copy of the underlying source array.\n    ///     </para>\n    ///     <para>\n    ///     Requires an active script context.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"arrayType\">The type of the array to create.</param>\n    /// <param name=\"baseArray\">\n    ///     The base array of the new array. Use <c>JS_INVALID_REFERENCE</c> if no base array.\n    /// </param>\n    /// <param name=\"byteOffset\">\n    ///     The offset in bytes from the start of baseArray (ArrayBuffer) for result typed array to reference.\n    ///     Only applicable when baseArray is an ArrayBuffer object. Must be 0 otherwise.\n    /// </param>\n    /// <param name=\"elementLength\">\n    ///     The number of elements in the array. Only applicable when creating a new typed array without\n    ///     baseArray (baseArray is <c>JS_INVALID_REFERENCE</c>) or when baseArray is an ArrayBuffer object.\n    ///     Must be 0 otherwise.\n    /// </param>\n    /// <param name=\"result\">The new typed array object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateTypedArray(\n            _In_ JsTypedArrayType arrayType,\n            _In_ JsValueRef baseArray,\n            _In_ unsigned int byteOffset,\n            _In_ unsigned int elementLength,\n            _Out_ JsValueRef *result);\n\n    /// <summary>\n    ///     Creates a Javascript DataView object.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"arrayBuffer\">\n    ///     An existing ArrayBuffer object to use as the storage for the result DataView object.\n    /// </param>\n    /// <param name=\"byteOffset\">\n    ///     The offset in bytes from the start of arrayBuffer for result DataView to reference.\n    /// </param>\n    /// <param name=\"byteLength\">\n    ///     The number of bytes in the ArrayBuffer for result DataView to reference.\n    /// </param>\n    /// <param name=\"result\">The new DataView object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateDataView(\n            _In_ JsValueRef arrayBuffer,\n            _In_ unsigned int byteOffset,\n            _In_ unsigned int byteLength,\n            _Out_ JsValueRef *result);\n\n    /// <summary>\n    ///     Obtains frequently used properties of a typed array.\n    /// </summary>\n    /// <param name=\"typedArray\">The typed array instance.</param>\n    /// <param name=\"arrayType\">The type of the array.</param>\n    /// <param name=\"arrayBuffer\">The ArrayBuffer backstore of the array.</param>\n    /// <param name=\"byteOffset\">The offset in bytes from the start of arrayBuffer referenced by the array.</param>\n    /// <param name=\"byteLength\">The number of bytes in the array.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetTypedArrayInfo(\n            _In_ JsValueRef typedArray,\n            _Out_opt_ JsTypedArrayType *arrayType,\n            _Out_opt_ JsValueRef *arrayBuffer,\n            _Out_opt_ unsigned int *byteOffset,\n            _Out_opt_ unsigned int *byteLength);\n\n    /// <summary>\n    ///     Obtains the underlying memory storage used by an <c>ArrayBuffer</c>.\n    /// </summary>\n    /// <param name=\"arrayBuffer\">The ArrayBuffer instance.</param>\n    /// <param name=\"buffer\">\n    ///     The ArrayBuffer's buffer. The lifetime of the buffer returned is the same as the lifetime of the\n    ///     the ArrayBuffer. The buffer pointer does not count as a reference to the ArrayBuffer for the purpose\n    ///     of garbage collection.\n    /// </param>\n    /// <param name=\"bufferLength\">The number of bytes in the buffer.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetArrayBufferStorage(\n            _In_ JsValueRef arrayBuffer,\n            _Outptr_result_bytebuffer_(*bufferLength) ChakraBytePtr *buffer,\n            _Out_ unsigned int *bufferLength);\n\n    /// <summary>\n    ///     Obtains the underlying memory storage used by a typed array.\n    /// </summary>\n    /// <param name=\"typedArray\">The typed array instance.</param>\n    /// <param name=\"buffer\">\n    ///     The array's buffer. The lifetime of the buffer returned is the same as the lifetime of the\n    ///     the array. The buffer pointer does not count as a reference to the array for the purpose\n    ///     of garbage collection.\n    /// </param>\n    /// <param name=\"bufferLength\">The number of bytes in the buffer.</param>\n    /// <param name=\"arrayType\">The type of the array.</param>\n    /// <param name=\"elementSize\">\n    ///     The size of an element of the array.\n    /// </param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetTypedArrayStorage(\n            _In_ JsValueRef typedArray,\n            _Outptr_result_bytebuffer_(*bufferLength) ChakraBytePtr *buffer,\n            _Out_ unsigned int *bufferLength,\n            _Out_opt_ JsTypedArrayType *arrayType,\n            _Out_opt_ int *elementSize);\n\n    /// <summary>\n    ///     Obtains the underlying memory storage used by a DataView.\n    /// </summary>\n    /// <param name=\"dataView\">The DataView instance.</param>\n    /// <param name=\"buffer\">\n    ///     The DataView's buffer. The lifetime of the buffer returned is the same as the lifetime of the\n    ///     the DataView. The buffer pointer does not count as a reference to the DataView for the purpose\n    ///     of garbage collection.\n    /// </param>\n    /// <param name=\"bufferLength\">The number of bytes in the buffer.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetDataViewStorage(\n            _In_ JsValueRef dataView,\n            _Outptr_result_bytebuffer_(*bufferLength) ChakraBytePtr *buffer,\n            _Out_ unsigned int *bufferLength);\n\n\n    /// <summary>\n    ///     Invokes a function.\n    /// </summary>\n    /// <remarks>\n    ///     Requires thisArg as first argument of arguments.\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"function\">The function to invoke.</param>\n    /// <param name=\"arguments\">The arguments to the call.</param>\n    /// <param name=\"argumentCount\">The number of arguments being passed in to the function.</param>\n    /// <param name=\"result\">The value returned from the function invocation, if any.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCallFunction(\n            _In_ JsValueRef function,\n            _In_reads_(argumentCount) JsValueRef *arguments,\n            _In_ unsigned short argumentCount,\n            _Out_opt_ JsValueRef *result);\n\n    /// <summary>\n    ///     Invokes a function as a constructor.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"function\">The function to invoke as a constructor.</param>\n    /// <param name=\"arguments\">The arguments to the call.</param>\n    /// <param name=\"argumentCount\">The number of arguments being passed in to the function.</param>\n    /// <param name=\"result\">The value returned from the function invocation.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsConstructObject(\n            _In_ JsValueRef function,\n            _In_reads_(argumentCount) JsValueRef *arguments,\n            _In_ unsigned short argumentCount,\n            _Out_ JsValueRef *result);\n\n    /// <summary>\n    ///     Creates a new JavaScript function.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"nativeFunction\">The method to call when the function is invoked.</param>\n    /// <param name=\"callbackState\">\n    ///     User provided state that will be passed back to the callback.\n    /// </param>\n    /// <param name=\"function\">The new function object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateFunction(\n            _In_ JsNativeFunction nativeFunction,\n            _In_opt_ void *callbackState,\n            _Out_ JsValueRef *function);\n\n    /// <summary>\n    ///     Creates a new JavaScript function with name.\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"name\">The name of this function that will be used for diagnostics and stringification purposes.</param>\n    /// <param name=\"nativeFunction\">The method to call when the function is invoked.</param>\n    /// <param name=\"callbackState\">\n    ///     User provided state that will be passed back to the callback.\n    /// </param>\n    /// <param name=\"function\">The new function object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateNamedFunction(\n            _In_ JsValueRef name,\n            _In_ JsNativeFunction nativeFunction,\n            _In_opt_ void *callbackState,\n            _Out_ JsValueRef *function);\n\n    /// <summary>\n    ///     Creates a new JavaScript error object\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"message\">Message for the error object.</param>\n    /// <param name=\"error\">The new error object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateError(\n            _In_ JsValueRef message,\n            _Out_ JsValueRef *error);\n\n    /// <summary>\n    ///     Creates a new JavaScript RangeError error object\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"message\">Message for the error object.</param>\n    /// <param name=\"error\">The new error object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateRangeError(\n            _In_ JsValueRef message,\n            _Out_ JsValueRef *error);\n\n    /// <summary>\n    ///     Creates a new JavaScript ReferenceError error object\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"message\">Message for the error object.</param>\n    /// <param name=\"error\">The new error object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateReferenceError(\n            _In_ JsValueRef message,\n            _Out_ JsValueRef *error);\n\n    /// <summary>\n    ///     Creates a new JavaScript SyntaxError error object\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"message\">Message for the error object.</param>\n    /// <param name=\"error\">The new error object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateSyntaxError(\n            _In_ JsValueRef message,\n            _Out_ JsValueRef *error);\n\n    /// <summary>\n    ///     Creates a new JavaScript TypeError error object\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"message\">Message for the error object.</param>\n    /// <param name=\"error\">The new error object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateTypeError(\n            _In_ JsValueRef message,\n            _Out_ JsValueRef *error);\n\n    /// <summary>\n    ///     Creates a new JavaScript URIError error object\n    /// </summary>\n    /// <remarks>\n    ///     Requires an active script context.\n    /// </remarks>\n    /// <param name=\"message\">Message for the error object.</param>\n    /// <param name=\"error\">The new error object.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsCreateURIError(\n            _In_ JsValueRef message,\n            _Out_ JsValueRef *error);\n\n    /// <summary>\n    ///     Determines whether the runtime of the current context is in an exception state.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     If a call into the runtime results in an exception (either as the result of running a\n    ///     script or due to something like a conversion failure), the runtime is placed into an\n    ///     \"exception state.\" All calls into any context created by the runtime (except for the\n    ///     exception APIs) will fail with <c>JsErrorInExceptionState</c> until the exception is\n    ///     cleared.\n    ///     </para>\n    ///     <para>\n    ///     If the runtime of the current context is in the exception state when a callback returns\n    ///     into the engine, the engine will automatically rethrow the exception.\n    ///     </para>\n    ///     <para>\n    ///     Requires an active script context.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"hasException\">\n    ///     Whether the runtime of the current context is in the exception state.\n    /// </param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsHasException(\n            _Out_ bool *hasException);\n\n    /// <summary>\n    ///     Returns the exception that caused the runtime of the current context to be in the\n    ///     exception state and resets the exception state for that runtime.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     If the runtime of the current context is not in an exception state, this API will return\n    ///     <c>JsErrorInvalidArgument</c>. If the runtime is disabled, this will return an exception\n    ///     indicating that the script was terminated, but it will not clear the exception (the\n    ///     exception will be cleared if the runtime is re-enabled using\n    ///     <c>JsEnableRuntimeExecution</c>).\n    ///     </para>\n    ///     <para>\n    ///     Requires an active script context.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"exception\">The exception for the runtime of the current context.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsGetAndClearException(\n            _Out_ JsValueRef *exception);\n\n    /// <summary>\n    ///     Sets the runtime of the current context to an exception state.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     If the runtime of the current context is already in an exception state, this API will\n    ///     return <c>JsErrorInExceptionState</c>.\n    ///     </para>\n    ///     <para>\n    ///     Requires an active script context.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"exception\">\n    ///     The JavaScript exception to set for the runtime of the current context.\n    /// </param>\n    /// <returns>\n    ///     JsNoError if the engine was set into an exception state, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetException(\n            _In_ JsValueRef exception);\n\n    /// <summary>\n    ///     Suspends script execution and terminates any running scripts in a runtime.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     Calls to a suspended runtime will fail until <c>JsEnableRuntimeExecution</c> is called.\n    ///     </para>\n    ///     <para>\n    ///     This API does not have to be called on the thread the runtime is active on. Although the\n    ///     runtime will be set into a suspended state, an executing script may not be suspended\n    ///     immediately; a running script will be terminated with an uncatchable exception as soon as\n    ///     possible.\n    ///     </para>\n    ///     <para>\n    ///     Suspending execution in a runtime that is already suspended is a no-op.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"runtime\">The runtime to be suspended.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsDisableRuntimeExecution(\n            _In_ JsRuntimeHandle runtime);\n\n    /// <summary>\n    ///     Enables script execution in a runtime.\n    /// </summary>\n    /// <remarks>\n    ///     Enabling script execution in a runtime that already has script execution enabled is a\n    ///     no-op.\n    /// </remarks>\n    /// <param name=\"runtime\">The runtime to be enabled.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsEnableRuntimeExecution(\n            _In_ JsRuntimeHandle runtime);\n\n    /// <summary>\n    ///     Returns a value that indicates whether script execution is disabled in the runtime.\n    /// </summary>\n    /// <param name=\"runtime\">Specifies the runtime to check if execution is disabled.</param>\n    /// <param name=\"isDisabled\">If execution is disabled, <c>true</c>, <c>false</c> otherwise.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsIsRuntimeExecutionDisabled(\n            _In_ JsRuntimeHandle runtime,\n            _Out_ bool *isDisabled);\n\n    /// <summary>\n    ///     Sets a promise continuation callback function that is called by the context when a task\n    ///     needs to be queued for future execution\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///     Requires an active script context.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"promiseContinuationCallback\">The callback function being set.</param>\n    /// <param name=\"callbackState\">\n    ///     User provided state that will be passed back to the callback.\n    /// </param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsSetPromiseContinuationCallback(\n            _In_opt_ JsPromiseContinuationCallback promiseContinuationCallback,\n            _In_opt_ void *callbackState);\n\n#ifdef _WIN32\n#include \"ChakraCommonWindows.h\"\n#endif // _WIN32\n#endif // _CHAKRACOMMON_H_\n"
  },
  {
    "path": "include/ChakraCore.h",
    "content": "//-------------------------------------------------------------------------------------------------------\n// Copyright (C) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n//-------------------------------------------------------------------------------------------------------\n/// \\mainpage Chakra Hosting API Reference\n///\n/// Chakra is Microsoft's JavaScript engine. It is an integral part of Internet Explorer but can\n/// also be hosted independently by other applications. This reference describes the APIs available\n/// to applications to host Chakra.\n///\n\n/// \\file\n/// \\brief The Chakra Core hosting API.\n///\n/// This file contains a flat C API layer. This is the API exported by ChakraCore.dll.\n\n#ifdef _MSC_VER\n#pragma once\n#endif // _MSC_VER\n\n#ifndef _CHAKRACORE_H_\n#define _CHAKRACORE_H_\n\n#if !defined(NTBUILD) && !defined(_CHAKRACOREBUILD)\n#define _CHAKRACOREBUILD\n#endif\n\n#include \"ChakraCommon.h\"\n#include \"ChakraDebug.h\"\n\n// Begin ChakraCore only APIs\n#ifdef _CHAKRACOREBUILD\n\n/// <summary>\n///     A reference to an ES module.\n/// </summary>\n/// <remarks>\n///     A module record represents an ES module.\n/// </remarks>\ntypedef void* JsModuleRecord;\n\n/// <summary>\n///     A reference to an object owned by the SharedArrayBuffer.\n/// </summary>\n/// <remarks>\n///     This represents SharedContents which is heap allocated object, it can be passed through\n///     different runtimes to share the underlying buffer.\n/// </remarks>\ntypedef void *JsSharedArrayBufferContentHandle;\n\n/// <summary>\n///     Flags for parsing a module.\n/// </summary>\ntypedef enum JsParseModuleSourceFlags\n{\n    /// <summary>\n    ///     Module source is UTF16.\n    /// </summary>\n    JsParseModuleSourceFlags_DataIsUTF16LE = 0x00000000,\n    /// <summary>\n    ///     Module source is UTF8.\n    /// </summary>\n    JsParseModuleSourceFlags_DataIsUTF8 = 0x00000001\n} JsParseModuleSourceFlags;\n\n/// <summary>\n///     The types of host info that can be set on a module record with JsSetModuleHostInfo.\n/// </summary>\n/// <remarks>\n///     For more information see JsSetModuleHostInfo.\n/// </remarks>\ntypedef enum JsModuleHostInfoKind\n{\n    /// <summary>\n    ///     An exception object - e.g. if the module file cannot be found.\n    /// </summary>\n    JsModuleHostInfo_Exception = 0x01,\n    /// <summary>\n    ///     Host defined info.\n    /// </summary>\n    JsModuleHostInfo_HostDefined = 0x02,\n    /// <summary>\n    ///     Callback for receiving notification when module is ready.\n    /// </summary>\n    JsModuleHostInfo_NotifyModuleReadyCallback = 0x3,\n    /// <summary>\n    ///     Callback for receiving notification to fetch a dependent module.\n    /// </summary>\n    JsModuleHostInfo_FetchImportedModuleCallback = 0x4,\n    /// <summary>\n    ///     Callback for receiving notification for calls to ```import()```\n    /// </summary>\n    JsModuleHostInfo_FetchImportedModuleFromScriptCallback = 0x5,\n    /// <summary>\n    ///     URL for use in error stack traces and debugging.\n    /// </summary>\n    JsModuleHostInfo_Url = 0x6\n} JsModuleHostInfoKind;\n\n/// <summary>\n///     The possible states for a Promise object.\n/// </summary>\ntypedef enum _JsPromiseState\n{\n    JsPromiseStatePending = 0x0,\n    JsPromiseStateFulfilled = 0x1,\n    JsPromiseStateRejected = 0x2\n} JsPromiseState;\n\n/// <summary>\n///     User implemented callback to fetch additional imported modules in ES modules.\n/// </summary>\n/// <remarks>\n///     The callback is invoked on the current runtime execution thread, therefore execution is blocked until \n///     the callback completes. Notify the host to fetch the dependent module. This is the \"import\" part \n///     before HostResolveImportedModule in ES6 spec. This notifies the host that the referencing module has\n///     the specified module dependency, and the host needs to retrieve the module back.\n///\n///     Callback should:\n///     1. Check if the requested module has been requested before - if yes return the existing\n///         module record\n///     2. If no create and initialize a new module record with JsInitializeModuleRecord to\n///         return and schedule a call to JsParseModuleSource for the new record.\n/// </remarks>\n/// <param name=\"referencingModule\">The referencing module that is requesting the dependent module.</param>\n/// <param name=\"specifier\">The specifier coming from the module source code.</param>\n/// <param name=\"dependentModuleRecord\">The ModuleRecord of the dependent module. If the module was requested \n///                                     before from other source, return the existing ModuleRecord, otherwise\n///                                     return a newly created ModuleRecord.</param>\n/// <returns>\n///     Returns a <c>JsNoError</c> if the operation succeeded an error code otherwise.\n/// </returns>\ntypedef JsErrorCode(CHAKRA_CALLBACK * FetchImportedModuleCallBack)(_In_ JsModuleRecord referencingModule, _In_ JsValueRef specifier, _Outptr_result_maybenull_ JsModuleRecord* dependentModuleRecord);\n\n/// <summary>\n///     User implemented callback to fetch imported modules dynamically in scripts.\n/// </summary>\n/// <remarks>\n///     The callback is invoked on the current runtime execution thread, therefore execution is blocked untill\n///     the callback completes. Notify the host to fetch the dependent module. This is used for the dynamic\n///     import() syntax.\n///\n///     Callback should:\n///     1. Check if the requested module has been requested before - if yes return the existing module record\n///     2. If no create and initialize a new module record with JsInitializeModuleRecord to return and\n///         schedule a call to JsParseModuleSource for the new record.\n/// </remarks>\n/// <param name=\"dwReferencingSourceContext\">The referencing script context that calls import()</param>\n/// <param name=\"specifier\">The specifier provided to the import() call.</param>\n/// <param name=\"dependentModuleRecord\">The ModuleRecord of the dependent module. If the module was requested\n///                                     before from other source, return the existing ModuleRecord, otherwise\n///                                     return a newly created ModuleRecord.</param>\n/// <returns>\n///     Returns <c>JsNoError</c> if the operation succeeded or an error code otherwise.\n/// </returns>\ntypedef JsErrorCode(CHAKRA_CALLBACK * FetchImportedModuleFromScriptCallBack)(_In_ JsSourceContext dwReferencingSourceContext, _In_ JsValueRef specifier, _Outptr_result_maybenull_ JsModuleRecord* dependentModuleRecord);\n\n/// <summary>\n///     User implemented callback to get notification when the module is ready.\n/// </summary>\n/// <remarks>\n///     The callback is invoked on the current runtime execution thread, therefore execution is blocked until the\n///     callback completes. This callback should schedule a call to JsEvaluateModule to run the module that has been loaded.\n/// </remarks>\n/// <param name=\"referencingModule\">The referencing module that has finished running ModuleDeclarationInstantiation step.</param>\n/// <param name=\"exceptionVar\">If nullptr, the module is successfully initialized and host should queue the execution job\n///                            otherwise it's the exception object.</param>\n/// <returns>\n///     Returns a JsErrorCode - note, the return value is ignored.\n/// </returns>\ntypedef JsErrorCode(CHAKRA_CALLBACK * NotifyModuleReadyCallback)(_In_opt_ JsModuleRecord referencingModule, _In_opt_ JsValueRef exceptionVar);\n\n/// <summary>\n///     A structure containing information about a native function callback.\n/// </summary>\ntypedef struct JsNativeFunctionInfo\n{\n    JsValueRef thisArg;\n    JsValueRef newTargetArg;\n    bool isConstructCall;\n}JsNativeFunctionInfo;\n\n/// <summary>\n///     A function callback.\n/// </summary>\n/// <param name=\"callee\">\n///     A function object that represents the function being invoked.\n/// </param>\n/// <param name=\"arguments\">The arguments to the call.</param>\n/// <param name=\"argumentCount\">The number of arguments.</param>\n/// <param name=\"info\">Additional information about this function call.</param>\n/// <param name=\"callbackState\">\n///     The state passed to <c>JsCreateFunction</c>.\n/// </param>\n/// <returns>The result of the call, if any.</returns>\ntypedef _Ret_maybenull_ JsValueRef(CHAKRA_CALLBACK * JsEnhancedNativeFunction)(_In_ JsValueRef callee, _In_ JsValueRef *arguments, _In_ unsigned short argumentCount, _In_ JsNativeFunctionInfo *info, _In_opt_ void *callbackState);\n\n/// <summary>\n///     A Promise Rejection Tracker callback.\n/// </summary>\n/// <remarks>\n///     The host can specify a promise rejection tracker callback in <c>JsSetHostPromiseRejectionTracker</c>.\n///     If a promise is rejected with no reactions or a reaction is added to a promise that was rejected\n///     before it had reactions by default nothing is done.\n///     A Promise Rejection Tracker callback may be set - which will then be called when this occurs.\n///     Note - per draft ECMASpec 2018 25.4.1.9 this function should not set or return an exception\n///     Note also the promise and reason parameters may be garbage collected after this function is called\n///     if you wish to make further use of them you will need to use JsAddRef to preserve them\n///     However if you use JsAddRef you must also call JsRelease and not hold unto them after \n///     a handled notification (both per spec and to avoid memory leaks)\n/// </remarks>\n/// <param name=\"promise\">The promise object, represented as a JsValueRef.</param>\n/// <param name=\"reason\">The value/cause of the rejection, represented as a JsValueRef.</param>\n/// <param name=\"handled\">Boolean - false for promiseRejected: i.e. if the promise has just been rejected with no handler, \n///                         true for promiseHandled: i.e. if it was rejected before without a handler and is now being handled.</param>\n/// <param name=\"callbackState\">The state passed to <c>JsSetHostPromiseRejectionTracker</c>.</param>\ntypedef void (CHAKRA_CALLBACK *JsHostPromiseRejectionTrackerCallback)(_In_ JsValueRef promise, _In_ JsValueRef reason, _In_ bool handled, _In_opt_ void *callbackState);\n\n/// <summary>\n///     Creates a new enhanced JavaScript function.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"nativeFunction\">The method to call when the function is invoked.</param>\n/// <param name=\"metadata\">If this is not <c>JS_INVALID_REFERENCE</c>, it is converted to a string and used as the name of the function.</param>\n/// <param name=\"callbackState\">\n///     User provided state that will be passed back to the callback.\n/// </param>\n/// <param name=\"function\">The new function object.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\nJsCreateEnhancedFunction(\n    _In_ JsEnhancedNativeFunction nativeFunction,\n    _In_opt_ JsValueRef metadata,\n    _In_opt_ void *callbackState,\n    _Out_ JsValueRef *function);\n\n/// <summary>\n///     Initialize a ModuleRecord from host\n/// </summary>\n/// <remarks>\n///     Bootstrap the module loading process by creating a new module record.\n/// </remarks>\n/// <param name=\"referencingModule\">The parent module of the new module - nullptr for a root module.</param>\n/// <param name=\"normalizedSpecifier\">The normalized specifier for the module.</param>\n/// <param name=\"moduleRecord\">The new module record. The host should not try to call this API twice\n///                            with the same normalizedSpecifier.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\nJsInitializeModuleRecord(\n    _In_opt_ JsModuleRecord referencingModule,\n    _In_ JsValueRef normalizedSpecifier,\n    _Outptr_result_maybenull_ JsModuleRecord* moduleRecord);\n\n/// <summary>\n///     Parse the source for an ES module\n/// </summary>\n/// <remarks>\n///     This is basically ParseModule operation in ES6 spec. It is slightly different in that:\n///     a) The ModuleRecord was initialized earlier, and passed in as an argument.\n///     b) This includes a check to see if the module being Parsed is the last module in the\n/// dependency tree. If it is it automatically triggers Module Instantiation.\n/// </remarks>\n/// <param name=\"requestModule\">The ModuleRecord being parsed.</param>\n/// <param name=\"sourceContext\">A cookie identifying the script that can be used by debuggable script contexts.</param>\n/// <param name=\"script\">The source script to be parsed, but not executed in this code.</param>\n/// <param name=\"scriptLength\">The length of sourceText in bytes. As the input might contain a embedded null.</param>\n/// <param name=\"sourceFlag\">The type of the source code passed in. It could be utf16 or utf8 at this time.</param>\n/// <param name=\"exceptionValueRef\">The error object if there is parse error.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\nJsParseModuleSource(\n    _In_ JsModuleRecord requestModule,\n    _In_ JsSourceContext sourceContext,\n    _In_ BYTE* script,\n    _In_ unsigned int scriptLength,\n    _In_ JsParseModuleSourceFlags sourceFlag,\n    _Outptr_result_maybenull_ JsValueRef* exceptionValueRef);\n\n/// <summary>\n///     Execute module code.\n/// </summary>\n/// <remarks>\n///     This method implements 15.2.1.1.6.5, \"ModuleEvaluation\" concrete method.\n///     This method should be called after the engine notifies the host that the module is ready.\n///     This method only needs to be called on root modules - it will execute all of the dependent modules.\n///\n///     One moduleRecord will be executed only once. Additional execution call on the same moduleRecord will fail.\n/// </remarks>\n/// <param name=\"requestModule\">The ModuleRecord being executed.</param>\n/// <param name=\"result\">The return value of the module.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\nJsModuleEvaluation(\n    _In_ JsModuleRecord requestModule,\n    _Outptr_result_maybenull_ JsValueRef* result);\n\n/// <summary>\n///     Set host info for the specified module.\n/// </summary>\n/// <remarks>\n///     This is used for four things:\n///     1. Setting up the callbacks for module loading - note these are actually\n///         set on the current Context not the module so only have to be set for\n///         the first root module in any given context.\n///     2. Setting host defined info on a module record - can be anything that\n///         you wish to associate with your modules.\n///     3. Setting a URL for a module to be used for stack traces/debugging -\n///         note this must be set before calling JsParseModuleSource on the module\n///         or it will be ignored.\n///     4. Setting an exception on the module object - only relevant prior to it being Parsed.\n/// </remarks>\n/// <param name=\"requestModule\">The request module.</param>\n/// <param name=\"moduleHostInfo\">The type of host info to be set.</param>\n/// <param name=\"hostInfo\">The host info to be set.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\nJsSetModuleHostInfo(\n    _In_ JsModuleRecord requestModule,\n    _In_ JsModuleHostInfoKind moduleHostInfo,\n    _In_ void* hostInfo);\n\n/// <summary>\n///     Retrieve the host info for the specified module.\n/// </summary>\n/// <remarks>\n///     This can used to retrieve info previously set with JsSetModuleHostInfo.\n/// </remarks>\n/// <param name=\"requestModule\">The request module.</param>\n/// <param name=\"moduleHostInfo\">The type of host info to be retrieved.</param>\n/// <param name=\"hostInfo\">The retrieved host info for the module.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\nJsGetModuleHostInfo(\n    _In_  JsModuleRecord requestModule,\n    _In_ JsModuleHostInfoKind moduleHostInfo,\n    _Outptr_result_maybenull_ void** hostInfo);\n\n/// <summary>\n///     Returns metadata relating to the exception that caused the runtime of the current context\n///     to be in the exception state and resets the exception state for that runtime. The metadata\n///     includes a reference to the exception itself.\n/// </summary>\n/// <remarks>\n///     <para>\n///     If the runtime of the current context is not in an exception state, this API will return\n///     <c>JsErrorInvalidArgument</c>. If the runtime is disabled, this will return an exception\n///     indicating that the script was terminated, but it will not clear the exception (the\n///     exception will be cleared if the runtime is re-enabled using\n///     <c>JsEnableRuntimeExecution</c>).\n///     </para>\n///     <para>\n///     The metadata value is a javascript object with the following properties: <c>exception</c>, the\n///     thrown exception object; <c>line</c>, the 0 indexed line number where the exception was thrown;\n///     <c>column</c>, the 0 indexed column number where the exception was thrown; <c>length</c>, the\n///     source-length of the cause of the exception; <c>source</c>, a string containing the line of\n///     source code where the exception was thrown; and <c>url</c>, a string containing the name of\n///     the script file containing the code that threw the exception.\n///     </para>\n///     <para>\n///     Requires an active script context.\n///     </para>\n/// </remarks>\n/// <param name=\"metadata\">The exception metadata for the runtime of the current context.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\nJsGetAndClearExceptionWithMetadata(\n    _Out_ JsValueRef *metadata);\n\n/// <summary>\n///     Called by the runtime to load the source code of the serialized script.\n/// </summary>\n/// <param name=\"sourceContext\">The context passed to Js[Parse|Run]SerializedScriptCallback</param>\n/// <param name=\"script\">The script returned.</param>\n/// <returns>\n///     true if the operation succeeded, false otherwise.\n/// </returns>\ntypedef bool (CHAKRA_CALLBACK * JsSerializedLoadScriptCallback)\n    (JsSourceContext sourceContext, _Out_ JsValueRef *value,\n    _Out_ JsParseScriptAttributes *parseAttributes);\n\n/// <summary>\n///     Create JavascriptString variable from ASCII or Utf8 string\n/// </summary>\n/// <remarks>\n///     <para>\n///        Requires an active script context.\n///     </para>\n///     <para>\n///         Input string can be either ASCII or Utf8\n///     </para>\n/// </remarks>\n/// <param name=\"content\">Pointer to string memory.</param>\n/// <param name=\"length\">Number of bytes within the string</param>\n/// <param name=\"value\">JsValueRef representing the JavascriptString</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsCreateString(\n        _In_ const char *content,\n        _In_ size_t length,\n        _Out_ JsValueRef *value);\n\n/// <summary>\n///     Create JavascriptString variable from Utf16 string\n/// </summary>\n/// <remarks>\n///     <para>\n///         Requires an active script context.\n///     </para>\n///     <para>\n///         Expects Utf16 string\n///     </para>\n/// </remarks>\n/// <param name=\"content\">Pointer to string memory.</param>\n/// <param name=\"length\">Number of characters within the string</param>\n/// <param name=\"value\">JsValueRef representing the JavascriptString</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsCreateStringUtf16(\n        _In_ const uint16_t *content,\n        _In_ size_t length,\n        _Out_ JsValueRef *value);\n\n/// <summary>\n///     Write JavascriptString value into C string buffer (Utf8)\n/// </summary>\n/// <remarks>\n///     <para>\n///         When size of the `buffer` is unknown,\n///         `buffer` argument can be nullptr.\n///         In that case, `length` argument will return the length needed.\n///     </para>\n/// </remarks>\n/// <param name=\"value\">JavascriptString value</param>\n/// <param name=\"buffer\">Pointer to buffer</param>\n/// <param name=\"bufferSize\">Buffer size</param>\n/// <param name=\"length\">Total number of characters needed or written</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsCopyString(\n        _In_ JsValueRef value,\n        _Out_opt_ char* buffer,\n        _In_ size_t bufferSize,\n        _Out_opt_ size_t* length);\n\n/// <summary>\n///     Write string value into Utf16 string buffer\n/// </summary>\n/// <remarks>\n///     <para>\n///         When size of the `buffer` is unknown,\n///         `buffer` argument can be nullptr.\n///         In that case, `written` argument will return the length needed.\n///     </para>\n///     <para>\n///         when start is out of range or &lt; 0, returns JsErrorInvalidArgument\n///         and `written` will be equal to 0.\n///         If calculated length is 0 (It can be due to string length or `start`\n///         and length combination), then `written` will be equal to 0 and call\n///         returns JsNoError\n///     </para>\n/// </remarks>\n/// <param name=\"value\">JavascriptString value</param>\n/// <param name=\"start\">start offset of buffer</param>\n/// <param name=\"length\">length to be written</param>\n/// <param name=\"buffer\">Pointer to buffer</param>\n/// <param name=\"written\">Total number of characters written</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsCopyStringUtf16(\n        _In_ JsValueRef value,\n        _In_ int start,\n        _In_ int length,\n        _Out_opt_ uint16_t* buffer,\n        _Out_opt_ size_t* written);\n\n/// <summary>\n///     Parses a script and returns a function representing the script.\n/// </summary>\n/// <remarks>\n///     <para>\n///         Requires an active script context.\n///     </para>\n///     <para>\n///         Script source can be either JavascriptString or JavascriptExternalArrayBuffer.\n///         In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16,\n///         JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes.\n///     </para>\n///     <para>\n///         Use JavascriptExternalArrayBuffer with Utf8/ASCII script source\n///         for better performance and smaller memory footprint.\n///     </para>\n/// </remarks>\n/// <param name=\"script\">The script to run.</param>\n/// <param name=\"sourceContext\">\n///     A cookie identifying the script that can be used by debuggable script contexts.\n/// </param>\n/// <param name=\"sourceUrl\">The location the script came from.</param>\n/// <param name=\"parseAttributes\">Attribute mask for parsing the script</param>\n/// <param name=\"result\">The result of the compiled script.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsParse(\n        _In_ JsValueRef script,\n        _In_ JsSourceContext sourceContext,\n        _In_ JsValueRef sourceUrl,\n        _In_ JsParseScriptAttributes parseAttributes,\n        _Out_ JsValueRef *result);\n\n/// <summary>\n///     Executes a script.\n/// </summary>\n/// <remarks>\n///     <para>\n///         Requires an active script context.\n///     </para>\n///     <para>\n///         Script source can be either JavascriptString or JavascriptExternalArrayBuffer.\n///         In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16,\n///         JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes.\n///     </para>\n///     <para>\n///         Use JavascriptExternalArrayBuffer with Utf8/ASCII script source\n///         for better performance and smaller memory footprint.\n///     </para>\n/// </remarks>\n/// <param name=\"script\">The script to run.</param>\n/// <param name=\"sourceContext\">\n///     A cookie identifying the script that can be used by debuggable script contexts.\n/// </param>\n/// <param name=\"sourceUrl\">The location the script came from</param>\n/// <param name=\"parseAttributes\">Attribute mask for parsing the script</param>\n/// <param name=\"result\">The result of the script, if any. This parameter can be null.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsRun(\n        _In_ JsValueRef script,\n        _In_ JsSourceContext sourceContext,\n        _In_ JsValueRef sourceUrl,\n        _In_ JsParseScriptAttributes parseAttributes,\n        _Out_ JsValueRef *result);\n\n/// <summary>\n///     Creates the property ID associated with the name.\n/// </summary>\n/// <remarks>\n///     <para>\n///         Property IDs are specific to a context and cannot be used across contexts.\n///     </para>\n///     <para>\n///         Requires an active script context.\n///     </para>\n/// </remarks>\n/// <param name=\"name\">\n///     The name of the property ID to get or create. The name may consist of only digits.\n///     The string is expected to be ASCII / utf8 encoded.\n/// </param>\n/// <param name=\"length\">length of the name in bytes</param>\n/// <param name=\"propertyId\">The property ID in this runtime for the given name.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsCreatePropertyId(\n        _In_z_ const char *name,\n        _In_ size_t length,\n        _Out_ JsPropertyIdRef *propertyId);\n\n/// <summary>\n///     Copies the name associated with the property ID into a buffer.\n/// </summary>\n/// <remarks>\n///     <para>\n///         Requires an active script context.\n///     </para>\n///     <para>\n///         When size of the `buffer` is unknown,\n///         `buffer` argument can be nullptr.\n///         `length` argument will return the size needed.\n///     </para>\n/// </remarks>\n/// <param name=\"propertyId\">The property ID to get the name of.</param>\n/// <param name=\"buffer\">The buffer holding the name associated with the property ID, encoded as utf8</param>\n/// <param name=\"bufferSize\">Size of the buffer.</param>\n/// <param name=\"written\">Total number of characters written or to be written</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsCopyPropertyId(\n        _In_ JsPropertyIdRef propertyId,\n        _Out_ char* buffer,\n        _In_ size_t bufferSize,\n        _Out_ size_t* length);\n\n/// <summary>\n///     Serializes a parsed script to a buffer than can be reused.\n/// </summary>\n/// <remarks>\n///     <para>\n///     <c>JsSerializeScript</c> parses a script and then stores the parsed form of the script in a\n///     runtime-independent format. The serialized script then can be deserialized in any\n///     runtime without requiring the script to be re-parsed.\n///     </para>\n///     <para>\n///     Requires an active script context.\n///     </para>\n///     <para>\n///         Script source can be either JavascriptString or JavascriptExternalArrayBuffer.\n///         In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16,\n///         JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes.\n///     </para>\n///     <para>\n///         Use JavascriptExternalArrayBuffer with Utf8/ASCII script source\n///         for better performance and smaller memory footprint.\n///     </para>\n/// </remarks>\n/// <param name=\"script\">The script to serialize</param>\n/// <param name=\"buffer\">ArrayBuffer</param>\n/// <param name=\"parseAttributes\">Encoding for the script.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsSerialize(\n        _In_ JsValueRef script,\n        _Out_ JsValueRef *buffer,\n        _In_ JsParseScriptAttributes parseAttributes);\n\n/// <summary>\n///     Parses a serialized script and returns a function representing the script.\n///     Provides the ability to lazy load the script source only if/when it is needed.\n/// </summary>\n/// <remarks>\n///     <para>\n///     Requires an active script context.\n///     </para>\n/// </remarks>\n/// <param name=\"buffer\">The serialized script as an ArrayBuffer (preferably ExternalArrayBuffer).</param>\n/// <param name=\"scriptLoadCallback\">\n///     Callback called when the source code of the script needs to be loaded.\n///     This is an optional parameter, set to null if not needed.\n/// </param>\n/// <param name=\"sourceContext\">\n///     A cookie identifying the script that can be used by debuggable script contexts.\n///     This context will passed into scriptLoadCallback.\n/// </param>\n/// <param name=\"sourceUrl\">The location the script came from.</param>\n/// <param name=\"result\">A function representing the script code.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsParseSerialized(\n        _In_ JsValueRef buffer,\n        _In_ JsSerializedLoadScriptCallback scriptLoadCallback,\n        _In_ JsSourceContext sourceContext,\n        _In_ JsValueRef sourceUrl,\n        _Out_ JsValueRef *result);\n\n/// <summary>\n///     Runs a serialized script.\n///     Provides the ability to lazy load the script source only if/when it is needed.\n/// </summary>\n/// <remarks>\n///     <para>\n///     Requires an active script context.\n///     </para>\n///     <para>\n///     The runtime will detach the data from the buffer and hold on to it until all\n///     instances of any functions created from the buffer are garbage collected.\n///     </para>\n/// </remarks>\n/// <param name=\"buffer\">The serialized script as an ArrayBuffer (preferably ExternalArrayBuffer).</param>\n/// <param name=\"scriptLoadCallback\">Callback called when the source code of the script needs to be loaded.</param>\n/// <param name=\"sourceContext\">\n///     A cookie identifying the script that can be used by debuggable script contexts.\n///     This context will passed into scriptLoadCallback.\n/// </param>\n/// <param name=\"sourceUrl\">The location the script came from.</param>\n/// <param name=\"result\">\n///     The result of running the script, if any. This parameter can be null.\n/// </param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsRunSerialized(\n        _In_ JsValueRef buffer,\n        _In_ JsSerializedLoadScriptCallback scriptLoadCallback,\n        _In_ JsSourceContext sourceContext,\n        _In_ JsValueRef sourceUrl,\n        _Out_ JsValueRef *result);\n\n/// <summary>\n///     Gets the state of a given Promise object.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"promise\">The Promise object.</param>\n/// <param name=\"state\">The current state of the Promise.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsGetPromiseState(\n        _In_ JsValueRef promise,\n        _Out_ JsPromiseState *state);\n\n/// <summary>\n///     Gets the result of a given Promise object.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"promise\">The Promise object.</param>\n/// <param name=\"result\">The result of the Promise.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsGetPromiseResult(\n        _In_ JsValueRef promise,\n        _Out_ JsValueRef *result);\n\n/// <summary>\n///     Creates a new JavaScript Promise object.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"promise\">The new Promise object.</param>\n/// <param name=\"resolveFunction\">The function called to resolve the created Promise object.</param>\n/// <param name=\"rejectFunction\">The function called to reject the created Promise object.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsCreatePromise(\n        _Out_ JsValueRef *promise,\n        _Out_ JsValueRef *resolveFunction,\n        _Out_ JsValueRef *rejectFunction);\n\n/// <summary>\n///     A weak reference to a JavaScript value.\n/// </summary>\n/// <remarks>\n///     A value with only weak references is available for garbage-collection. A strong reference\n///     to the value (<c>JsValueRef</c>) may be obtained from a weak reference if the value happens\n///     to still be available.\n/// </remarks>\ntypedef JsRef JsWeakRef;\n\n/// <summary>\n///     Creates a weak reference to a value.\n/// </summary>\n/// <param name=\"value\">The value to be referenced.</param>\n/// <param name=\"weakRef\">Weak reference to the value.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsCreateWeakReference(\n        _In_ JsValueRef value,\n        _Out_ JsWeakRef* weakRef);\n\n/// <summary>\n///     Gets a strong reference to the value referred to by a weak reference.\n/// </summary>\n/// <param name=\"weakRef\">A weak reference.</param>\n/// <param name=\"value\">Reference to the value, or <c>JS_INVALID_REFERENCE</c> if the value is\n///     no longer available.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsGetWeakReferenceValue(\n        _In_ JsWeakRef weakRef,\n        _Out_ JsValueRef* value);\n\n/// <summary>\n///     Creates a Javascript SharedArrayBuffer object with shared content get from JsGetSharedArrayBufferContent.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"sharedContents\">\n///     The storage object of a SharedArrayBuffer which can be shared between multiple thread.\n/// </param>\n/// <param name=\"result\">The new SharedArrayBuffer object.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\nJsCreateSharedArrayBufferWithSharedContent(\n    _In_ JsSharedArrayBufferContentHandle sharedContents,\n    _Out_ JsValueRef *result);\n\n/// <summary>\n///     Get the storage object from a SharedArrayBuffer.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"sharedArrayBuffer\">The SharedArrayBuffer object.</param>\n/// <param name=\"sharedContents\">\n///     The storage object of a SharedArrayBuffer which can be shared between multiple thread.\n///     User should call JsReleaseSharedArrayBufferContentHandle after finished using it.\n/// </param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\nJsGetSharedArrayBufferContent(\n    _In_ JsValueRef sharedArrayBuffer,\n    _Out_ JsSharedArrayBufferContentHandle *sharedContents);\n\n/// <summary>\n///     Decrease the reference count on a SharedArrayBuffer storage object.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"sharedContents\">\n///     The storage object of a SharedArrayBuffer which can be shared between multiple thread.\n/// </param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\nJsReleaseSharedArrayBufferContentHandle(\n    _In_ JsSharedArrayBufferContentHandle sharedContents);\n\n/// <summary>\n///     Determines whether an object has a non-inherited property.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"object\">The object that may contain the property.</param>\n/// <param name=\"propertyId\">The ID of the property.</param>\n/// <param name=\"hasOwnProperty\">Whether the object has the non-inherited property.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsHasOwnProperty(\n        _In_ JsValueRef object,\n        _In_ JsPropertyIdRef propertyId,\n        _Out_ bool *hasOwnProperty);\n\n/// <summary>\n///     Write JS string value into char string buffer without a null terminator\n/// </summary>\n/// <remarks>\n///     <para>\n///         When size of the `buffer` is unknown,\n///         `buffer` argument can be nullptr.\n///         In that case, `written` argument will return the length needed.\n///     </para>\n///     <para>\n///         When start is out of range or &lt; 0, returns JsErrorInvalidArgument\n///         and `written` will be equal to 0.\n///         If calculated length is 0 (It can be due to string length or `start`\n///         and length combination), then `written` will be equal to 0 and call\n///         returns JsNoError\n///     </para>\n///     <para>\n///         The JS string `value` will be converted one utf16 code point at a time,\n///         and if it has code points that do not fit in one byte, those values\n///         will be truncated.\n///     </para>\n/// </remarks>\n/// <param name=\"value\">JavascriptString value</param>\n/// <param name=\"start\">Start offset of buffer</param>\n/// <param name=\"length\">Number of characters to be written</param>\n/// <param name=\"buffer\">Pointer to buffer</param>\n/// <param name=\"written\">Total number of characters written</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\nJsCopyStringOneByte(\n    _In_ JsValueRef value,\n    _In_ int start,\n    _In_ int length,\n    _Out_opt_ char* buffer,\n    _Out_opt_ size_t* written);\n\n/// <summary>\n///     Obtains frequently used properties of a data view.\n/// </summary>\n/// <param name=\"dataView\">The data view instance.</param>\n/// <param name=\"arrayBuffer\">The ArrayBuffer backstore of the view.</param>\n/// <param name=\"byteOffset\">The offset in bytes from the start of arrayBuffer referenced by the array.</param>\n/// <param name=\"byteLength\">The number of bytes in the array.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsGetDataViewInfo(\n        _In_ JsValueRef dataView,\n        _Out_opt_ JsValueRef *arrayBuffer,\n        _Out_opt_ unsigned int *byteOffset,\n        _Out_opt_ unsigned int *byteLength);\n\n/// <summary>\n///     Determine if one JavaScript value is less than another JavaScript value.\n/// </summary>\n/// <remarks>\n///     <para>\n///     This function is equivalent to the <c>&lt;</c> operator in Javascript.\n///     </para>\n///     <para>\n///     Requires an active script context.\n///     </para>\n/// </remarks>\n/// <param name=\"object1\">The first object to compare.</param>\n/// <param name=\"object2\">The second object to compare.</param>\n/// <param name=\"result\">Whether object1 is less than object2.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsLessThan(\n        _In_ JsValueRef object1,\n        _In_ JsValueRef object2,\n        _Out_ bool *result);\n\n/// <summary>\n///     Determine if one JavaScript value is less than or equal to another JavaScript value.\n/// </summary>\n/// <remarks>\n///     <para>\n///     This function is equivalent to the <c>&lt;=</c> operator in Javascript.\n///     </para>\n///     <para>\n///     Requires an active script context.\n///     </para>\n/// </remarks>\n/// <param name=\"object1\">The first object to compare.</param>\n/// <param name=\"object2\">The second object to compare.</param>\n/// <param name=\"result\">Whether object1 is less than or equal to object2.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsLessThanOrEqual(\n        _In_ JsValueRef object1,\n        _In_ JsValueRef object2,\n        _Out_ bool *result);\n\n/// <summary>\n///     Creates a new object (with prototype) that stores some external data.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"data\">External data that the object will represent. May be null.</param>\n/// <param name=\"finalizeCallback\">\n///     A callback for when the object is finalized. May be null.\n/// </param>\n/// <param name=\"prototype\">Prototype object or nullptr.</param>\n/// <param name=\"object\">The new object.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsCreateExternalObjectWithPrototype(\n        _In_opt_ void *data,\n        _In_opt_ JsFinalizeCallback finalizeCallback,\n        _In_opt_ JsValueRef prototype,\n        _Out_ JsValueRef *object);\n\n/// <summary>\n///     Gets an object's property.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"object\">The object that contains the property.</param>\n/// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n/// <param name=\"value\">The value of the property.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsObjectGetProperty(\n        _In_ JsValueRef object,\n        _In_ JsValueRef key,\n        _Out_ JsValueRef *value);\n\n/// <summary>\n///     Puts an object's property.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"object\">The object that contains the property.</param>\n/// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n/// <param name=\"value\">The new value of the property.</param>\n/// <param name=\"useStrictRules\">The property set should follow strict mode rules.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsObjectSetProperty(\n        _In_ JsValueRef object,\n        _In_ JsValueRef key,\n        _In_ JsValueRef value,\n        _In_ bool useStrictRules);\n\n/// <summary>\n///     Determines whether an object has a property.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"object\">The object that may contain the property.</param>\n/// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n/// <param name=\"hasProperty\">Whether the object (or a prototype) has the property.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsObjectHasProperty(\n        _In_ JsValueRef object,\n        _In_ JsValueRef key,\n        _Out_ bool *hasProperty);\n\n/// <summary>\n///     Defines a new object's own property from a property descriptor.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"object\">The object that has the property.</param>\n/// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n/// <param name=\"propertyDescriptor\">The property descriptor.</param>\n/// <param name=\"result\">Whether the property was defined.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsObjectDefineProperty(\n        _In_ JsValueRef object,\n        _In_ JsValueRef key,\n        _In_ JsValueRef propertyDescriptor,\n        _Out_ bool *result);\n\n/// <summary>\n///     Deletes an object's property.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"object\">The object that contains the property.</param>\n/// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n/// <param name=\"useStrictRules\">The property set should follow strict mode rules.</param>\n/// <param name=\"result\">Whether the property was deleted.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsObjectDeleteProperty(\n        _In_ JsValueRef object,\n        _In_ JsValueRef key,\n        _In_ bool useStrictRules,\n        _Out_ JsValueRef *result);\n\n/// <summary>\n///     Gets a property descriptor for an object's own property.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"object\">The object that has the property.</param>\n/// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n/// <param name=\"propertyDescriptor\">The property descriptor.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsObjectGetOwnPropertyDescriptor(\n        _In_ JsValueRef object,\n        _In_ JsValueRef key,\n        _Out_ JsValueRef *propertyDescriptor);\n\n/// <summary>\n///     Determines whether an object has a non-inherited property.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"object\">The object that may contain the property.</param>\n/// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n/// <param name=\"hasOwnProperty\">Whether the object has the non-inherited property.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsObjectHasOwnProperty(\n        _In_ JsValueRef object,\n        _In_ JsValueRef key,\n        _Out_ bool *hasOwnProperty);\n\n/// <summary>\n///     Sets whether any action should be taken when a promise is rejected with no reactions\n///     or a reaction is added to a promise that was rejected before it had reactions.\n///     By default in either of these cases nothing occurs.\n///     This function allows you to specify if something should occur and provide a callback\n///     to implement whatever should occur.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n/// </remarks>\n/// <param name=\"promiseRejectionTrackerCallback\">The callback function being set.</param>\n/// <param name=\"callbackState\">\n///     User provided state that will be passed back to the callback.\n/// </param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsSetHostPromiseRejectionTracker(\n        _In_ JsHostPromiseRejectionTrackerCallback promiseRejectionTrackerCallback, \n        _In_opt_ void *callbackState);\n\n/// <summary>\n///     Retrieve the namespace object for a module.\n/// </summary>\n/// <remarks>\n///     Requires an active script context and that the module has already been evaluated.\n/// </remarks>\n/// <param name=\"requestModule\">The JsModuleRecord for which the namespace is being requested.</param>\n/// <param name=\"moduleNamespace\">A JsValueRef - the requested namespace object.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsGetModuleNamespace(\n        _In_ JsModuleRecord requestModule,\n        _Outptr_result_maybenull_ JsValueRef *moduleNamespace);\n\n/// <summary>\n///     Determines if a provided object is a JavscriptProxy Object and\n///     provides references to a Proxy's target and handler.\n/// </summary>\n/// <remarks>\n///     Requires an active script context.\n///     If object is not a Proxy object the target and handler parameters are not touched.\n///     If nullptr is supplied for target or handler the function returns after\n///     setting the isProxy value.\n///     If the object is a revoked Proxy target and handler are set to JS_INVALID_REFERENCE.\n///     If it is a Proxy object that has not been revoked target and handler are set to the\n///     the object's target and handler.\n/// </remarks>\n/// <param name=\"object\">The object that may be a Proxy.</param>\n/// <param name=\"isProxy\">Pointer to a Boolean - is the object a proxy?</param>\n/// <param name=\"target\">Pointer to a JsValueRef - the object's target.</param>\n/// <param name=\"handler\">Pointer to a JsValueRef - the object's handler.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsGetProxyProperties(\n        _In_ JsValueRef object,\n        _Out_ bool* isProxy,\n        _Out_opt_ JsValueRef* target,\n        _Out_opt_ JsValueRef* handler);\n\n/// <summary>\n///     Parses a script and stores the generated parser state cache into a buffer which can be reused.\n/// </summary>\n/// <remarks>\n///     <para>\n///     <c>JsSerializeParserState</c> parses a script and then stores a cache of the parser state\n///     in a runtime-independent format. The parser state may be deserialized in any runtime along\n///     with the same script to skip the initial parse phase.\n///     </para>\n///     <para>\n///         Requires an active script context.\n///     </para>\n///     <para>\n///         Script source can be either JavascriptString or JavascriptExternalArrayBuffer.\n///         In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16,\n///         JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes.\n///     </para>\n///     <para>\n///         Use JavascriptExternalArrayBuffer with Utf8/ASCII script source\n///         for better performance and smaller memory footprint.\n///     </para>\n/// </remarks>\n/// <param name=\"scriptVal\">The script to parse.</param>\n/// <param name=\"bufferVal\">The buffer to put the serialized parser state cache into.</param>\n/// <param name=\"parseAttributes\">Encoding for the script.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsSerializeParserState(\n        _In_ JsValueRef scriptVal,\n        _Out_ JsValueRef *bufferVal,\n        _In_ JsParseScriptAttributes parseAttributes);\n\n/// <summary>\n///     Deserializes the cache of initial parser state and (along with the same\n///     script source) executes the script and returns the result.\n/// </summary>\n/// <remarks>\n///     <para>\n///         Requires an active script context.\n///     </para>\n///     <para>\n///         Script source can be either JavascriptString or JavascriptExternalArrayBuffer.\n///         In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16,\n///         JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes.\n///     </para>\n///     <para>\n///         Use JavascriptExternalArrayBuffer with Utf8/ASCII script source\n///         for better performance and smaller memory footprint.\n///     </para>\n/// </remarks>\n/// <param name=\"script\">The script to run.</param>\n/// <param name=\"sourceContext\">\n///     A cookie identifying the script that can be used by debuggable script contexts.\n/// </param>\n/// <param name=\"sourceUrl\">The location the script came from</param>\n/// <param name=\"parseAttributes\">Attribute mask for parsing the script</param>\n/// <param name=\"parserState\">\n///     A buffer containing a cache of the parser state generated by <c>JsSerializeParserState</c>.\n/// </param>\n/// <param name=\"result\">The result of the script, if any. This parameter can be null.</param>\n/// <returns>\n///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n/// </returns>\nCHAKRA_API\n    JsRunScriptWithParserState(\n        _In_ JsValueRef script,\n        _In_ JsSourceContext sourceContext,\n        _In_ JsValueRef sourceUrl,\n        _In_ JsParseScriptAttributes parseAttributes,\n        _In_ JsValueRef parserState,\n        _Out_ JsValueRef * result);\n\n#endif // _CHAKRACOREBUILD\n#endif // _CHAKRACORE_H_\n"
  },
  {
    "path": "include/ChakraCoreVersion.h",
    "content": "//-------------------------------------------------------------------------------------------------------\n// Copyright (C) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n//-------------------------------------------------------------------------------------------------------\n#pragma once\n\n// NOTE: When changing this file, you may need to update the GUID in ByteCodeCacheReleaseFileVersion.h\n// Please update the GUID when:\n// * CHAKRA_CORE_VERSION_RELEASE is changed to 1\n// * CHAKRA_CORE_VERSION_RELEASE is currently set to 1 and the bytecode changes\n// See notes below about ReleaseVersioningScheme.\n\n// --------------\n// VERSION NUMBER\n// --------------\n\n// ChakraCore version number definitions (used in ChakraCore binary metadata)\n#define CHAKRA_CORE_MAJOR_VERSION 1\n#define CHAKRA_CORE_MINOR_VERSION 11\n#define CHAKRA_CORE_PATCH_VERSION 24\n#define CHAKRA_CORE_VERSION_RELEASE_QFE 0 // Redundant with PATCH_VERSION. Keep this value set to 0.\n\n// -------------\n// RELEASE FLAGS\n// -------------\n\n// NOTE: CHAKRA_CORE_VERSION_PRERELEASE can only be set to 1 when\n// CHAKRA_CORE_VERSION_RELEASE is set to 1, or there is no effect.\n// Here are the meanings of the various combinations:\n//\n//                  RELEASE**   PRERELEASE\n// DEVELOPMENT      0           0\n// <INVALID>        0           1           # INVALID but identical to DEVELOPMENT\n// RELEASE**        1           0           #\n// PRERELEASE       1           1\n//                  ** Release flags are not related to build type (e.g. x64_release)\n//\n// Unless otherwise noted, the code affected by these flags lies mostly in bin/CoreCommon.ver\n//\n// DEVELOPMENT:\n// * Uses EngineeringVersioningScheme (see lib/Runtime/ByteCode/ByteCodeSerializer.cpp)\n// * Sets file flag VS_FF_PRIVATEBUILD\n// * Adds \"Private\" to the file description\n//\n// RELEASE** and PRERELEASE (i.e. controlled by CHAKRA_CORE_VERSION_RELEASE flag):\n// * Uses ReleaseVersioningScheme (see lib/Runtime/ByteCode/ByteCodeSerializer.cpp)\n//\n// PRERELEASE (preparing for release but not yet ready to release):\n// * Sets file flag VS_FF_PRERELEASE\n// * Adds \"Pre-release\" to the file description\n//\n// RELEASE** (code is ready to release)\n// * Sets neither of the file flags noted above\n// * Does not add anything to the file description\n\n// ChakraCore RELEASE and PRERELEASE flags\n#define CHAKRA_CORE_VERSION_RELEASE 1\n#define CHAKRA_CORE_VERSION_PRERELEASE 0\n\n// Chakra RELEASE flag\n// Mostly redundant with CHAKRA_CORE_VERSION_RELEASE,\n// but semantically refers to Chakra rather than ChakraCore.\n#define CHAKRA_VERSION_RELEASE 0\n"
  },
  {
    "path": "include/ChakraDebug.h",
    "content": "//-------------------------------------------------------------------------------------------------------\n// Copyright (C) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n//-------------------------------------------------------------------------------------------------------\n/// \\mainpage Chakra Hosting Debugging API Reference\n///\n/// Chakra is Microsoft's JavaScript engine. It is an integral part of Internet Explorer but can\n/// also be hosted independently by other applications. This reference describes the APIs available\n/// to applications to debug JavaScript.\n\n/// \\file\n/// \\brief The Chakra hosting debugging API.\n///\n/// This file contains a flat C API layer. This is the API exported by ChakraCore.dll.\n\n#ifdef _MSC_VER\n#pragma once\n#endif  // _MSC_VER\n\n#ifndef _CHAKRADEBUG_H_\n#define _CHAKRADEBUG_H_\n\n#ifdef _WIN32\n//Other platforms already include <stdint.h> and have this defined automatically\ntypedef __int64 int64_t;\ntypedef unsigned __int32 uint32_t;\n#endif\n\n    /// <summary>\n    ///     Debug events reported from ChakraCore engine.\n    /// </summary>\n    typedef enum _JsDiagDebugEvent\n    {\n        /// <summary>\n        ///     Indicates a new script being compiled, this includes script, eval, new function.\n        /// </summary>\n        JsDiagDebugEventSourceCompile = 0,\n        /// <summary>\n        ///     Indicates compile error for a script.\n        /// </summary>\n        JsDiagDebugEventCompileError = 1,\n        /// <summary>\n        ///     Indicates a break due to a breakpoint.\n        /// </summary>\n        JsDiagDebugEventBreakpoint = 2,\n        /// <summary>\n        ///     Indicates a break after completion of step action.\n        /// </summary>\n        JsDiagDebugEventStepComplete = 3,\n        /// <summary>\n        ///     Indicates a break due to debugger statement.\n        /// </summary>\n        JsDiagDebugEventDebuggerStatement = 4,\n        /// <summary>\n        ///     Indicates a break due to async break.\n        /// </summary>\n        JsDiagDebugEventAsyncBreak = 5,\n        /// <summary>\n        ///     Indicates a break due to a runtime script exception.\n        /// </summary>\n        JsDiagDebugEventRuntimeException = 6\n    } JsDiagDebugEvent;\n\n    /// <summary>\n    ///     Break on Exception attributes.\n    /// </summary>\n    typedef enum _JsDiagBreakOnExceptionAttributes\n    {\n        /// <summary>\n        ///     Don't break on any exception.\n        /// </summary>\n        JsDiagBreakOnExceptionAttributeNone = 0x0,\n        /// <summary>\n        ///     Break on uncaught exception.\n        /// </summary>\n        JsDiagBreakOnExceptionAttributeUncaught = 0x1,\n        /// <summary>\n        ///     Break on first chance exception.\n        /// </summary>\n        JsDiagBreakOnExceptionAttributeFirstChance = 0x2\n    } JsDiagBreakOnExceptionAttributes;\n\n    /// <summary>\n    ///     Stepping types.\n    /// </summary>\n    typedef enum _JsDiagStepType\n    {\n        /// <summary>\n        ///     Perform a step operation to next statement.\n        /// </summary>\n        JsDiagStepTypeStepIn = 0,\n        /// <summary>\n        ///     Perform a step out from the current function.\n        /// </summary>\n        JsDiagStepTypeStepOut = 1,\n        /// <summary>\n        ///     Perform a single step over after a debug break if the next statement is a function call, else behaves as a stepin.\n        /// </summary>\n        JsDiagStepTypeStepOver = 2,\n        /// <summary>\n        ///     Perform a single step back to the previous statement (only applicable in TTD mode).\n        /// </summary>\n        JsDiagStepTypeStepBack = 3,\n        /// <summary>\n        ///     Perform a reverse continue operation (only applicable in TTD mode).\n        /// </summary>\n        JsDiagStepTypeReverseContinue = 4,\n        /// <summary>\n        ///     Perform a forward continue operation. Clears any existing step value.\n        /// </summary>\n        JsDiagStepTypeContinue = 5\n    } JsDiagStepType;\n\n    /// <summary>\n    ///     User implemented callback routine for debug events.\n    /// </summary>\n    /// <remarks>\n    ///     Use <c>JsDiagStartDebugging</c> to register the callback.\n    /// </remarks>\n    /// <param name=\"debugEvent\">The type of JsDiagDebugEvent event.</param>\n    /// <param name=\"eventData\">Additional data related to the debug event.</param>\n    /// <param name=\"callbackState\">The state passed to <c>JsDiagStartDebugging</c>.</param>\n    typedef void (CHAKRA_CALLBACK * JsDiagDebugEventCallback)(_In_ JsDiagDebugEvent debugEvent, _In_ JsValueRef eventData, _In_opt_ void* callbackState);\n\n    /// <summary>\n    ///     Starts debugging in the given runtime.\n    /// </summary>\n    /// <param name=\"runtimeHandle\">Runtime to put into debug mode.</param>\n    /// <param name=\"debugEventCallback\">Registers a callback to be called on every JsDiagDebugEvent.</param>\n    /// <param name=\"callbackState\">User provided state that will be passed back to the callback.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The runtime should be active on the current thread and should not be in debug state.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagStartDebugging(\n            _In_ JsRuntimeHandle runtimeHandle,\n            _In_ JsDiagDebugEventCallback debugEventCallback,\n            _In_opt_ void* callbackState);\n\n    /// <summary>\n    ///     Stops debugging in the given runtime.\n    /// </summary>\n    /// <param name=\"runtimeHandle\">Runtime to stop debugging.</param>\n    /// <param name=\"callbackState\">User provided state that was passed in JsDiagStartDebugging.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The runtime should be active on the current thread and in debug state.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagStopDebugging(\n            _In_ JsRuntimeHandle runtimeHandle,\n            _Out_opt_ void** callbackState);\n\n    /// <summary>\n    ///     Request the runtime to break on next JavaScript statement.\n    /// </summary>\n    /// <param name=\"runtimeHandle\">Runtime to request break.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The runtime should be in debug state. This API can be called from another runtime.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagRequestAsyncBreak(\n            _In_ JsRuntimeHandle runtimeHandle);\n\n    /// <summary>\n    ///     List all breakpoints in the current runtime.\n    /// </summary>\n    /// <param name=\"breakpoints\">Array of breakpoints.</param>\n    /// <remarks>\n    ///     <para>\n    ///     [{\n    ///         \"breakpointId\" : 1,\n    ///         \"scriptId\" : 1,\n    ///         \"line\" : 0,\n    ///         \"column\" : 62\n    ///     }]\n    ///     </para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The current runtime should be in debug state. This API can be called when runtime is at a break or running.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagGetBreakpoints(\n            _Out_ JsValueRef *breakpoints);\n\n    /// <summary>\n    ///     Sets breakpoint in the specified script at give location.\n    /// </summary>\n    /// <param name=\"scriptId\">Id of script from JsDiagGetScripts or JsDiagGetSource to put breakpoint.</param>\n    /// <param name=\"lineNumber\">0 based line number to put breakpoint.</param>\n    /// <param name=\"columnNumber\">0 based column number to put breakpoint.</param>\n    /// <param name=\"breakpoint\">Breakpoint object with id, line and column if success.</param>\n    /// <remarks>\n    ///     <para>\n    ///     {\n    ///         \"breakpointId\" : 1,\n    ///         \"line\" : 2,\n    ///         \"column\" : 4\n    ///     }\n    ///     </para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The current runtime should be in debug state. This API can be called when runtime is at a break or running.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagSetBreakpoint(\n            _In_ unsigned int scriptId,\n            _In_ unsigned int lineNumber,\n            _In_ unsigned int columnNumber,\n            _Out_ JsValueRef *breakpoint);\n\n    /// <summary>\n    ///     Remove a breakpoint.\n    /// </summary>\n    /// <param name=\"breakpointId\">Breakpoint id returned from JsDiagSetBreakpoint.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The current runtime should be in debug state. This API can be called when runtime is at a break or running.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagRemoveBreakpoint(\n            _In_ unsigned int breakpointId);\n\n    /// <summary>\n    ///     Sets break on exception handling.\n    /// </summary>\n    /// <param name=\"runtimeHandle\">Runtime to set break on exception attributes.</param>\n    /// <param name=\"exceptionAttributes\">Mask of JsDiagBreakOnExceptionAttributes to set.</param>\n    /// <remarks>\n    ///     <para>\n    ///         If this API is not called the default value is set to JsDiagBreakOnExceptionAttributeUncaught in the runtime.\n    ///     </para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The runtime should be in debug state. This API can be called from another runtime.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagSetBreakOnException(\n            _In_ JsRuntimeHandle runtimeHandle,\n            _In_ JsDiagBreakOnExceptionAttributes exceptionAttributes);\n\n    /// <summary>\n    ///     Gets break on exception setting.\n    /// </summary>\n    /// <param name=\"runtimeHandle\">Runtime from which to get break on exception attributes, should be in debug mode.</param>\n    /// <param name=\"exceptionAttributes\">Mask of JsDiagBreakOnExceptionAttributes.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The runtime should be in debug state. This API can be called from another runtime.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagGetBreakOnException(\n            _In_ JsRuntimeHandle runtimeHandle,\n            _Out_ JsDiagBreakOnExceptionAttributes* exceptionAttributes);\n\n    /// <summary>\n    ///     Sets the step type in the runtime after a debug break.\n    /// </summary>\n    /// <remarks>\n    ///     Requires to be at a debug break.\n    /// </remarks>\n    /// <param name=\"resumeType\">Type of JsDiagStepType.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The current runtime should be in debug state. This API can only be called when runtime is at a break.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagSetStepType(\n            _In_ JsDiagStepType stepType);\n\n    /// <summary>\n    ///     Gets list of scripts.\n    /// </summary>\n    /// <param name=\"scriptsArray\">Array of script objects.</param>\n    /// <remarks>\n    ///     <para>\n    ///     [{\n    ///         \"scriptId\" : 2,\n    ///         \"fileName\" : \"c:\\\\Test\\\\Test.js\",\n    ///         \"lineCount\" : 4,\n    ///         \"sourceLength\" : 111\n    ///       }, {\n    ///         \"scriptId\" : 3,\n    ///         \"parentScriptId\" : 2,\n    ///         \"scriptType\" : \"eval code\",\n    ///         \"lineCount\" : 1,\n    ///         \"sourceLength\" : 12\n    ///     }]\n    ///     </para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The current runtime should be in debug state. This API can be called when runtime is at a break or running.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagGetScripts(\n            _Out_ JsValueRef *scriptsArray);\n\n    /// <summary>\n    ///     Gets source for a specific script identified by scriptId from JsDiagGetScripts.\n    /// </summary>\n    /// <param name=\"scriptId\">Id of the script.</param>\n    /// <param name=\"source\">Source object.</param>\n    /// <remarks>\n    ///     <para>\n    ///     {\n    ///         \"scriptId\" : 1,\n    ///         \"fileName\" : \"c:\\\\Test\\\\Test.js\",\n    ///         \"lineCount\" : 12,\n    ///         \"sourceLength\" : 15154,\n    ///         \"source\" : \"var x = 1;\"\n    ///     }\n    ///     </para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The current runtime should be in debug state. This API can be called when runtime is at a break or running.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagGetSource(\n            _In_ unsigned int scriptId,\n            _Out_ JsValueRef *source);\n\n    /// <summary>\n    ///     Gets the source information for a function object.\n    /// </summary>\n    /// <param name=\"function\">JavaScript function.</param>\n    /// <param name=\"functionPosition\">Function position - scriptId, start line, start column, line number of first statement, column number of first statement.</param>\n    /// <remarks>\n    ///     <para>\n    ///     {\n    ///         \"scriptId\" : 1,\n    ///         \"fileName\" : \"c:\\\\Test\\\\Test.js\",\n    ///         \"line\" : 1,\n    ///         \"column\" : 2,\n    ///         \"firstStatementLine\" : 6,\n    ///         \"firstStatementColumn\" : 0\n    ///     }\n    ///     </para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     This API can be called when runtime is at a break or running.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagGetFunctionPosition(\n            _In_ JsValueRef function,\n            _Out_ JsValueRef *functionPosition);\n\n    /// <summary>\n    ///     Gets the stack trace information.\n    /// </summary>\n    /// <param name=\"stackTrace\">Stack trace information.</param>\n    /// <remarks>\n    ///     <para>\n    ///     [{\n    ///         \"index\" : 0,\n    ///         \"scriptId\" : 2,\n    ///         \"line\" : 3,\n    ///         \"column\" : 0,\n    ///         \"sourceLength\" : 9,\n    ///         \"sourceText\" : \"var x = 1\",\n    ///         \"functionHandle\" : 1\n    ///     }]\n    ///    </para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The current runtime should be in debug state. This API can only be called when runtime is at a break.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagGetStackTrace(\n            _Out_ JsValueRef *stackTrace);\n\n    /// <summary>\n    ///     Gets the list of properties corresponding to the frame.\n    /// </summary>\n    /// <param name=\"stackFrameIndex\">Index of stack frame from JsDiagGetStackTrace.</param>\n    /// <param name=\"properties\">Object of properties array (properties, scopes and globals).</param>\n    /// <remarks>\n    ///     <para>\n    ///     propertyAttributes is a bit mask of\n    ///         NONE = 0x1,\n    ///         HAVE_CHILDRENS = 0x2,\n    ///         READ_ONLY_VALUE = 0x4,\n    ///         IN_TDZ = 0x8,\n    ///     </para>\n    ///     <para>\n    ///     {\n    ///         \"thisObject\": {\n    ///             \"name\": \"this\",\n    ///             \"type\" : \"object\",\n    ///             \"className\" : \"Object\",\n    ///             \"display\" : \"{...}\",\n    ///             \"propertyAttributes\" : 1,\n    ///             \"handle\" : 306\n    ///         },\n    ///         \"exception\" : {\n    ///             \"name\" : \"{exception}\",\n    ///             \"type\" : \"object\",\n    ///             \"display\" : \"'a' is undefined\",\n    ///             \"className\" : \"Error\",\n    ///             \"propertyAttributes\" : 1,\n    ///             \"handle\" : 307\n    ///         }\n    ///         \"arguments\" : {\n    ///             \"name\" : \"arguments\",\n    ///             \"type\" : \"object\",\n    ///             \"display\" : \"{...}\",\n    ///             \"className\" : \"Object\",\n    ///             \"propertyAttributes\" : 1,\n    ///             \"handle\" : 190\n    ///         },\n    ///         \"returnValue\" : {\n    ///             \"name\" : \"[Return value]\",\n    ///             \"type\" : \"undefined\",\n    ///             \"propertyAttributes\" : 0,\n    ///             \"handle\" : 192\n    ///         },\n    ///         \"functionCallsReturn\" : [{\n    ///                 \"name\" : \"[foo1 returned]\",\n    ///                 \"type\" : \"number\",\n    ///                 \"value\" : 1,\n    ///                 \"propertyAttributes\" : 2,\n    ///                 \"handle\" : 191\n    ///             }\n    ///         ],\n    ///         \"locals\" : [],\n    ///         \"scopes\" : [{\n    ///                 \"index\" : 0,\n    ///                 \"handle\" : 193\n    ///             }\n    ///         ],\n    ///         \"globals\" : {\n    ///             \"handle\" : 194\n    ///         }\n    ///     }\n    ///     </para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The current runtime should be in debug state. This API can only be called when runtime is at a break.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagGetStackProperties(\n            _In_ unsigned int stackFrameIndex,\n            _Out_ JsValueRef *properties);\n\n    /// <summary>\n    ///     Gets the list of children of a handle.\n    /// </summary>\n    /// <param name=\"objectHandle\">Handle of object.</param>\n    /// <param name=\"fromCount\">0-based from count of properties, usually 0.</param>\n    /// <param name=\"totalCount\">Number of properties to return.</param>\n    /// <param name=\"propertiesObject\">Array of properties.</param>\n    /// <remarks>Handle should be from objects returned from call to JsDiagGetStackProperties.</remarks>\n    /// <remarks>For scenarios where object have large number of properties totalCount can be used to control how many properties are given.</remarks>\n    /// <remarks>\n    ///     <para>\n    ///     {\n    ///         \"totalPropertiesOfObject\": 10,\n    ///         \"properties\" : [{\n    ///                 \"name\" : \"__proto__\",\n    ///                 \"type\" : \"object\",\n    ///                 \"display\" : \"{...}\",\n    ///                 \"className\" : \"Object\",\n    ///                 \"propertyAttributes\" : 1,\n    ///                 \"handle\" : 156\n    ///             }\n    ///         ],\n    ///         \"debuggerOnlyProperties\" : [{\n    ///                 \"name\" : \"[Map]\",\n    ///                 \"type\" : \"string\",\n    ///                 \"value\" : \"size = 0\",\n    ///                 \"propertyAttributes\" : 2,\n    ///                 \"handle\" : 157\n    ///             }\n    ///         ]\n    ///     }\n    ///     </para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The current runtime should be in debug state. This API can only be called when runtime is at a break.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagGetProperties(\n            _In_ unsigned int objectHandle,\n            _In_ unsigned int fromCount,\n            _In_ unsigned int totalCount,\n            _Out_ JsValueRef *propertiesObject);\n\n    /// <summary>\n    ///     Gets the object corresponding to handle.\n    /// </summary>\n    /// <param name=\"objectHandle\">Handle of object.</param>\n    /// <param name=\"handleObject\">Object corresponding to the handle.</param>\n    /// <remarks>\n    ///     <para>\n    ///     {\n    ///         \"scriptId\" : 24,\n    ///          \"line\" : 1,\n    ///          \"column\" : 63,\n    ///          \"name\" : \"foo\",\n    ///          \"type\" : \"function\",\n    ///          \"handle\" : 2\n    ///     }\n    ///    </para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    /// <remarks>\n    ///     The current runtime should be in debug state. This API can only be called when runtime is at a break.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagGetObjectFromHandle(\n            _In_ unsigned int objectHandle,\n            _Out_ JsValueRef *handleObject);\n\n    /// <summary>\n    ///     Evaluates an expression on given frame.\n    /// </summary>\n    /// <param name=\"expression\">\n    ///     Javascript String or ArrayBuffer (incl. ExternalArrayBuffer).\n    /// </param>\n    /// <param name=\"stackFrameIndex\">Index of stack frame on which to evaluate the expression.</param>\n    /// <param name=\"parseAttributes\">\n    ///     Defines how `expression` (JsValueRef) should be parsed.\n    ///     - `JsParseScriptAttributeNone` when `expression` is a Utf8 encoded ArrayBuffer and/or a Javascript String (encoding independent)\n    ///     - `JsParseScriptAttributeArrayBufferIsUtf16Encoded` when `expression` is Utf16 Encoded ArrayBuffer\n    ///     - `JsParseScriptAttributeLibraryCode` has no use for this function and has similar effect with `JsParseScriptAttributeNone`\n    /// </param>\n    /// <param name=\"forceSetValueProp\">Forces the result to contain the raw value of the expression result.</param>\n    /// <param name=\"evalResult\">Result of evaluation.</param>\n    /// <remarks>\n    ///     <para>\n    ///     evalResult when evaluating 'this' and return is JsNoError\n    ///     {\n    ///         \"name\" : \"this\",\n    ///         \"type\" : \"object\",\n    ///         \"className\" : \"Object\",\n    ///         \"display\" : \"{...}\",\n    ///         \"propertyAttributes\" : 1,\n    ///         \"handle\" : 18\n    ///     }\n    ///\n    ///     evalResult when evaluating a script which throws JavaScript error and return is JsErrorScriptException\n    ///     {\n    ///         \"name\" : \"a.b.c\",\n    ///         \"type\" : \"object\",\n    ///         \"className\" : \"Error\",\n    ///         \"display\" : \"'a' is undefined\",\n    ///         \"propertyAttributes\" : 1,\n    ///         \"handle\" : 18\n    ///     }\n    ///     </para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, evalResult will contain the result\n    ///     The code <c>JsErrorScriptException</c> if evaluate generated a JavaScript exception, evalResult will contain the error details\n    ///     Other error code for invalid parameters or API was not called at break\n    /// </returns>\n    /// <remarks>\n    ///     The current runtime should be in debug state. This API can only be called when runtime is at a break.\n    /// </remarks>\n    CHAKRA_API\n        JsDiagEvaluate(\n            _In_ JsValueRef expression,\n            _In_ unsigned int stackFrameIndex,\n            _In_ JsParseScriptAttributes parseAttributes,\n            _In_ bool forceSetValueProp,\n            _Out_ JsValueRef *evalResult);\n\n    /////////////////////\n    /// <summary>\n    ///     TimeTravel move options as bit flag enum.\n    /// </summary>\n    typedef enum _JsTTDMoveModes\n    {\n        /// <summary>\n        ///     Indicates no special actions needed for move.\n        /// </summary>\n        JsTTDMoveNone = 0x0,\n\n        /// <summary>\n        ///     Indicates that we want to move to the first event.\n        /// </summary>\n        JsTTDMoveFirstEvent = 0x1,\n\n        /// <summary>\n        ///     Indicates that we want to move to the last event.\n        /// </summary>\n        JsTTDMoveLastEvent = 0x2,\n\n        /// <summary>\n        ///     Indicates that we want to move to the kth event -- top 32 bits are event count.\n        /// </summary>\n        JsTTDMoveKthEvent = 0x4,\n\n        /// <summary>\n        ///     Indicates if we are doing the scan for a continue operation\n        /// </summary>\n        JsTTDMoveScanIntervalForContinue = 0x10,\n\n        /// <summary>\n        ///     Indicates if we are doing the scan for a continue operation and are in the time-segment where the active breakpoint was\n        /// </summary>\n        JsTTDMoveScanIntervalForContinueInActiveBreakpointSegment = 0x20,\n\n        /// <summary>\n        ///     Indicates if we want to set break on entry or just run and let something else trigger breakpoints.\n        /// </summary>\n        JsTTDMoveBreakOnEntry = 0x100\n    } JsTTDMoveMode;\n\n    /// <summary>\n    ///     A handle for URI's that TTD information is written to/read from.\n    /// </summary>\n    typedef void* JsTTDStreamHandle;\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Construct a JsTTDStreamHandle that will be used to read/write the event log portion of the TTD data based on the uri\n    ///     provided by JsTTDInitializeUriCallback.\n    /// </summary>\n    /// <remarks>\n    ///     <para>Exactly one of read or write will be set to true.</para>\n    /// </remarks>\n    /// <param name=\"uriLength\">The length of the uri array that the host passed in for storing log info.</param>\n    /// <param name=\"uri\">The URI that the host passed in for storing log info.</param>\n    /// <param name=\"asciiNameLength\">The length of the ascii name array that the host passed in for storing log info.</param>\n    /// <param name=\"asciiResourceName\">An optional ascii string giving a unique name to the resource that the JsTTDStreamHandle will be created for.</param>\n    /// <param name=\"read\">If the handle should be opened for reading.</param>\n    /// <param name=\"write\">If the handle should be opened for writing.</param>\n    /// <returns>A JsTTDStreamHandle opened in read/write mode as specified.</returns>\n    typedef JsTTDStreamHandle (CHAKRA_CALLBACK *TTDOpenResourceStreamCallback)(_In_ size_t uriLength, _In_reads_(uriLength) const char* uri, _In_ size_t asciiNameLength, _In_reads_(asciiNameLength) const char* asciiResourceName, _In_ bool read, _In_ bool write);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     A callback for reading data from a handle.\n    /// </summary>\n    /// <param name=\"handle\">The JsTTDStreamHandle to read the data from.</param>\n    /// <param name=\"buff\">The buffer to place the data into.</param>\n    /// <param name=\"size\">The max number of bytes that should be read.</param>\n    /// <param name=\"readCount\">The actual number of bytes read and placed in the buffer.</param>\n    /// <returns>true if the read was successful false otherwise.</returns>\n    typedef bool (CHAKRA_CALLBACK *JsTTDReadBytesFromStreamCallback)(_In_ JsTTDStreamHandle handle, _Out_writes_(size) byte* buff, _In_ size_t size, _Out_ size_t* readCount);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     A callback for writing data to a handle.\n    /// </summary>\n    /// <param name=\"handle\">The JsTTDStreamHandle to write the data to.</param>\n    /// <param name=\"buff\">The buffer to copy the data from.</param>\n    /// <param name=\"size\">The max number of bytes that should be written.</param>\n    /// <param name=\"readCount\">The actual number of bytes written to the HANDLE.</param>\n    /// <returns>true if the write was successful false otherwise.</returns>\n    typedef bool (CHAKRA_CALLBACK *JsTTDWriteBytesToStreamCallback)(_In_ JsTTDStreamHandle handle, _In_reads_(size) const byte* buff, _In_ size_t size, _Out_ size_t* writtenCount);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Flush and close the stream represented by the HANDLE as needed.\n    /// </summary>\n    /// <remarks>\n    ///     <para>Exactly one of read or write will be set to true.</para>\n    /// </remarks>\n    /// <param name=\"handle\">The JsTTDStreamHandle to close.</param>\n    /// <param name=\"read\">If the handle was opened for reading.</param>\n    /// <param name=\"write\">If the handle was opened for writing.</param>\n    typedef void (CHAKRA_CALLBACK *JsTTDFlushAndCloseStreamCallback)(_In_ JsTTDStreamHandle handle, _In_ bool read, _In_ bool write);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Creates a new runtime in Record Mode.\n    /// </summary>\n    /// <param name=\"attributes\">The attributes of the runtime to be created.</param>\n    /// <param name=\"enableDebugging\">A flag to enable debugging during record.</param>\n    /// <param name=\"snapInterval\">The interval to wait between snapshots (measured in millis).</param>\n    /// <param name=\"snapHistoryLength\">The amount of history to maintain before discarding -- measured in number of snapshots and controls how far back in time a trace can be reversed.</param>\n    /// <param name=\"openResourceStream\">The <c>TTDOpenResourceStreamCallback</c> function for generating a JsTTDStreamHandle to read/write serialized data.</param>\n    /// <param name=\"writeBytesToStream\">The <c>JsTTDWriteBytesToStreamCallback</c> function for writing bytes to a JsTTDStreamHandle.</param>\n    /// <param name=\"flushAndCloseStream\">The <c>JsTTDFlushAndCloseStreamCallback</c> function for flushing and closing a JsTTDStreamHandle as needed.</param>\n    /// <param name=\"threadService\">The thread service for the runtime. Can be null.</param>\n    /// <param name=\"runtime\">The runtime created.</param>\n    /// <remarks>\n    ///     <para>See <c>JsCreateRuntime</c> for additional information.</para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsTTDCreateRecordRuntime(\n            _In_ JsRuntimeAttributes attributes,\n            _In_ bool enableDebugging,\n            _In_ size_t snapInterval,\n            _In_ size_t snapHistoryLength,\n            _In_ TTDOpenResourceStreamCallback openResourceStream,\n            _In_ JsTTDWriteBytesToStreamCallback writeBytesToStream,\n            _In_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream,\n            _In_opt_ JsThreadServiceCallback threadService,\n            _Out_ JsRuntimeHandle *runtime);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Creates a new runtime in Debug Mode.\n    /// </summary>\n    /// <param name=\"attributes\">The attributes of the runtime to be created.</param>\n    /// <param name=\"infoUri\">The uri where the recorded Time-Travel data should be loaded from.</param>\n    /// <param name=\"enableDebugging\">A flag to enable additional debugging operation support during replay.</param>\n    /// <param name=\"openResourceStream\">The <c>TTDOpenResourceStreamCallback</c> function for generating a JsTTDStreamHandle to read/write serialized data.</param>\n    /// <param name=\"readBytesFromStream\">The <c>JsTTDReadBytesFromStreamCallback</c> function for reading bytes from a JsTTDStreamHandle.</param>\n    /// <param name=\"flushAndCloseStream\">The <c>JsTTDFlushAndCloseStreamCallback</c> function for flushing and closing a JsTTDStreamHandle as needed.</param>\n    /// <param name=\"threadService\">The thread service for the runtime. Can be null.</param>\n    /// <param name=\"runtime\">The runtime created.</param>\n    /// <remarks>\n    ///     <para>See <c>JsCreateRuntime</c> for additional information.</para>\n    /// </remarks>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API\n        JsTTDCreateReplayRuntime(\n            _In_ JsRuntimeAttributes attributes,\n            _In_reads_(infoUriCount) const char* infoUri,\n            _In_ size_t infoUriCount,\n            _In_ bool enableDebugging,\n            _In_ TTDOpenResourceStreamCallback openResourceStream,\n            _In_ JsTTDReadBytesFromStreamCallback readBytesFromStream,\n            _In_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream,\n            _In_opt_ JsThreadServiceCallback threadService,\n            _Out_ JsRuntimeHandle *runtime);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Creates a script context that takes the TTD mode from the log or explicitly is not in TTD mode (regular takes mode from currently active script).\n    /// </summary>\n    /// <param name=\"runtime\">The runtime the script context is being created in.</param>\n    /// <param name=\"useRuntimeTTDMode\">Set to true to use runtime TTD mode false to explicitly be non-TTD context.</param>\n    /// <param name=\"newContext\">The created script context.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API JsTTDCreateContext(\n        _In_ JsRuntimeHandle runtimeHandle,\n        _In_ bool useRuntimeTTDMode,\n        _Out_ JsContextRef *newContext);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Notify the time-travel system that a context has been identified as dead by the gc (and is being de-allocated).\n    /// </summary>\n    /// <param name=\"context\">The script context that is now dead.</param>\n    /// <returns>\n    ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n    /// </returns>\n    CHAKRA_API JsTTDNotifyContextDestroy(\n        _In_ JsContextRef context);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Start Time-Travel record or replay at next turn of event loop.\n    /// </summary>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDStart();\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Stop Time-Travel record or replay.\n    /// </summary>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDStop();\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Pause Time-Travel recording before executing code on behalf of debugger or other diagnostic/telemetry.\n    /// </summary>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDPauseTimeTravelBeforeRuntimeOperation();\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     ReStart Time-Travel recording after executing code on behalf of debugger or other diagnostic/telemetry.\n    /// </summary>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDReStartTimeTravelAfterRuntimeOperation();\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Notify the Js runtime we are at a safe yield point in the event loop (i.e. no locals on the stack and we can process as desired).\n    /// </summary>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDNotifyYield();\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Notify the TTD runtime that we are doing a weak add on a reference (we may use this in external API calls and the release will happen in a GC callback).\n    /// </summary>\n    /// <param name=\"value\">The value we are adding the ref to.</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDNotifyLongLivedReferenceAdd(_In_ JsValueRef value);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Notify the Js runtime the host is aborting the process and what the status code is.\n    /// </summary>\n    /// <param name=\"statusCode\">The exit status code.</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDHostExit(_In_ int statusCode);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Notify the event log that the contents of one buffer have been copied to a second buffer.\n    /// </summary>\n    /// <param name=\"dst\">The buffer that was written into.</param>\n    /// <param name=\"dstIndex\">The first index modified.</param>\n    /// <param name=\"src\">The buffer that was copied from.</param>\n    /// <param name=\"srcIndex\">The first index copied.</param>\n    /// <param name=\"count\">The number of bytes copied.</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDRawBufferCopySyncIndirect(\n            _In_ JsValueRef dst,\n            _In_ size_t dstIndex,\n            _In_ JsValueRef src,\n            _In_ size_t srcIndex,\n            _In_ size_t count);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Notify the event log that the contents of a naked byte* buffer passed to the host have been modified synchronously.\n    /// </summary>\n    /// <param name=\"buffer\">The buffer that was modified.</param>\n    /// <param name=\"index\">The first index modified.</param>\n    /// <param name=\"count\">The number of bytes written.</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDRawBufferModifySyncIndirect(\n            _In_ JsValueRef buffer,\n            _In_ size_t index,\n            _In_ size_t count);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Get info for notifying the TTD system that a raw buffer it shares with the host has been modified.\n    /// </summary>\n    /// <param name=\"instance\">The array buffer we want to monitor for contents modification.</param>\n    /// <param name=\"initialModPos\">The first position in the buffer that may be modified.</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDRawBufferAsyncModificationRegister(\n            _In_ JsValueRef instance,\n            _In_ byte* initialModPos);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Notify the event log that the contents of a naked byte* buffer passed to the host have been modified asynchronously.\n    /// </summary>\n    /// <param name=\"finalModPos\">One past the last modified position in the buffer.</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDRawBufferAsyncModifyComplete(\n            _In_ byte* finalModPos);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     A check for unimplemented TTD actions in the host.\n    ///     This API is a TEMPORARY API while we complete the implementation of TTD support in the Node host and will be deleted once that is complete.\n    /// </summary>\n    /// <param name=\"msg\">The message to print if we should be catching this as a TTD operation.</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDCheckAndAssertIfTTDRunning(\n            _In_ const char* msg);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Before calling JsTTDMoveToTopLevelEvent (which inflates a snapshot and replays) check to see if we want to reset the script context.\n    ///     We reset the script context if the move will require inflating from a different snapshot that the last one.\n    /// </summary>\n    /// <param name=\"runtimeHandle\">The runtime handle that the script is executing in.</param>\n    /// <param name=\"moveMode\">Flags controlling the way the move it performed and how other parameters are interpreted.</param>\n    /// <param name=\"kthEvent\">When <c>moveMode == JsTTDMoveKthEvent</c> indicates which event, otherwise this parameter is ignored.</param>\n    /// <param name=\"targetEventTime\">The event time we want to move to or -1 if not relevant.</param>\n    /// <param name=\"targetStartSnapTime\">Out parameter with the event time of the snapshot that we should inflate from.</param>\n    /// <param name=\"targetEndSnapTime\">Optional Out parameter with the snapshot time following the event.</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API JsTTDGetSnapTimeTopLevelEventMove(\n        _In_ JsRuntimeHandle runtimeHandle,\n        _In_ JsTTDMoveMode moveMode,\n        _In_opt_ uint32_t kthEvent,\n        _Inout_ int64_t* targetEventTime,\n        _Out_ int64_t* targetStartSnapTime,\n        _Out_opt_ int64_t* targetEndSnapTime);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Get the snapshot interval that bounds the target event time.\n    /// </summary>\n    /// <param name=\"runtimeHandle\">The runtime handle that the script is executing in.</param>\n    /// <param name=\"targetEventTime\">The event time we want to get the interval for.</param>\n    /// <param name=\"startSnapTime\">The snapshot time that comes before the desired event.</param>\n    /// <param name=\"endSnapTime\">The snapshot time that comes after the desired event (-1 if the leg ends before a snapshot appears).</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API JsTTDGetSnapShotBoundInterval(\n        _In_ JsRuntimeHandle runtimeHandle,\n        _In_ int64_t targetEventTime,\n        _Out_ int64_t* startSnapTime,\n        _Out_ int64_t* endSnapTime);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Get the snapshot interval that precedes the one given by currentSnapStartTime (or -1 if there is no such interval).\n    /// </summary>\n    /// <param name=\"runtimeHandle\">The runtime handle that the script is executing in.</param>\n    /// <param name=\"currentSnapStartTime\">The current snapshot interval start time.</param>\n    /// <param name=\"previousSnapTime\">The resulting previous snapshot interval start time or -1 if no such time.</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API JsTTDGetPreviousSnapshotInterval(\n        _In_ JsRuntimeHandle runtimeHandle,\n        _In_ int64_t currentSnapStartTime,\n        _Out_ int64_t* previousSnapTime);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     During debug operations some additional information is populated during replay. This runs the code between the given\n    ///     snapshots to populate this information which may be needed by the debugger to determine time-travel jump targets.\n    /// </summary>\n    /// <param name=\"runtimeHandle\">The runtime handle that the script is executing in.</param>\n    ///<param name = \"startSnapTime\">The snapshot time that we will start executing from.< / param>\n    ///<param name = \"endSnapTime\">The snapshot time that we will stop at (or -1 if we want to run to the end).< / param>\n    /// <param name=\"moveMode\">Additional flags for controling how the move is done.</param>\n    /// <param name=\"newTargetEventTime\">The updated target event time set according to the moveMode (-1 if not found).</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API JsTTDPreExecuteSnapShotInterval(\n        _In_ JsRuntimeHandle runtimeHandle,\n        _In_ int64_t startSnapTime,\n        _In_ int64_t endSnapTime,\n        _In_ JsTTDMoveMode moveMode,\n        _Out_ int64_t* newTargetEventTime);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Move to the given top-level call event time (assuming JsTTDPrepContextsForTopLevelEventMove) was called previously to reset any script contexts.\n    ///     This also computes the ready-to-run snapshot if needed.\n    /// </summary>\n    /// <param name=\"runtimeHandle\">The runtime handle that the script is executing in.</param>\n    /// <param name=\"moveMode\">Additional flags for controling how the move is done.</param>\n    /// <param name=\"snapshotTime\">The event time that we will start executing from to move to the given target time.</param>\n    /// <param name=\"eventTime\">The event that we want to move to.</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDMoveToTopLevelEvent(\n            _In_ JsRuntimeHandle runtimeHandle,\n            _In_ JsTTDMoveMode moveMode,\n            _In_ int64_t snapshotTime,\n            _In_ int64_t eventTime);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Execute from the current point in the log to the end returning the error code.\n    /// </summary>\n    /// <param name=\"moveMode\">Additional flags for controling how the move is done.</param>\n    /// <param name=\"rootEventTime\">The event time that we should move to next or notification (-1) that replay has ended.</param>\n    /// <returns>\n    ///     If the debugger requested an abort the code is JsNoError -- rootEventTime is the target event time we need to move to and re - execute from.\n    ///     If we aborted at the end of the replay log the code is JsNoError -- rootEventTime is -1.\n    ///     If there was an unhandled script exception the code is JsErrorCategoryScript.\n    /// </returns>\n    CHAKRA_API\n        JsTTDReplayExecution(\n            _Inout_ JsTTDMoveMode* moveMode,\n            _Out_ int64_t* rootEventTime);\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     Enable or disable autotrace ability from JsRT.\n    /// </summary>\n    /// <param name=\"status\">True to enable autotracing false to disable it.</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDDiagSetAutoTraceStatus(\n            _In_ bool status\n        );\n\n    /// <summary>\n    ///     TTD API -- may change in future versions:\n    ///     A way for the debugger to programatically write a trace when it is at a breakpoint.\n    /// </summary>\n    /// <param name=\"uri\">The URI that the log should be written into.</param>\n    /// <param name=\"uriLength\">The length of the uri array that the host passed in for storing log info.</param>\n    /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n    CHAKRA_API\n        JsTTDDiagWriteLog(\n            _In_reads_(uriLength) const char* uri,\n            _In_ size_t uriLength\n        );\n\n#endif // _CHAKRADEBUG_H_\n"
  },
  {
    "path": "packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Microsoft.ChakraCore.vc140\" version=\"1.11.24\" targetFramework=\"native\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "samples/HostSample/ChakraCoreHostMainData.dfm",
    "content": "object DataModuleMain: TDataModuleMain\n  OldCreateOrder = False\n  OnCreate = DataModuleCreate\n  OnDestroy = DataModuleDestroy\n  Height = 265\n  Width = 368\nend\n"
  },
  {
    "path": "samples/HostSample/ChakraCoreHostMainData.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nunit ChakraCoreHostMainData;\n\ninterface\n\n{$include common.inc}\n\nuses\n{$ifdef FPC}{$ifdef UNIX}\n  cwstring,\n{$endif}{$endif}\n{$ifdef WINDOWS}\n  Windows,\n{$endif}\n  SysUtils, Classes,\n{$ifdef HAS_WIDESTRUTILS}\n  WideStrUtils,\n{$endif}\n  Compat, ChakraCommon, ChakraCore, ChakraCoreUtils, ChakraCoreClasses, Console;\n\ntype\n\n  { TDataModuleMain }\n\n  TDataModuleMain = class(TDataModule)\n    procedure DataModuleCreate(Sender: TObject);\n    procedure DataModuleDestroy(Sender: TObject);\n  private\n    FBaseDir: UnicodeString;\n    FConsole: TConsole;\n    FContext: TChakraCoreContext;\n    FRuntime: TChakraCoreRuntime;\n    FUseAnsiColors: Boolean;\n\n    procedure ConsoleLog(Sender: TObject; const Text: UnicodeString; Level: TInfoLevel = ilNone);\n    procedure ContextActivate(Sender: TObject);\n    procedure ContextLoadModule(Sender: TObject; Module: TChakraModule);\n    procedure ContextNativeObjectCreated(Sender: TObject; NativeObject: TNativeObject);\n  public\n    procedure Execute(const ScriptFileNames: array of UnicodeString);\n\n    property BaseDir: UnicodeString read FBaseDir;\n    property Console: TConsole read FConsole;\n    property Context: TChakraCoreContext read FContext;\n    property Runtime: TChakraCoreRuntime read FRuntime;\n    property UseAnsiColors: Boolean read FUseAnsiColors write FUseAnsiColors;\n  end;\n\nimplementation\n\n{$R *.dfm}\n\nfunction LoadFile(const FileName: UnicodeString): UnicodeString;\nvar\n  FileStream: TFileStream;\n  S: UTF8String;\nbegin\n  Result := '';\n\n  FileStream := TFileStream.Create(FileName, fmOpenRead);\n  try\n    if FileStream.Size = 0 then\n      Exit;\n\n    SetLength(S, FileStream.Size);\n    FileStream.Read(S[1], FileStream.Size);\n\n    Result := UTF8ToString(S);\n  finally\n    FileStream.Free;\n  end;\nend;\n\nfunction PostTimedTask(Args: PJsValueRefArray; ArgCount: Word; CallbackState: Pointer; RepeatCount: Integer): JsValueRef;\nvar\n  DataModule: TDataModuleMain absolute CallbackState;\n  AMessage: TTaskMessage;\n  Delay: Cardinal;\n  FuncArgs: array of JsValueRef;\n  I: Integer;\nbegin\n  Result := JsUndefinedValue;\n\n  if ArgCount < 2 then // thisarg, function to call, optional: delay, function args\n    raise Exception.Create('Invalid arguments');\n\n  if ArgCount >= 3 then\n    Delay := JsNumberToInt(Args^[2])\n  else\n    Delay := 0;\n\n  if ArgCount >= 4 then\n  begin\n    SetLength(FuncArgs, ArgCount - 3);\n    for I := 0 to ArgCount - 4 do\n      FuncArgs[I] := Args^[I + 3];\n  end;\n\n  AMessage := TTaskMessage.Create(DataModule.Context, Args^[1], Args^[0], FuncArgs, Delay, RepeatCount);\n  try\n    DataModule.Context.PostMessage(AMessage);\n  except\n    AMessage.Free;\n    raise;\n  end;\nend;\n\nfunction SetInterval_Callback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRefArray; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := PostTimedTask(Args, ArgCount, CallbackState, -1); // repeat endlessly\nend;\n\nfunction SetTimeout_Callback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRefArray; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := PostTimedTask(Args, ArgCount, CallbackState, 1); // run once\nend;\n\ntype\n  THackPromiseMessage = class(TPromiseMessage);\n\n  TDummyPromiseThread = class(TThread)\n  private\n    FMessage: TPromiseMessage;\n    FTimeout: Cardinal;\n    FValue: JsValueRef;\n  protected\n    procedure Execute; override;\n  public\n    constructor Create(AMessage: TPromiseMessage; ATimeout: Cardinal);\n  end;\n\n{ TTestPromiseThread }\n\nprocedure TDummyPromiseThread.Execute;\nbegin\n  Sleep(FTimeout);\n  THackPromiseMessage(FMessage).SetStatus(psResolved, FValue);\nend;\n\nconstructor TDummyPromiseThread.Create(AMessage: TPromiseMessage; ATimeout: Cardinal);\nbegin\n  FMessage := AMessage;\n  FTimeout := ATimeout;\n  FValue := StringToJsString('Success!');\n  JsAddRef(FValue);\n  FreeOnTerminate := True;\n  inherited Create(False);\nend;\n\nfunction TestPromise_Callback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRefArray;\n  ArgCount: Word; CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nvar\n  DataModule: TDataModuleMain absolute CallbackState;\n  AMessage: TPromiseMessage;\n  ResolveTask, RejectTask: JsValueRef;\nbegin\n  if ArgCount <> 2 then // thisarg, timeout\n    raise Exception.Create('Invalid arguments');\n\n  JsCreatePromise(Result, ResolveTask, RejectTask);\n  AMessage := TPromiseMessage.Create(DataModule.Context, Args^[0], ResolveTask, RejectTask);\n  try\n    TDummyPromiseThread.Create(AMessage, JsNumberToInt(Args^[1]));\n    DataModule.Context.PostMessage(AMessage);\n  except\n    AMessage.Free;\n    raise;\n  end;\nend;\n\nprocedure TDataModuleMain.ConsoleLog(Sender: TObject; const Text: UnicodeString; Level: TInfoLevel);\nconst\n  StartBlocks: array[TInfoLevel] of RawByteString = ('', #$1b'[32;1m', #$1b'[33;1m', #$1b'[31;1m');\n  EndBlocks: array[Boolean] of RawByteString = ('', #$1b'[0m');\n{$ifdef WINDOwS}\n  BackgroundMask = $F0;\n  TextColors: array[TInfoLevel] of Word = (0, FOREGROUND_GREEN or FOREGROUND_INTENSITY,\n    FOREGROUND_GREEN or FOREGROUND_RED or FOREGROUND_INTENSITY, FOREGROUND_RED or FOREGROUND_INTENSITY);\n{$endif}\nvar\n{$ifdef WINDOWS}\n  Info: TConsoleScreenBufferInfo;\n{$endif}\n  S: UTF8String;\nbegin\n  S := UTF8Encode(Text);\n{$ifdef WINDOWS}\n  if UseAnsiColors then\n    Writeln(StartBlocks[Level], S, EndBlocks[Level <> ilNone])\n  else\n  begin\n    if (Level = ilNone) or not GetConsoleScreenBufferInfo(TTextRec(Output).Handle, Info) then\n    begin\n      Writeln(S);\n      Exit;\n    end;\n\n    SetConsoleTextAttribute(TTextRec(Output).Handle, Info.wAttributes and BackgroundMask or TextColors[Level]);\n    try\n      Writeln(S);\n    finally\n      SetConsoleTextAttribute(TTextRec(Output).Handle, Info.wAttributes);\n    end;\n  end;\n{$else}\n  Writeln(StartBlocks[Level], S, EndBlocks[Level <> ilNone]);\n{$endif}\nend;\n\nprocedure TDataModuleMain.ContextActivate(Sender: TObject);\nbegin\n  // expose additional functions\n  JsSetCallback(FContext.Global, 'setTimeout', @SetTimeout_Callback, Self, True);\n  JsSetCallback(FContext.Global, 'setInterval', @SetInterval_Callback, Self, True);\n  JsSetCallback(FContext.Global, 'testPromise', @TestPromise_Callback, Self, True);\n\n  // project TConsole class so scripts can create instances, e.g. var c = new Console();\n  TConsole.Project;\n\n  // expose global.console\n  FConsole := TConsole.Create;\n  JsSetProperty(FContext.Global, 'console', FConsole.Instance);\nend;\n\nprocedure TDataModuleMain.ContextLoadModule(Sender: TObject; Module: TChakraModule);\nvar\n  ModuleFileName: UnicodeString;\nbegin\n  ModuleFileName := IncludeTrailingPathDelimiter(FBaseDir) + ChangeFileExt(Module.Name, UnicodeString('.js'));\n  if FileExists(ModuleFileName) then\n  begin\n    Module.Parse(LoadFile(ModuleFileName));\n    Module.URL := WideFormat('file://%s/%s', [ChangeFileExt(ExtractFileName(ParamStr(0)), UnicodeString('')),\n      ChangeFileExt(Module.Name, UnicodeString('.js'))]);\n  end;\nend;\n\nprocedure TDataModuleMain.ContextNativeObjectCreated(Sender: TObject; NativeObject: TNativeObject);\nbegin\n  if NativeObject is TConsole then\n    TConsole(NativeObject).OnLog := ConsoleLog;\nend;\n\nprocedure TDataModuleMain.DataModuleCreate(Sender: TObject);\nbegin\n  try\n    FRuntime := TChakraCoreRuntime.Create([ccroEnableExperimentalFeatures, ccroDispatchSetExceptionsToDebugger]);\n    FContext := TChakraCoreContext.Create(FRuntime);\n    FContext.OnActivate := ContextActivate;\n    FContext.OnLoadModule := ContextLoadModule;\n    FContext.OnNativeObjectCreated := ContextNativeObjectCreated;\n  except\n    FreeAndNil(FConsole);\n    FreeAndNil(FContext);\n    FreeAndNil(FRuntime);\n    raise;\n  end;\nend;\n\nprocedure TDataModuleMain.DataModuleDestroy(Sender: TObject);\nbegin\n  FreeAndNil(FConsole);\n  FreeAndNil(FContext);\n  FreeAndNil(FRuntime);\nend;\n\nprocedure TDataModuleMain.Execute(const ScriptFileNames: array of UnicodeString);\nvar\n  I: Integer;\nbegin\n  for I := Low(ScriptFileNames) to High(ScriptFileNames) do\n  begin\n    FBaseDir := ExtractFilePath(ScriptFileNames[I]);\n    FContext.RunScript(LoadFile(ScriptFilenames[I]), UnicodeString(ExtractFileName(ScriptFileNames[I])));\n  end;\nend;\n\nend.\n"
  },
  {
    "path": "samples/HostSample/ChakraCoreHostSample.XE.dproj",
    "content": "﻿\t<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\t\t<PropertyGroup>\n\t\t\t<ProjectGuid>{2b63895c-8001-41eb-a2d0-6815b28b3222}</ProjectGuid>\n\t\t\t<MainSource>ChakraCoreHostSample.dpr</MainSource>\n\t\t\t<Config Condition=\"'$(Config)'==''\">Debug</Config>\n\t\t\t<DCC_DCCCompiler>DCC32</DCC_DCCCompiler>\n\t\t\t<ProjectVersion>12.3</ProjectVersion>\n\t\t\t<Base>True</Base>\n\t\t\t<Platform>Win32</Platform>\n\t\t\t<AppType>Console</AppType>\n\t\t\t<FrameworkType>None</FrameworkType>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Base' or '$(Base)'!=''\">\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Release' or '$(Cfg_1)'!=''\">\n\t\t\t<Cfg_1>true</Cfg_1>\n\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Debug' or '$(Cfg_2)'!=''\">\n\t\t\t<Cfg_2>true</Cfg_2>\n\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Base)'!=''\">\n\t\t\t<DCC_DependencyCheckOutputName>..\\..\\bin\\$(Platform)\\$(Config)\\ChakraCoreHostSample.exe</DCC_DependencyCheckOutputName>\n\t\t\t<DCC_ExeOutput>..\\..\\bin\\$(Platform)\\$(Config)</DCC_ExeOutput>\n\t\t\t<DCC_DcuOutput>..\\..\\lib\\$(Platform)\\$(Config)</DCC_DcuOutput>\n\t\t\t<DCC_ImageBase>00400000</DCC_ImageBase>\n\t\t\t<DCC_UsePackage>vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP;JclDeveloperTools;Jcl;JclVcl;JclContainers</DCC_UsePackage>\n\t\t\t<DCC_UnitAlias>WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;$(DCC_UnitAlias)</DCC_UnitAlias>\n\t\t\t<DCC_Platform>x86</DCC_Platform>\n\t\t\t<DCC_UnitSearchPath>..\\..\\src;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>\n\t\t\t<DCC_K>false</DCC_K>\n\t\t\t<DCC_N>true</DCC_N>\n\t\t\t<DCC_S>false</DCC_S>\n\t\t\t<DCC_SymbolReferenceInfo>1</DCC_SymbolReferenceInfo>\n\t\t\t<DCC_E>false</DCC_E>\n\t\t\t<DCC_F>false</DCC_F>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Cfg_1)'!=''\">\n\t\t\t<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>\n\t\t\t<DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>\n\t\t\t<DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>\n\t\t\t<DCC_DebugInformation>false</DCC_DebugInformation>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Cfg_2)'!=''\">\n\t\t\t<DCC_Define>DEBUG;$(DCC_Define)</DCC_Define>\n\t\t</PropertyGroup>\n\t\t<ItemGroup>\n\t\t\t<DelphiCompile Include=\"ChakraCoreHostSample.dpr\">\n\t\t\t\t<MainSource>MainSource</MainSource>\n\t\t\t</DelphiCompile>\n\t\t\t<DCCReference Include=\"ChakraCoreHostMainData.pas\">\n\t\t\t\t<Form>DataModuleMain</Form>\n\t\t\t\t<DesignClass>TDataModule</DesignClass>\n\t\t\t</DCCReference>\n\t\t\t<BuildConfiguration Include=\"Debug\">\n\t\t\t\t<Key>Cfg_2</Key>\n\t\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t</BuildConfiguration>\n\t\t\t<BuildConfiguration Include=\"Base\">\n\t\t\t\t<Key>Base</Key>\n\t\t\t</BuildConfiguration>\n\t\t\t<BuildConfiguration Include=\"Release\">\n\t\t\t\t<Key>Cfg_1</Key>\n\t\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t</BuildConfiguration>\n\t\t</ItemGroup>\n\t\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Delphi.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Delphi.Targets\"/>\n\t\t<Import Condition=\"Exists('$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj')\" Project=\"$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj\"/>\n\t\t<ProjectExtensions>\n\t\t\t<Borland.Personality>Delphi.Personality.12</Borland.Personality>\n\t\t\t<Borland.ProjectType>VCLApplication</Borland.ProjectType>\n\t\t\t<BorlandProject>\n\t\t\t\t<Delphi.Personality>\n\t\t\t\t\t<Source>\n\t\t\t\t\t\t<Source Name=\"MainSource\">ChakraCoreHostSample.dpr</Source>\n\t\t\t\t\t</Source>\n\t\t\t\t\t<Parameters>\n\t\t\t\t\t\t<Parameters Name=\"RunParams\">..\\..\\..\\samples\\HostSample\\scripts\\main.js</Parameters>\n\t\t\t\t\t</Parameters>\n\t\t\t\t\t<VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"IncludeVerInfo\">True</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"AutoIncBuild\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"MajorVer\">1</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"MinorVer\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Release\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Build\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Debug\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"PreRelease\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Special\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Private\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"DLL\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Locale\">1033</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"CodePage\">1252</VersionInfo>\n\t\t\t\t\t</VersionInfo>\n\t\t\t\t\t<VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"CompanyName\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"FileDescription\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"FileVersion\">1.0.0.0</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"InternalName\">ChakraCoreHostSample</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"LegalCopyright\">© 2021 Ondrej Kelle</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"LegalTrademarks\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"OriginalFilename\">ChakraCoreHostSample.exe</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"ProductName\">chakracore-delphi</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"ProductVersion\">1.0.0.0</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"Comments\"/>\n\t\t\t\t\t</VersionInfoKeys>\n\t\t\t\t</Delphi.Personality>\n\t\t\t\t<Platforms>\n\t\t\t\t\t<Platform value=\"Win32\">True</Platform>\n\t\t\t\t</Platforms>\n\t\t\t</BorlandProject>\n\t\t\t<ProjectFileVersion>12</ProjectFileVersion>\n\t\t</ProjectExtensions>\n\t</Project>\n"
  },
  {
    "path": "samples/HostSample/ChakraCoreHostSample.dof",
    "content": "[FileVersion]\nVersion=7.0\n[Compiler]\nA=8\nB=0\nC=1\nD=1\nE=0\nF=0\nG=1\nH=1\nI=1\nJ=0\nK=0\nL=1\nM=0\nN=1\nO=0\nP=1\nQ=0\nR=0\nS=0\nT=0\nU=0\nV=1\nW=0\nX=1\nY=1\nZ=1\nShowHints=1\nShowWarnings=1\nUnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;\nNamespacePrefix=\nSymbolDeprecated=1\nSymbolLibrary=1\nSymbolPlatform=1\nUnitLibrary=1\nUnitPlatform=1\nUnitDeprecated=1\nHResultCompat=1\nHidingMember=1\nHiddenVirtual=1\nGarbage=1\nBoundsError=1\nZeroNilCompat=1\nStringConstTruncated=1\nForLoopVarVarPar=1\nTypedConstVarPar=1\nAsgToTypedConst=1\nCaseLabelRange=1\nForVariable=1\nConstructingAbstract=1\nComparisonFalse=1\nComparisonTrue=1\nComparingSignedUnsigned=1\nCombiningSignedUnsigned=1\nUnsupportedConstruct=1\nFileOpen=1\nFileOpenUnitSrc=1\nBadGlobalSymbol=1\nDuplicateConstructorDestructor=1\nInvalidDirective=1\nPackageNoLink=1\nPackageThreadVar=1\nImplicitImport=1\nHPPEMITIgnored=1\nNoRetVal=1\nUseBeforeDef=1\nForLoopVarUndef=1\nUnitNameMismatch=1\nNoCFGFileFound=1\nMessageDirective=1\nImplicitVariants=1\nUnicodeToLocale=1\nLocaleToUnicode=1\nImagebaseMultiple=1\nSuspiciousTypecast=1\nPrivatePropAccessor=1\nUnsafeType=0\nUnsafeCode=0\nUnsafeCast=0\n[Linker]\nMapFile=0\nOutputObjs=0\nConsoleApp=1\nDebugInfo=0\nRemoteSymbols=0\nMinStackSize=16384\nMaxStackSize=1048576\nImageBase=4194304\nExeDescription=\n[Directories]\nOutputDir=..\\..\\bin\\Win32\\Debug\nUnitOutputDir=..\\..\\lib\\Win32\\Debug\nPackageDLLOutputDir=\nPackageDCPOutputDir=\nSearchPath=..\\..\\src\nPackages=vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP;JclDeveloperTools;Jcl;JclVcl;JclContainers\nConditionals=\nDebugSourceDirs=\nUsePackages=0\n[Parameters]\nRunParams=..\\..\\..\\samples\\HostSample\\scripts\\main.js\nHostApplication=\nLauncher=\nUseLauncher=0\nDebugCWD=\n[Language]\nActiveLang=\nProjectLang=\nRootDir=\n[Version Info]\nIncludeVerInfo=1\nAutoIncBuild=0\nMajorVer=1\nMinorVer=0\nRelease=0\nBuild=0\nDebug=0\nPreRelease=0\nSpecial=0\nPrivate=0\nDLL=0\nLocale=1033\nCodePage=1252\n[Version Info Keys]\nCompanyName=\nFileDescription=\nFileVersion=1.0.0.0\nInternalName=ChakraCoreHostSample\nLegalCopyright=© 2021 Ondrej Kelle\nLegalTrademarks=\nOriginalFilename=ChakraCoreHostSample.exe\nProductName=chakracore-delphi\nProductVersion=1.0.0.0\nComments=\n[HistoryLists\\hlUnitAliases]\nCount=1\nItem0=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;\n[HistoryLists\\hlSearchPath]\nCount=1\nItem0=..\\..\\src\n[HistoryLists\\hlUnitOutputDirectory]\nCount=1\nItem0=..\\..\\lib\\Win32\\Debug\n[HistoryLists\\hlOutputDirectorry]\nCount=1\nItem0=..\\..\\bin\\Win32\\Debug\n"
  },
  {
    "path": "samples/HostSample/ChakraCoreHostSample.dpr",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nprogram ChakraCoreHostSample;\n\n{$APPTYPE CONSOLE}\n\n{$include common.inc}\n\nuses\n  {$ifdef FPC}{$ifdef UNIX}\n  cthreads,\n  {$endif}{$endif}\n  SysUtils,\n  Compat,\n  ChakraCoreVersion, ChakraCoreUtils,\n  ChakraCoreHostMainData in 'ChakraCoreHostMainData.pas' {DataModuleMain: TDataModule};\n\n{$R *.res}\n\nprocedure ShowInfo;\nbegin\n  Writeln(Format('%s %s', [ExtractFileName(ParamStr(0)), GetExeFileVersionString]));\n  Writeln(Format('Built with %s', [GetBuildInfoString]));\n  Writeln(Format('Chakra Core version: %d.%d.%d', [CHAKRA_CORE_MAJOR_VERSION, CHAKRA_CORE_MINOR_VERSION, CHAKRA_CORE_PATCH_VERSION]));\n  Writeln;\nend;\n\ntype\n  UnicodeStringDynArray = array of UnicodeString;\n\nfunction ParamStrings: UnicodeStringDynArray;\nvar\n  I: Integer;\nbegin\n  Result := nil;\n  SetLength(Result, ParamCount);\n  for I := 1 to ParamCount do\n    Result[I - 1] := UnicodeString(ParamStr(I));\nend;\n\nprocedure Main;\nvar\n  DataModule: TDataModuleMain;\nbegin\n  ShowInfo;\n\n  DataModule := TDataModuleMain.Create(nil);\n  try\n    DataModule.Execute(ParamStrings);\n  finally\n    DataModule.Free;\n  end;\nend;\n\nbegin\n{$ifdef DELPHI2006_UP}\n  ReportMemoryLeaksOnShutdown := True;\n{$endif}\n  try\n    Main;\n  except\n    on E: EChakraCoreScript do\n    begin\n      ExitCode := 1;\n      Writeln(Format('%s (%d, %d): [%s] %s', [E.ScriptURL, E.Line + 1, E.Column + 1, E.ClassName, E.Message]));\n    end;\n    on E: Exception do\n    begin\n      ExitCode := 1;\n      Writeln(Format('[%s] %s', [E.ClassName, E.Message]));\n    end;\n  end;\nend.\n"
  },
  {
    "path": "samples/HostSample/ChakraCoreHostSample.lpi",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CONFIG>\n  <ProjectOptions>\n    <Version Value=\"10\"/>\n    <General>\n      <Flags>\n        <MainUnitHasCreateFormStatements Value=\"False\"/>\n        <MainUnitHasScaledStatement Value=\"False\"/>\n      </Flags>\n      <SessionStorage Value=\"InProjectDir\"/>\n      <MainUnit Value=\"0\"/>\n      <UseAppBundle Value=\"False\"/>\n      <ResourceType Value=\"res\"/>\n    </General>\n    <VersionInfo>\n      <UseVersionInfo Value=\"True\"/>\n      <MajorVersionNr Value=\"1\"/>\n      <StringTable InternalName=\"ChakraCoreHostSample\" LegalCopyright=\"© 2021 Ondrej Kelle\" OriginalFilename=\"ChakraCoreHostSample\"/>\n    </VersionInfo>\n    <BuildModes Count=\"2\">\n      <Item1 Name=\"Debug\" Default=\"True\"/>\n      <Item2 Name=\"Release\">\n        <CompilerOptions>\n          <Version Value=\"11\"/>\n          <Target>\n            <Filename Value=\"ChakraCoreHostSample\"/>\n          </Target>\n          <SearchPaths>\n            <UnitOutputDirectory Value=\"lib/$(TargetCPU)-$(TargetOS)\"/>\n          </SearchPaths>\n          <CodeGeneration>\n            <SmartLinkUnit Value=\"True\"/>\n            <Optimizations>\n              <OptimizationLevel Value=\"3\"/>\n            </Optimizations>\n          </CodeGeneration>\n          <Linking>\n            <Debugging>\n              <GenerateDebugInfo Value=\"False\"/>\n            </Debugging>\n            <LinkSmart Value=\"True\"/>\n          </Linking>\n        </CompilerOptions>\n      </Item2>\n    </BuildModes>\n    <PublishOptions>\n      <Version Value=\"2\"/>\n    </PublishOptions>\n    <RunParams>\n      <local>\n        <FormatVersion Value=\"1\"/>\n        <CommandLineParams Value=\"../../../samples/HostSample/scripts/main.js\"/>\n      </local>\n    </RunParams>\n    <Units Count=\"2\">\n      <Unit0>\n        <Filename Value=\"ChakraCoreHostSample.dpr\"/>\n        <IsPartOfProject Value=\"True\"/>\n      </Unit0>\n      <Unit1>\n        <Filename Value=\"ChakraCoreHostMainData.pas\"/>\n        <IsPartOfProject Value=\"True\"/>\n        <ComponentName Value=\"DataModuleMain\"/>\n        <HasResources Value=\"True\"/>\n        <ResourceBaseClass Value=\"DataModule\"/>\n      </Unit1>\n    </Units>\n  </ProjectOptions>\n  <CompilerOptions>\n    <Version Value=\"11\"/>\n    <Target>\n      <Filename Value=\"../../bin/$(TargetCPU)-$(TargetOS)/$(BuildMode)/ChakraCoreHostSample\"/>\n    </Target>\n    <SearchPaths>\n      <IncludeFiles Value=\"$(ProjOutDir);../../src\"/>\n      <OtherUnitFiles Value=\"../../src\"/>\n      <UnitOutputDirectory Value=\"../../lib/$(TargetCPU)-$(TargetOS)/$(BuildMode)\"/>\n    </SearchPaths>\n    <Parsing>\n      <SyntaxOptions>\n        <IncludeAssertionCode Value=\"True\"/>\n      </SyntaxOptions>\n    </Parsing>\n    <CodeGeneration>\n      <Checks>\n        <IOChecks Value=\"True\"/>\n        <RangeChecks Value=\"True\"/>\n        <OverflowChecks Value=\"True\"/>\n        <StackChecks Value=\"True\"/>\n      </Checks>\n    </CodeGeneration>\n    <Linking>\n      <Debugging>\n        <DebugInfoType Value=\"dsDwarf2Set\"/>\n        <UseHeaptrc Value=\"True\"/>\n        <TrashVariables Value=\"True\"/>\n        <UseExternalDbgSyms Value=\"True\"/>\n      </Debugging>\n    </Linking>\n  </CompilerOptions>\n  <Debugging>\n    <Exceptions Count=\"4\">\n      <Item1>\n        <Name Value=\"EAbort\"/>\n      </Item1>\n      <Item2>\n        <Name Value=\"ECodetoolError\"/>\n      </Item2>\n      <Item3>\n        <Name Value=\"EFOpenError\"/>\n      </Item3>\n      <Item4>\n        <Name Value=\"EChakraCore\"/>\n      </Item4>\n    </Exceptions>\n  </Debugging>\n</CONFIG>\n"
  },
  {
    "path": "samples/HostSample/Console.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nunit Console;\n\ninterface\n\n{$include common.inc}\n\nuses\n  SysUtils, Classes,\n{$ifdef HAS_WIDESTRUTILS}\n  WideStrUtils,\n{$endif}\n  Compat, ChakraCommon, ChakraCoreUtils, ChakraCoreClasses;\n\ntype\n  TInfoLevel = (ilNone, ilInfo, ilWarn, ilError);\n\n  TConsoleLogEvent = procedure (Sender: TObject; const Text: UnicodeString; Level: TInfoLevel = ilNone) of object;\n\n  { TConsole }\n\n  TConsole = class(TNativeObject)\n  private\n    FOnLog: TConsoleLogEvent;\n    \n    function Assert(Args: PJsValueRef; ArgCount: Word): JsValueRef;\n    function LogError(Args: PJsValueRef; ArgCount: Word): JsValueRef;\n    function LogInfo(Args: PJsValueRef; ArgCount: Word): JsValueRef;\n    function LogNone(Args: PJsValueRef; ArgCount: Word): JsValueRef;\n    function LogWarn(Args: PJsValueRef; ArgCount: Word): JsValueRef;\n  protected\n    procedure DoLog(const Text: UnicodeString; Level: TInfoLevel = ilNone); virtual;\n    class procedure RegisterMethods(AInstance: JsValueRef); override;\n  public\n    function Log(Args: PJsValueRef; ArgCount: Word; Level: TInfoLevel = ilNone): JsValueRef; overload;\n    function Log(const Args: array of JsValueRef; Level: TInfoLevel = ilNone): JsValueRef; overload;\n\n    property OnLog: TConsoleLogEvent read FOnLog write FOnLog;\n  end;\n\nimplementation\n\nfunction FmtSpecPos(S: PWideChar): PWideChar;\nvar\n  P: PWideChar;\nbegin\n  Result := nil;\n\n  P := WStrPos(S, '%');\n  while Assigned(P) do\n  begin\n    case (P + 1)^ of\n      #0:\n        Break;\n      'd', 'i', 'f', 'o', 's':\n        begin\n          Result := P;\n          Break;\n        end;\n      '%':\n        begin\n          Inc(P);\n          if P^ = #0 then\n            Break;\n        end;\n    end;\n\n    P := WStrPos(P + 1, '%');\n  end;\nend;\n\n{ TConsole private }\n\nfunction TConsole.Assert(Args: PJsValueRef; ArgCount: Word): JsValueRef;\nvar\n  ArgCondition: JsValueRef;\n  SMessage: UnicodeString;\nbegin\n  Result := JsUndefinedValue;\n  if ArgCount < 1 then\n    Exit;\n\n  SMessage := 'Assertion failed';\n\n  // arg 1 = condition (boolean)\n  ArgCondition := Args^;\n  if (JsGetValueType(ArgCondition) <> JsBoolean) then\n    raise Exception.Create('condition passed to console.assert not a boolean');\n\n  Inc(Args);\n  Dec(ArgCount);\n\n  if (JsBooleanToBoolean(ArgCondition)) then // assertion passed\n    Exit;\n\n  if ArgCount = 0 then // no message/data\n    DoLog(SMessage, ilError)\n  else\n    Log(Args, ArgCount, ilError);\nend;\n\nfunction TConsole.LogError(Args: PJsValueRef; ArgCount: Word): JsValueRef;\nbegin\n  Result := Log(Args, ArgCount, ilError);\nend;\n\nfunction TConsole.LogInfo(Args: PJsValueRef; ArgCount: Word): JsValueRef;\nbegin\n  Result := Log(Args, ArgCount, ilInfo);\nend;\n\nfunction TConsole.LogNone(Args: PJsValueRef; ArgCount: Word): JsValueRef;\nbegin\n  Result := Log(Args, ArgCount, ilNone);\nend;\n\nfunction TConsole.LogWarn(Args: PJsValueRef; ArgCount: Word): JsValueRef;\nbegin\n  Result := Log(Args, ArgCount, ilWarn);\nend;\n\n{ TConsole protected }\n\nprocedure TConsole.DoLog(const Text: UnicodeString; Level: TInfoLevel);\nbegin\n  if Assigned(FOnLog) then\n    FOnLog(Self, Text, Level);\nend;\n\n{ TConsole public }\n\nfunction TConsole.Log(Args: PJsValueRef; ArgCount: Word; Level: TInfoLevel): JsValueRef;\nvar\n  FirstArg, S, SCopy: UnicodeString;\n  P, PPrev: PWideChar;\n  Arg: PJsValueRef;\n  I, ArgIndex: Integer;\nbegin\n  Result := JsUndefinedValue;\n  if not Assigned(Args) then\n    Exit;\n\n  S := '';\n  P := nil;\n  PPrev := nil;\n  Arg := Args;\n  ArgIndex := 0;\n  if Assigned(Args) and (ArgCount > 0) and (JsGetValueType(Args^) = JsString) then\n  begin\n    FirstArg := JsStringToUnicodeString(Args^);\n    PPrev := PWideChar(FirstArg);\n    P := FmtSpecPos(PPrev);\n  end;\n\n  if Assigned(P) then\n  begin\n    Inc(Arg);\n    Inc(ArgIndex);\n    while Assigned(P) do\n    begin\n      if ArgIndex > ArgCount - 1 then\n      begin\n        SetString(SCopy, PPrev, (P - PPrev) + 2);\n        S := S + WideStringReplace(SCopy, '%%', '%', [rfReplaceAll]);\n      end\n      else\n      begin\n        SetString(SCopy, PPrev, P - PPrev);\n        S := S + WideStringReplace(SCopy, '%%', '%', [rfReplaceAll]);\n        case (P + 1)^ of\n          'd', 'i':\n            S := S + UnicodeString(IntToStr(JsNumberToInt(Arg^)));\n          'f':\n            S := S + UnicodeString(FloatToStr(JsNumberToDouble(Arg^), DefaultFormatSettings));\n          'o':\n            S := S + JsInspect(Arg^);\n          's':\n            S := S + JsStringToUnicodeString(JsValueAsJsString(Arg^));\n        end;\n      end;\n\n      PPrev := P + 2;\n      P := FmtSpecPos(PPrev);\n      Inc(Arg);\n      Inc(ArgIndex);\n    end;\n    S := S + WideStringReplace(PPrev, '%%', '%', [rfReplaceAll]);\n  end\n  else\n  begin\n    for I := 0 to ArgCount - 1 do\n    begin\n      if S <> '' then\n        S := S + ' ';\n      S := S + JsStringToUnicodeString(JsValueAsJsString(Arg^));\n      Inc(Arg);\n    end;\n  end;\n  DoLog(S, Level);\nend;\n\nfunction TConsole.Log(const Args: array of JsValueRef; Level: TInfoLevel): JsValueRef;\nvar\n  P: PJsValueRef;\n  L: Integer;\nbegin\n  P := nil;\n  L := Length(Args);\n  if L > 0 then\n    P := @Args[0];\n  Result := Log(P, L, Level);\nend;\n\nclass procedure TConsole.RegisterMethods(AInstance: JsValueRef);\nbegin\n  RegisterMethod(AInstance, 'assert', @TConsole.Assert);\n  RegisterMethod(AInstance, 'log', @TConsole.LogNone);\n  RegisterMethod(AInstance, 'info', @TConsole.LogInfo);\n  RegisterMethod(AInstance, 'warn', @TConsole.LogWarn);\n  RegisterMethod(AInstance, 'error', @TConsole.LogError);\n  RegisterMethod(AInstance, 'exception', @TConsole.LogError);\nend;\n\nend.\n"
  },
  {
    "path": "samples/HostSample/scripts/json2.js",
    "content": "//  json2.js\n//  2016-10-28\n//  Public Domain.\n//  NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n//  See http://www.JSON.org/js.html\n//  This code should be minified before deployment.\n//  See http://javascript.crockford.com/jsmin.html\n\n//  USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO\n//  NOT CONTROL.\n\n//  This file creates a global JSON object containing two methods: stringify\n//  and parse. This file provides the ES5 JSON capability to ES3 systems.\n//  If a project might run on IE8 or earlier, then this file should be included.\n//  This file does nothing on ES5 systems.\n\n//      JSON.stringify(value, replacer, space)\n//          value       any JavaScript value, usually an object or array.\n//          replacer    an optional parameter that determines how object\n//                      values are stringified for objects. It can be a\n//                      function or an array of strings.\n//          space       an optional parameter that specifies the indentation\n//                      of nested structures. If it is omitted, the text will\n//                      be packed without extra whitespace. If it is a number,\n//                      it will specify the number of spaces to indent at each\n//                      level. If it is a string (such as \"\\t\" or \"&nbsp;\"),\n//                      it contains the characters used to indent at each level.\n//          This method produces a JSON text from a JavaScript value.\n//          When an object value is found, if the object contains a toJSON\n//          method, its toJSON method will be called and the result will be\n//          stringified. A toJSON method does not serialize: it returns the\n//          value represented by the name/value pair that should be serialized,\n//          or undefined if nothing should be serialized. The toJSON method\n//          will be passed the key associated with the value, and this will be\n//          bound to the value.\n\n//          For example, this would serialize Dates as ISO strings.\n\n//              Date.prototype.toJSON = function (key) {\n//                  function f(n) {\n//                      // Format integers to have at least two digits.\n//                      return (n < 10)\n//                          ? \"0\" + n\n//                          : n;\n//                  }\n//                  return this.getUTCFullYear()   + \"-\" +\n//                       f(this.getUTCMonth() + 1) + \"-\" +\n//                       f(this.getUTCDate())      + \"T\" +\n//                       f(this.getUTCHours())     + \":\" +\n//                       f(this.getUTCMinutes())   + \":\" +\n//                       f(this.getUTCSeconds())   + \"Z\";\n//              };\n\n//          You can provide an optional replacer method. It will be passed the\n//          key and value of each member, with this bound to the containing\n//          object. The value that is returned from your method will be\n//          serialized. If your method returns undefined, then the member will\n//          be excluded from the serialization.\n\n//          If the replacer parameter is an array of strings, then it will be\n//          used to select the members to be serialized. It filters the results\n//          such that only members with keys listed in the replacer array are\n//          stringified.\n\n//          Values that do not have JSON representations, such as undefined or\n//          functions, will not be serialized. Such values in objects will be\n//          dropped; in arrays they will be replaced with null. You can use\n//          a replacer function to replace those with JSON values.\n\n//          JSON.stringify(undefined) returns undefined.\n\n//          The optional space parameter produces a stringification of the\n//          value that is filled with line breaks and indentation to make it\n//          easier to read.\n\n//          If the space parameter is a non-empty string, then that string will\n//          be used for indentation. If the space parameter is a number, then\n//          the indentation will be that many spaces.\n\n//          Example:\n\n//          text = JSON.stringify([\"e\", {pluribus: \"unum\"}]);\n//          // text is '[\"e\",{\"pluribus\":\"unum\"}]'\n\n//          text = JSON.stringify([\"e\", {pluribus: \"unum\"}], null, \"\\t\");\n//          // text is '[\\n\\t\"e\",\\n\\t{\\n\\t\\t\"pluribus\": \"unum\"\\n\\t}\\n]'\n\n//          text = JSON.stringify([new Date()], function (key, value) {\n//              return this[key] instanceof Date\n//                  ? \"Date(\" + this[key] + \")\"\n//                  : value;\n//          });\n//          // text is '[\"Date(---current time---)\"]'\n\n//      JSON.parse(text, reviver)\n//          This method parses a JSON text to produce an object or array.\n//          It can throw a SyntaxError exception.\n\n//          The optional reviver parameter is a function that can filter and\n//          transform the results. It receives each of the keys and values,\n//          and its return value is used instead of the original value.\n//          If it returns what it received, then the structure is not modified.\n//          If it returns undefined then the member is deleted.\n\n//          Example:\n\n//          // Parse the text. Values that look like ISO date strings will\n//          // be converted to Date objects.\n\n//          myData = JSON.parse(text, function (key, value) {\n//              var a;\n//              if (typeof value === \"string\") {\n//                  a =\n//   /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n//                  if (a) {\n//                      return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],\n//                          +a[5], +a[6]));\n//                  }\n//              }\n//              return value;\n//          });\n\n//          myData = JSON.parse('[\"Date(09/09/2001)\"]', function (key, value) {\n//              var d;\n//              if (typeof value === \"string\" &&\n//                      value.slice(0, 5) === \"Date(\" &&\n//                      value.slice(-1) === \")\") {\n//                  d = new Date(value.slice(5, -1));\n//                  if (d) {\n//                      return d;\n//                  }\n//              }\n//              return value;\n//          });\n\n//  This is a reference implementation. You are free to copy, modify, or\n//  redistribute.\n\n/*jslint\n    eval, for, this\n*/\n\n/*property\n    JSON, apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,\n    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,\n    lastIndex, length, parse, prototype, push, replace, slice, stringify,\n    test, toJSON, toString, valueOf\n*/\n\n\n// Create a JSON object only if one does not already exist. We create the\n// methods in a closure to avoid creating global variables.\n\nif (typeof JSON !== \"object\") {\n    JSON = {};\n}\n\n(function () {\n    \"use strict\";\n\n    var rx_one = /^[\\],:{}\\s]*$/;\n    var rx_two = /\\\\(?:[\"\\\\\\/bfnrt]|u[0-9a-fA-F]{4})/g;\n    var rx_three = /\"[^\"\\\\\\n\\r]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?/g;\n    var rx_four = /(?:^|:|,)(?:\\s*\\[)+/g;\n    var rx_escapable = /[\\\\\"\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g;\n    var rx_dangerous = /[\\u0000\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g;\n\n    function f(n) {\n        // Format integers to have at least two digits.\n        return n < 10\n            ? \"0\" + n\n            : n;\n    }\n\n    function this_value() {\n        return this.valueOf();\n    }\n\n    if (typeof Date.prototype.toJSON !== \"function\") {\n\n        Date.prototype.toJSON = function () {\n\n            return isFinite(this.valueOf())\n                ? this.getUTCFullYear() + \"-\" +\n                        f(this.getUTCMonth() + 1) + \"-\" +\n                        f(this.getUTCDate()) + \"T\" +\n                        f(this.getUTCHours()) + \":\" +\n                        f(this.getUTCMinutes()) + \":\" +\n                        f(this.getUTCSeconds()) + \"Z\"\n                : null;\n        };\n\n        Boolean.prototype.toJSON = this_value;\n        Number.prototype.toJSON = this_value;\n        String.prototype.toJSON = this_value;\n    }\n\n    var gap;\n    var indent;\n    var meta;\n    var rep;\n\n\n    function quote(string) {\n\n// If the string contains no control characters, no quote characters, and no\n// backslash characters, then we can safely slap some quotes around it.\n// Otherwise we must also replace the offending characters with safe escape\n// sequences.\n\n        rx_escapable.lastIndex = 0;\n        return rx_escapable.test(string)\n            ? \"\\\"\" + string.replace(rx_escapable, function (a) {\n                var c = meta[a];\n                return typeof c === \"string\"\n                    ? c\n                    : \"\\\\u\" + (\"0000\" + a.charCodeAt(0).toString(16)).slice(-4);\n            }) + \"\\\"\"\n            : \"\\\"\" + string + \"\\\"\";\n    }\n\n\n    function str(key, holder) {\n\n// Produce a string from holder[key].\n\n        var i;          // The loop counter.\n        var k;          // The member key.\n        var v;          // The member value.\n        var length;\n        var mind = gap;\n        var partial;\n        var value = holder[key];\n\n// If the value has a toJSON method, call it to obtain a replacement value.\n\n        if (value && typeof value === \"object\" &&\n                typeof value.toJSON === \"function\") {\n            value = value.toJSON(key);\n        }\n\n// If we were called with a replacer function, then call the replacer to\n// obtain a replacement value.\n\n        if (typeof rep === \"function\") {\n            value = rep.call(holder, key, value);\n        }\n\n// What happens next depends on the value's type.\n\n        switch (typeof value) {\n        case \"string\":\n            return quote(value);\n\n        case \"number\":\n\n// JSON numbers must be finite. Encode non-finite numbers as null.\n\n            return isFinite(value)\n                ? String(value)\n                : \"null\";\n\n        case \"boolean\":\n        case \"null\":\n\n// If the value is a boolean or null, convert it to a string. Note:\n// typeof null does not produce \"null\". The case is included here in\n// the remote chance that this gets fixed someday.\n\n            return String(value);\n\n// If the type is \"object\", we might be dealing with an object or an array or\n// null.\n\n        case \"object\":\n\n// Due to a specification blunder in ECMAScript, typeof null is \"object\",\n// so watch out for that case.\n\n            if (!value) {\n                return \"null\";\n            }\n\n// Make an array to hold the partial results of stringifying this object value.\n\n            gap += indent;\n            partial = [];\n\n// Is the value an array?\n\n            if (Object.prototype.toString.apply(value) === \"[object Array]\") {\n\n// The value is an array. Stringify every element. Use null as a placeholder\n// for non-JSON values.\n\n                length = value.length;\n                for (i = 0; i < length; i += 1) {\n                    partial[i] = str(i, value) || \"null\";\n                }\n\n// Join all of the elements together, separated with commas, and wrap them in\n// brackets.\n\n                v = partial.length === 0\n                    ? \"[]\"\n                    : gap\n                        ? \"[\\n\" + gap + partial.join(\",\\n\" + gap) + \"\\n\" + mind + \"]\"\n                        : \"[\" + partial.join(\",\") + \"]\";\n                gap = mind;\n                return v;\n            }\n\n// If the replacer is an array, use it to select the members to be stringified.\n\n            if (rep && typeof rep === \"object\") {\n                length = rep.length;\n                for (i = 0; i < length; i += 1) {\n                    if (typeof rep[i] === \"string\") {\n                        k = rep[i];\n                        v = str(k, value);\n                        if (v) {\n                            partial.push(quote(k) + (\n                                gap\n                                    ? \": \"\n                                    : \":\"\n                            ) + v);\n                        }\n                    }\n                }\n            } else {\n\n// Otherwise, iterate through all of the keys in the object.\n\n                for (k in value) {\n                    if (Object.prototype.hasOwnProperty.call(value, k)) {\n                        v = str(k, value);\n                        if (v) {\n                            partial.push(quote(k) + (\n                                gap\n                                    ? \": \"\n                                    : \":\"\n                            ) + v);\n                        }\n                    }\n                }\n            }\n\n// Join all of the member texts together, separated with commas,\n// and wrap them in braces.\n\n            v = partial.length === 0\n                ? \"{}\"\n                : gap\n                    ? \"{\\n\" + gap + partial.join(\",\\n\" + gap) + \"\\n\" + mind + \"}\"\n                    : \"{\" + partial.join(\",\") + \"}\";\n            gap = mind;\n            return v;\n        }\n    }\n\n// If the JSON object does not yet have a stringify method, give it one.\n\n    if (typeof JSON.stringify !== \"function\") {\n        meta = {    // table of character substitutions\n            \"\\b\": \"\\\\b\",\n            \"\\t\": \"\\\\t\",\n            \"\\n\": \"\\\\n\",\n            \"\\f\": \"\\\\f\",\n            \"\\r\": \"\\\\r\",\n            \"\\\"\": \"\\\\\\\"\",\n            \"\\\\\": \"\\\\\\\\\"\n        };\n        JSON.stringify = function (value, replacer, space) {\n\n// The stringify method takes a value and an optional replacer, and an optional\n// space parameter, and returns a JSON text. The replacer can be a function\n// that can replace values, or an array of strings that will select the keys.\n// A default replacer method can be provided. Use of the space parameter can\n// produce text that is more easily readable.\n\n            var i;\n            gap = \"\";\n            indent = \"\";\n\n// If the space parameter is a number, make an indent string containing that\n// many spaces.\n\n            if (typeof space === \"number\") {\n                for (i = 0; i < space; i += 1) {\n                    indent += \" \";\n                }\n\n// If the space parameter is a string, it will be used as the indent string.\n\n            } else if (typeof space === \"string\") {\n                indent = space;\n            }\n\n// If there is a replacer, it must be a function or an array.\n// Otherwise, throw an error.\n\n            rep = replacer;\n            if (replacer && typeof replacer !== \"function\" &&\n                    (typeof replacer !== \"object\" ||\n                    typeof replacer.length !== \"number\")) {\n                throw new Error(\"JSON.stringify\");\n            }\n\n// Make a fake root object containing our value under the key of \"\".\n// Return the result of stringifying the value.\n\n            return str(\"\", {\"\": value});\n        };\n    }\n\n\n// If the JSON object does not yet have a parse method, give it one.\n\n    if (typeof JSON.parse !== \"function\") {\n        JSON.parse = function (text, reviver) {\n\n// The parse method takes a text and an optional reviver function, and returns\n// a JavaScript value if the text is a valid JSON text.\n\n            var j;\n\n            function walk(holder, key) {\n\n// The walk method is used to recursively walk the resulting structure so\n// that modifications can be made.\n\n                var k;\n                var v;\n                var value = holder[key];\n                if (value && typeof value === \"object\") {\n                    for (k in value) {\n                        if (Object.prototype.hasOwnProperty.call(value, k)) {\n                            v = walk(value, k);\n                            if (v !== undefined) {\n                                value[k] = v;\n                            } else {\n                                delete value[k];\n                            }\n                        }\n                    }\n                }\n                return reviver.call(holder, key, value);\n            }\n\n\n// Parsing happens in four stages. In the first stage, we replace certain\n// Unicode characters with escape sequences. JavaScript handles many characters\n// incorrectly, either silently deleting them, or treating them as line endings.\n\n            text = String(text);\n            rx_dangerous.lastIndex = 0;\n            if (rx_dangerous.test(text)) {\n                text = text.replace(rx_dangerous, function (a) {\n                    return \"\\\\u\" +\n                            (\"0000\" + a.charCodeAt(0).toString(16)).slice(-4);\n                });\n            }\n\n// In the second stage, we run the text against regular expressions that look\n// for non-JSON patterns. We are especially concerned with \"()\" and \"new\"\n// because they can cause invocation, and \"=\" because it can cause mutation.\n// But just to be safe, we want to reject all unexpected forms.\n\n// We split the second stage into 4 regexp operations in order to work around\n// crippling inefficiencies in IE's and Safari's regexp engines. First we\n// replace the JSON backslash pairs with \"@\" (a non-JSON character). Second, we\n// replace all simple value tokens with \"]\" characters. Third, we delete all\n// open brackets that follow a colon or comma or that begin the text. Finally,\n// we look to see that the remaining characters are only whitespace or \"]\" or\n// \",\" or \":\" or \"{\" or \"}\". If that is so, then the text is safe for eval.\n\n            if (\n                rx_one.test(\n                    text\n                        .replace(rx_two, \"@\")\n                        .replace(rx_three, \"]\")\n                        .replace(rx_four, \"\")\n                )\n            ) {\n\n// In the third stage we use the eval function to compile the text into a\n// JavaScript structure. The \"{\" operator is subject to a syntactic ambiguity\n// in JavaScript: it can begin a block or an object literal. We wrap the text\n// in parens to eliminate the ambiguity.\n\n                j = eval(\"(\" + text + \")\");\n\n// In the optional fourth stage, we recursively walk the new structure, passing\n// each name/value pair to a reviver function for possible transformation.\n\n                return (typeof reviver === \"function\")\n                    ? walk({\"\": j}, \"\")\n                    : j;\n            }\n\n// If the text is not JSON parseable, then a SyntaxError is thrown.\n\n            throw new SyntaxError(\"JSON.parse\");\n        };\n    }\n}());\n"
  },
  {
    "path": "samples/HostSample/scripts/main.js",
    "content": "var p = new Promise((resolve, reject) => {\n\tsetTimeout(c => {\n\t\tresolve(\"Success!\");\n\t}, 100, console);\n});\np.then(\n  r => { console.info(\"Promise: %o\", r); }\n).catch(\n\te => { console.error(\"Promise: %o\", e); }\n);\n\ntestPromise(200).then(\n  x => {\n\tconsole.info(\"testPromise: %o\", x);\n}).catch(\n  e => {\n\t  console.error(\"testPromise: %o\", e);\n  }\n);\n\nimport('json2').then(\n\tm => {\n\t\tsetTimeout(c => { c.log(\"(timeout 1000) Current time: \", new Date()) }, 1000, console);\n\t\tsetTimeout(c => { c.log(\"(timeout 2000) Current time: \", new Date()) }, 2000, console);\n\t\tsetTimeout(c => {\n\t\t\tc.log(\"(timeout 3000) Current time: \", new Date());\n\t\t\tsetInterval(c => { c.log(\"(interval 500) Current time: \", new Date()) }, 500, console);\n\t\t}, 3000, console);\n\n\t\tvar f = function (console) {\n\t\t\tconsole.log(\"Current time: \", new Date());\n\t\t\tconsole.info(\"%s: %s\", \"Info\", \"Info message\");\n\t\t\tconsole.warn(\"%s: %s\", \"Warning\", \"Warning message\");\n\t\t\tconsole.error(\"%s: %s %d\", \"Error\", \"Error message\", 42);\n\n\t\t\tvar o = {int_prop: 42, str_prop: \"Hello\", float_prop: 3.14, array_prop: [42, \"Hello\", 3.14]};\n\t\t\tconsole.log(JSON.stringify(o));\n\t\t\tconsole.log(\"%o\", o);\n\t\t};\n\n\t\tf(console);\n\t\tconsole.log(\"\");\n\n\t\tvar console2 = new Console();\n\t\tf(console2);\n\t}\n).catch(\n\te => {\n\t\tconsole.error(\"%o\", e);\n\t}\n);\n"
  },
  {
    "path": "samples/NodeSample/EventEmitter.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nunit EventEmitter;\n\n{$include common.inc}\n\ninterface\n\nuses\n  Classes, SysUtils, Types,\n  Compat, ChakraCore, ChakraCommon, ChakraCoreUtils, ChakraCoreClasses;\n\nconst\n  DefaultMaxListeners = 10;\n\ntype\n\n  TEventEmitter = class;\n\n  { TEvent }\n\n  TEvent = class\n  private\n    FName: JsValueRef;\n    FListeners: TList;\n    FOnceList: TList;\n    FOwner: TEventEmitter;\n\n    function GetListenerCount: Integer;\n    function GetListeners(Index: Integer): JsValueRef;\n  public\n    constructor Create(AOwner: TEventEmitter; AName: JsValueRef);\n    destructor Destroy; override;\n\n    function AddListener(AListener: JsValueRef; AOnce: Boolean = False): Integer;\n    procedure Emit(Args: PJsValueRef; ArgCount: Word); overload;\n    procedure Emit(const Args: array of JsValueRef); overload;\n    procedure PrependListener(AListener: JsValueRef; AOnce: Boolean = False);\n    function RemoveListener(AListener: JsValueRef): Integer;\n    procedure RemoveListeners;\n\n    property Name: JsValueRef read FName;\n    property ListenerCount: Integer read GetListenerCount;\n    property Listeners[Index: Integer]: JsValueRef read GetListeners;\n    property Owner: TEventEmitter read FOwner;\n  end;\n\n  { TEventEmitter }\n\n  TEventEmitter = class(TNativeObject)\n  private\n    FEvents: TList;\n    FMaxListeners: Integer;\n\n    function GetEventCount: Integer;\n    function GetEvents(Index: Integer): TEvent;\n    function GetMaxListeners: Integer;\n    procedure SetMaxListeners(AValue: Integer);\n  protected\n    class function InitializePrototype(AConstructor: JsValueRef): JsValueRef; override;\n    class procedure RegisterMethods(AInstance: JsValueRef); override;\n\n    function _AddListener(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _Emit(Args: PJsValueRef; ArgCount: Word): JsValueRef;\n    function _EventNames(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _GetMaxListeners(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _ListenerCount(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _Listeners(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _Off(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _On(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _Once(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _PrependListener(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _PrependOnceListener(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _RemoveAllListeners(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _RemoveListener(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _SetMaxListeners(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n    function _RawListeners(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\n  public\n    constructor Create(Args: PJsValueRef = nil; ArgCount: Word = 0; AFinalize: Boolean = False); overload; override;\n    destructor Destroy; override;\n\n    procedure AddListener(Name, Listener: JsValueRef; Once: Boolean = False);\n    function FindEvent(Name: JsValueRef): TEvent;\n    procedure PrependListener(Name, Listener: JsValueRef; Once: Boolean = False);\n    procedure RemoveListener(Name, Listener: JsValueRef);\n\n    property EventCount: Integer read GetEventCount;\n    property Events[Index: Integer]: TEvent read GetEvents;\n    property MaxListeners: Integer read GetMaxListeners write SetMaxListeners;\n  end;\n\nimplementation\n\n// TODO move to ChakraCoreUtils\n\ntype\n  JsValueTypes = set of JsValueType;\n\nconst\n  JsValueTypeStrings: array[JsValueType] of UnicodeString = (\n    'undefined',\n    'null',\n    'number',\n    'string',\n    'boolean',\n    'object',\n    'function',\n    'error',\n    'array',\n    'symbol',\n    'ArrayBuffer',\n    'TypedArray',\n    'DataView'\n);\n\nfunction JsValueTypesStr(ValueTypes: JsValueTypes): UnicodeString;\nvar\n  ValueType: JsValueType;\nbegin\n  Result := '';\n  for ValueType := Low(JsValueType) to High(JsValueType) do\n    if ValueType in ValueTypes then\n    begin\n      if Result <> '' then\n        Result := Result + ', ';\n      Result := Result + JsValueTypeStrings[ValueType];\n    end;\nend;\n\nprocedure CheckArgCount(Expected, Actual: Word);\nbegin\n  if Expected <> Actual then\n    raise Exception.CreateFmt('Invalid number of arguments: %d (expected %d)', [Actual, Expected]);\nend;\n\nprocedure CheckMinArgCount(Expected, Actual: Word);\nbegin\n  if Expected > Actual then\n    raise Exception.CreateFmt('Invalid number of arguments: %d (expected at least %d)', [Actual, Expected]);\nend;\n\nprocedure CheckArgValueType(Expected: JsValueType; Arg: JsValueRef); overload;\nvar\n  ArgValueType: JsValueType;\nbegin\n  ArgValueType := JsGetValueType(Arg);\n  if Expected <> ArgValueType then\n    raise Exception.CreateFmt('Invalid argument type %s (expected %s)',\n      [JsValueTypeStrings[ArgValueType], JsValueTypeStrings[Expected]]);\nend;\n\nprocedure CheckArgValueType(Expected: JsValueTypes; Arg: JsValueRef); overload;\nvar\n  ArgValueType: JsValueType;\nbegin\n  ArgValueType := JsGetValueType(Arg);\n  if not (ArgValueType in Expected) then\n    raise Exception.CreateFmt('Invalid argument type %s (expected %s)', [JsValueTypesStr(Expected)]);\nend;\n\n{ TEvent private }\n\nfunction TEvent.GetListenerCount: Integer;\nbegin\n  Result := FListeners.Count;\nend;\n\nfunction TEvent.GetListeners(Index: Integer): JsValueRef;\nbegin\n  Result := FListeners[Index];\nend;\n\n{ TEvent public }\n\nconstructor TEvent.Create(AOwner: TEventEmitter; AName: JsValueRef);\nbegin\n  inherited Create;\n  FOwner := AOwner;\n  FName := AName;\n  FListeners := TList.Create;\n  FOnceList := TList.Create;\n  if Assigned(FOwner) then\n    FOwner.FEvents.Add(Self);\nend;\n\ndestructor TEvent.Destroy;\nbegin\n  if Assigned(FOwner) then\n    FOwner.FEvents.Remove(Self);\n  FListeners.Free;\n  FOnceList.Free;\n  inherited Destroy;\nend;\n\nfunction TEvent.AddListener(AListener: JsValueRef; AOnce: Boolean): Integer;\nbegin\n  Result := FListeners.Add(AListener);\n  if AOnce and (FOnceList.IndexOf(AListener) = -1) then\n    FOnceList.Add(AListener);\nend;\n\nprocedure TEvent.Emit(Args: PJsValueRef; ArgCount: Word);\nvar\n  NewArgs: array of JsValueRef;\n  I, J: Integer;\nbegin\n  SetLength(NewArgs, ArgCount + 1);\n  NewArgs[0] := FOwner.Instance;\n  if ArgCount > 0 then\n    Move(Args^, NewArgs[1], ArgCount * SizeOf(JsValueRef));\n\n  for I := 0 to FListeners.Count - 1 do\n    JsCallFunction(FListeners[I], @NewArgs[0], ArgCount + 1);\n\n  for I := FListeners.Count - 1 downto 0 do\n  begin\n    J := FOnceList.IndexOf(FListeners[I]);\n    if J <> -1 then\n    begin\n      FListeners.Delete(I);\n      FOnceList.Delete(J);\n    end;\n  end;\nend;\n\nprocedure TEvent.Emit(const Args: array of JsValueRef);\nvar\n  PArg: PJsValueRef;\n  Len: Integer;\nbegin\n  PArg := nil;\n  Len := Length(Args);\n  if Len > 0 then\n    PArg := @Args[0];\n  Emit(PArg, Len);\nend;\n\nprocedure TEvent.PrependListener(AListener: JsValueRef; AOnce: Boolean);\nbegin\n  FListeners.Insert(0, AListener);\n  if AOnce and (FOnceList.IndexOf(AListener) = -1) then\n    FOnceList.Add(AListener);\nend;\n\nfunction TEvent.RemoveListener(AListener: JsValueRef): Integer;\nbegin\n  Result := FListeners.Remove(AListener);\nend;\n\nprocedure TEvent.RemoveListeners;\nbegin\n  FListeners.Clear;\nend;\n\n{ TEventEmitter private }\n\nfunction TEventEmitter.GetEventCount: Integer;\nbegin\n  Result := FEvents.Count;\nend;\n\nfunction TEventEmitter.GetEvents(Index: Integer): TEvent;\nbegin\n  Result := TEvent(FEvents[Index]);\nend;\n\nfunction TEventEmitter.GetMaxListeners: Integer;\nbegin\n  Result := FMaxListeners;\n  if Result = -1 then\n    Result := JsNumberToInt(JsValueAsJsNumber(JsGetProperty(Instance, 'defaultMaxListeners')));\nend;\n\nprocedure TEventEmitter.SetMaxListeners(AValue: Integer);\nbegin\n  if AValue <> FMaxListeners then\n  begin\n    if AValue < 0 then\n      FMaxListeners := -1\n    else\n      FMaxListeners := AValue;\n  end;\nend;\n\n{ TEventEmitter protected }\n\nclass function TEventEmitter.InitializePrototype(AConstructor: JsValueRef): JsValueRef;\nbegin\n  Result := inherited InitializePrototype(AConstructor);\n  JsSetProperty(Result, 'defaultMaxListeners', IntToJsNumber(DefaultMaxListeners));\n  RegisterClassMethod(AConstructor, 'listenerCount', @TEventEmitter._ListenerCount);\nend;\n\nclass procedure TEventEmitter.RegisterMethods(AInstance: JsValueRef);\nbegin\n  RegisterMethod(AInstance, 'addListener',         @TEventEmitter._AddListener);\n  RegisterMethod(AInstance, 'emit',                @TEventEmitter._Emit);\n  RegisterMethod(AInstance, 'eventNames',          @TEventEmitter._EventNames);\n  RegisterMethod(AInstance, 'getMaxListeners',     @TEventEmitter._GetMaxListeners);\n  RegisterMethod(AInstance, 'listeners',           @TEventEmitter._Listeners);\n  RegisterMethod(AInstance, 'off',                 @TEventEmitter._Off);\n  RegisterMethod(AInstance, 'on',                  @TEventEmitter._On);\n  RegisterMethod(AInstance, 'once',                @TEventEmitter._Once);\n  RegisterMethod(AInstance, 'prependListener',     @TEventEmitter._PrependListener);\n  RegisterMethod(AInstance, 'prependOnceListener', @TEventEmitter._PrependOnceListener);\n  RegisterMethod(AInstance, 'removeAllListeners',  @TEventEmitter._RemoveAllListeners);\n  RegisterMethod(AInstance, 'removeListener',      @TEventEmitter._RemoveListener);\n  RegisterMethod(AInstance, 'setMaxListeners',     @TEventEmitter._SetMaxListeners);\n  RegisterMethod(AInstance, 'rawListeners',        @TEventEmitter._RawListeners);\nend;\n\nfunction TEventEmitter._AddListener(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nbegin\n  Result := _On(Args, ArgCount);\nend;\n\nfunction TEventEmitter._Emit(Args: PJsValueRef; ArgCount: Word): JsValueRef;\nvar\n  Event: TEvent;\nbegin\n  Result := JsUndefinedValue;\n  try\n    CheckMinArgCount(1, ArgCount);\n    CheckArgValueType([JsSymbol, JsString], Args^);\n\n    Event := FindEvent(Args^);\n    if not Assigned(Event) then\n      raise EListError.CreateFmt('Event %s not found', [JsStringToUnicodeString(JsValueAsJsString(Args^))]);\n\n    Inc(Args);\n    Dec(ArgCount);\n\n    Event.Emit(Args, ArgCount);\n    Result := Instance;\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TEventEmitter._EventNames(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nvar\n  I: Integer;\nbegin\n  Result := JsUndefinedValue;\n  try\n    Result := JsCreateArray(EventCount);\n    for I := 0 to EventCount - 1 do\n      JsSetIndexedProperty(Result, IntToJsNumber(I), Events[I].Name);\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TEventEmitter._GetMaxListeners(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n  try\n    Result := IntToJsNumber(GetMaxListeners);\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TEventEmitter._ListenerCount(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nvar\n  Emitter: TEventEmitter;\n  Event: TEvent;\nbegin\n  Result := JsUndefinedValue;\n  try\n    CheckArgCount(2, ArgCount);\n    CheckArgValueType([JsObject], Args^[0]);\n    CheckArgValueType([JsSymbol, JsString], Args^[1]);\n\n    Emitter := TEventEmitter(JsGetExternalData(Args^[0]));\n    Event := Emitter.FindEvent(Args^[1]);\n    if not Assigned(Event) then\n      raise EListError.CreateFmt('Event ''%s'' not found for %s', [JsStringToUnicodeString(JsValueAsJsString(Args^[1])),\n        Emitter.ClassName]);\n\n    Result := IntToJsNumber(Event.ListenerCount);\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TEventEmitter._Listeners(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nvar\n  Event: TEvent;\n  I: Integer;\nbegin\n  Result := JsUndefinedValue;\n  try\n    CheckArgCount(1, ArgCount);\n    CheckArgValueType([JsSymbol, JsString], Args^[0]);\n    Event := FindEvent(Args^[0]);\n    if not Assigned(Event) then\n      raise EListError.CreateFmt('Event %s not found', [JsStringToUnicodeString(JsValueAsJsString(Args^[0]))]);\n\n    Result := JsCreateArray(Event.ListenerCount);\n    for I := 0 to Event.ListenerCount - 1 do\n      JsSetIndexedProperty(Result, IntToJsNumber(I), Event.Listeners[I]);\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TEventEmitter._Off(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n  try\n    CheckArgCount(2, ArgCount);\n    CheckArgValueType([JsSymbol, JsString], Args^[0]);\n    CheckArgValueType(JsFunction, Args^[1]);\n    RemoveListener(Args^[0], Args^[1]);\n    Result := Instance;\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TEventEmitter._On(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n  try\n    CheckArgCount(2, ArgCount);\n    CheckArgValueType([JsSymbol, JsString], Args^[0]);\n    CheckArgValueType(JsFunction, Args^[1]);\n    AddListener(Args^[0], Args^[1]);\n    Result := Instance;\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TEventEmitter._Once(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n  try\n    CheckArgCount(2, ArgCount);\n    CheckArgValueType([JsSymbol, JsString], Args^[0]);\n    CheckArgValueType(JsFunction, Args^[1]);\n    AddListener(Args^[0], Args^[1], True);\n    Result := Instance;\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TEventEmitter._PrependListener(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n  try\n    CheckArgCount(2, ArgCount);\n    CheckArgValueType([JsSymbol, JsString], Args^[0]);\n    CheckArgValueType(JsFunction, Args^[1]);\n    PrependListener(Args^[0], Args^[1]);\n    Result := Instance;\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TEventEmitter._PrependOnceListener(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n  try\n    CheckArgCount(2, ArgCount);\n    CheckArgValueType([JsSymbol, JsString], Args^[0]);\n    CheckArgValueType(JsFunction, Args^[1]);\n    PrependListener(Args^[0], Args^[1], True);\n    Result := Instance;\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TEventEmitter._RemoveAllListeners(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nvar\n  I: Integer;\n  Event: TEvent;\nbegin\n  Result := JsUndefinedValue;\n  try\n    if ArgCount = 0 then\n    begin\n      for I := 0 to EventCount - 1 do\n        Events[I].RemoveListeners;\n    end\n    else\n    begin\n      CheckArgValueType([JsSymbol, JsString], Args^[0]);\n      Event := FindEvent(Args^[0]);\n      if not Assigned(Event) then\n        raise EListError.CreateFmt('Event %s not found', [JsStringToUnicodeString(JsValueAsJsString(Args^[0]))]);\n      Event.RemoveListeners;\n    end;\n\n    Result := Instance;\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TEventEmitter._RemoveListener(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nbegin\n  Result := _Off(Args, ArgCount);\nend;\n\nfunction TEventEmitter._SetMaxListeners(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n  try\n    CheckArgCount(1, ArgCount);\n    CheckArgValueType(JsNumber, Args^[0]);\n    MaxListeners := JsNumberToInt(Args^[0]);\n    Result := Instance;\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TEventEmitter._RawListeners(Args: PJsValueRefArray; ArgCount: Word): JsValueRef;\nbegin\n  Result := _Listeners(Args, ArgCount);\nend;\n\n{ TEventEmitter public }\n\nconstructor TEventEmitter.Create(Args: PJsValueRef; ArgCount: Word; AFinalize: Boolean);\nbegin\n  inherited Create(Args, ArgCount, AFinalize);\n  FEvents := TList.Create;\n  FMaxListeners := -1;\n  TEvent.Create(Self, StringToJsString('newListener'));\n  TEvent.Create(Self, StringToJsString('removeListener'));\nend;\n\ndestructor TEventEmitter.Destroy;\nvar\n  I: Integer;\nbegin\n  for I := FEvents.Count - 1 downto 0 do\n    TEvent(FEvents[I]).Free;\n  FEvents.Free;\n  inherited Destroy;\nend;\n\nprocedure TEventEmitter.AddListener(Name, Listener: JsValueRef; Once: Boolean);\nvar\n  Event: TEvent;\nbegin\n  Event := FindEvent(Name);\n  if not Assigned(Event) then\n    Event := TEvent.Create(Self, Name);\n  Event.AddListener(Listener, Once);\n\n  Event := FindEvent(StringToJsString('newListener'));\n  Event.Emit([Name, Listener]);\nend;\n\nfunction TEventEmitter.FindEvent(Name: JsValueRef): TEvent;\nvar\n  I: Integer;\nbegin\n  Result := nil;\n\n  for I := 0 to EventCount - 1 do\n    if JsEqual(Name, Events[I].Name) then\n    begin\n      Result := Events[I];\n      Break;\n    end;\nend;\n\nprocedure TEventEmitter.PrependListener(Name, Listener: JsValueRef; Once: Boolean);\nvar\n  Event: TEvent;\nbegin\n  Event := FindEvent(Name);\n  if not Assigned(Event) then\n    Event := TEvent.Create(Self, Name);\n  Event.PrependListener(Listener, Once);\n\n  Event := FindEvent(StringToJsString('newListener'));\n  Event.Emit([Name, Listener]);\nend;\n\nprocedure TEventEmitter.RemoveListener(Name, Listener: JsValueRef);\nvar\n  Event: TEvent;\nbegin\n  Event := FindEvent(Name);\n  if Assigned(Event) then\n    Event.RemoveListener(Listener);\n\n  Event := FindEvent(StringToJsString('removeListener'));\n  Event.Emit([Name, Listener]);\nend;\n\nend.\n"
  },
  {
    "path": "samples/NodeSample/NodeMainData.dfm",
    "content": "object DataModuleMain: TDataModuleMain\n  OldCreateOrder = False\n  OnCreate = DataModuleCreate\n  OnDestroy = DataModuleDestroy\n  Height = 265\n  Width = 368\nend\n"
  },
  {
    "path": "samples/NodeSample/NodeMainData.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nunit NodeMainData;\n\ninterface\n\n{$include common.inc}\n\nuses\n{$ifdef FPC}{$ifdef UNIX}\n  cwstring,\n{$endif}{$endif}\n{$ifdef WINDOWS}\n  Windows,\n{$endif}\n  SysUtils, Classes, Types, Contnrs,\n{$ifdef HAS_WIDESTRUTILS}\n  WideStrUtils,\n{$endif}\n  Compat, ChakraCommon, ChakraCore, ChakraCoreUtils, ChakraCoreClasses,\n  Console, NodeProcess;\n\ntype\n  TNodeModule = class\n  private\n    FFileName: UnicodeString;\n    FHandle: JsvalueRef;\n    FParent: TNodeModule;\n    FRequire: JsValueRef;\n  public\n    constructor Create(AParent: TNodeModule);\n\n    property FileName: UnicodeString read FFileName;\n    property Handle: JsValueRef read FHandle;\n    property Parent: TNodeModule read FParent;\n    property Require: JsValueRef read FRequire;\n  end;\n\n  { TDataModuleMain }\n\n  TDataModuleMain = class(TDataModule)\n    procedure DataModuleCreate(Sender: TObject);\n    procedure DataModuleDestroy(Sender: TObject);\n  private\n    FBaseDir: UnicodeString;\n    FConsole: TConsole;\n    FContext: TChakraCoreContext;\n    FMainModule: TNodeModule;\n    FModules: TObjectList;\n    FNodeBaseDir: UnicodeString;\n    FProcess: TProcess;\n    FRuntime: TChakraCoreRuntime;\n    FUseAnsiColors: Boolean;\n\n    procedure ConsoleLog(Sender: TObject; const Text: UnicodeString; Level: TInfoLevel = ilNone);\n    procedure ContextActivate(Sender: TObject);\n    procedure ContextLoadModule(Sender: TObject; Module: TChakraModule);\n    procedure ContextNativeObjectCreated(Sender: TObject; NativeObject: TNativeObject);\n    function FindModule(ARequire: JsValueRef): TNodeModule; overload;\n    function FindModule(const AFileName: UnicodeString): TNodeModule; overload;\n    procedure LoadModule(Module: TNodeModule; const FileName: UnicodeString);\n    function LoadPackage(const FileName: UnicodeString): JsValueRef;\n    function Require(CallerModule: TNodeModule; const Path: UnicodeString): JsValueRef;\n    function Resolve(const Request, CurrentPath: UnicodeString): UnicodeString;\n    function ResolveDirectory(const Request: UnicodeString; out FileName: UnicodeString): Boolean;\n    function ResolveFile(const Request: UnicodeString; out FileName: UnicodeString): Boolean;\n    function ResolveIndex(const Request: UnicodeString; out FileName: UnicodeString): Boolean;\n    function ResolveModules(const Request: UnicodeString; out FileName: UnicodeString): Boolean;\n    function RunModule(Module: TNodeModule): JsValueRef;\n  public\n    procedure Execute(const FileName: UnicodeString);\n\n    property BaseDir: UnicodeString read FBaseDir;\n    property Console: TConsole read FConsole;\n    property Context: TChakraCoreContext read FContext;\n    property NodeBaseDir: UnicodeString read FNodeBaseDir;\n    property Runtime: TChakraCoreRuntime read FRuntime;\n    property UseAnsiColors: Boolean read FUseAnsiColors write FUseAnsiColors;\n  end;\n\nimplementation\n\n{$R *.dfm}\n\nfunction JsInspectHandler(Value: JsValueRef; E: Exception): UnicodeString;\nbegin\n  Result := WideFormat('[%s] %s', [E.ClassName, E.Message]);\nend;\n\nfunction CombinePath(const Path, Name: UnicodeString): UnicodeString;\nbegin\n  Result := IncludeTrailingPathDelimiter(Path) + Name;\nend;\n\nfunction ParentPath(const Path: UnicodeString): UnicodeString;\nbegin\n  Result := ExtractFilePath(ExcludeTrailingPathDelimiter(Path));\nend;\n\nfunction LoadFile(const FileName: UnicodeString): UnicodeString;\nvar\n  FileStream: TFileStream;\n  S: UTF8String;\nbegin\n  Result := '';\n\n  FileStream := TFileStream.Create(FileName, fmOpenRead);\n  try\n    if FileStream.Size = 0 then\n      Exit;\n\n    SetLength(S, FileStream.Size);\n    FileStream.Read(S[1], FileStream.Size);\n\n    Result := UTF8ToString(S);\n  finally\n    FileStream.Free;\n  end;\nend;\n\nfunction PostTimedTask(Args: PJsValueRefArray; ArgCount: Word; CallbackState: Pointer; RepeatCount: Integer): JsValueRef;\nvar\n  DataModule: TDataModuleMain absolute CallbackState;\n  AMessage: TTaskMessage;\n  Delay: Cardinal;\n  FuncArgs: array of JsValueRef;\n  I: Integer;\nbegin\n  Result := JsUndefinedValue;\n\n  if ArgCount < 2 then // thisarg, function to call, optional: delay, function args\n    raise Exception.Create('Invalid arguments');\n\n  if ArgCount >= 3 then\n    Delay := JsNumberToInt(Args^[2])\n  else\n    Delay := 0;\n\n  if ArgCount >= 4 then\n  begin\n    SetLength(FuncArgs, ArgCount - 3);\n    for I := 0 to ArgCount - 4 do\n      FuncArgs[I] := Args^[I + 3];\n  end;\n\n  AMessage := TTaskMessage.Create(DataModule.Context, Args^[1], Args^[0], FuncArgs, Delay, RepeatCount);\n  try\n    DataModule.Context.PostMessage(AMessage);\n  except\n    AMessage.Free;\n    raise;\n  end;\nend;\n\nfunction Require_Callback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRefArray; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nvar\n  DataModule: TDataModuleMain absolute CallbackState;\n  CallerModule: TNodeModule;\n  Path: UnicodeString;\nbegin\n  Result := JsUndefinedValue;\n  try\n    if ArgCount <> 2 then\n      raise Exception.Create('require: module name not specified');\n\n    if JsGetValueType(Args^[1]) <> JsString then\n      raise Exception.Create('require: module name not a string value');\n\n    CallerModule := DataModule.FindModule(Callee);\n    Path := JsStringToUnicodeString(Args^[1]);\n    if PathDelim <> '/' then\n      Path := UnicodeStringReplace(Path, '/', PathDelim, [rfReplaceAll]);\n\n    Result := DataModule.Require(CallerModule, Path);\n  except\n    on E: EChakraCoreScript do\n      JsThrowError(WideFormat('%s (%d, %d): [%s] %s', [E.ScriptURL, E.Line + 1, E.Column + 1, E.ClassName, E.Message]));\n    on E: Exception do\n      JsThrowError(WideFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction SetInterval_Callback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRefArray; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := PostTimedTask(Args, ArgCount, CallbackState, -1); // repeat endlessly\nend;\n\nfunction SetTimeout_Callback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRefArray; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := PostTimedTask(Args, ArgCount, CallbackState, 1); // run once\nend;\n\ntype\n  THackPromiseMessage = class(TPromiseMessage);\n\n  TDummyPromiseThread = class(TThread)\n  private\n    FMessage: TPromiseMessage;\n    FTimeout: Cardinal;\n    FValue: JsValueRef;\n  protected\n    procedure Execute; override;\n  public\n    constructor Create(AMessage: TPromiseMessage; ATimeout: Cardinal);\n  end;\n\n{ TTestPromiseThread }\n\nprocedure TDummyPromiseThread.Execute;\nbegin\n  Sleep(FTimeout);\n  THackPromiseMessage(FMessage).SetStatus(psResolved, FValue);\nend;\n\nconstructor TDummyPromiseThread.Create(AMessage: TPromiseMessage; ATimeout: Cardinal);\nbegin\n  FMessage := AMessage;\n  FTimeout := ATimeout;\n  FValue := StringToJsString('Success!');\n  JsAddRef(FValue);\n  FreeOnTerminate := True;\n  inherited Create(False);\nend;\n\nprocedure TDataModuleMain.ConsoleLog(Sender: TObject; const Text: UnicodeString; Level: TInfoLevel);\nconst\n  StartBlocks: array[TInfoLevel] of RawByteString = ('', #$1b'[32;1m', #$1b'[33;1m', #$1b'[31;1m');\n  EndBlocks: array[Boolean] of RawByteString = ('', #$1b'[0m');\n{$ifdef WINDOwS}\n  BackgroundMask = $F0;\n  TextColors: array[TInfoLevel] of Word = (0, FOREGROUND_GREEN or FOREGROUND_INTENSITY,\n    FOREGROUND_GREEN or FOREGROUND_RED or FOREGROUND_INTENSITY, FOREGROUND_RED or FOREGROUND_INTENSITY);\n{$endif}\nvar\n{$ifdef WINDOWS}\n  Info: TConsoleScreenBufferInfo;\n{$endif}\n  S: UTF8String;\nbegin\n  S := UTF8Encode(Text);\n{$ifdef WINDOWS}\n  if UseAnsiColors then\n    Writeln(StartBlocks[Level], S, EndBlocks[Level <> ilNone])\n  else\n  begin\n    if (Level = ilNone) or not GetConsoleScreenBufferInfo(TTextRec(Output).Handle, Info) then\n    begin\n      Writeln(S);\n      Exit;\n    end;\n\n    SetConsoleTextAttribute(TTextRec(Output).Handle, Info.wAttributes and BackgroundMask or TextColors[Level]);\n    try\n      Writeln(S);\n    finally\n      SetConsoleTextAttribute(TTextRec(Output).Handle, Info.wAttributes);\n    end;\n  end;\n{$else}\n  Writeln(StartBlocks[Level], S, EndBlocks[Level <> ilNone]);\n{$endif}\nend;\n\nprocedure TDataModuleMain.ContextActivate(Sender: TObject);\nbegin\n  // expose global.console\n  FConsole := TConsole.Create;\n  FConsole.OnLog := ConsoleLog;\n  JsSetProperty(FContext.Global, 'console', FConsole.Instance);\n\n  // expose additional functions\n  JsSetCallback(FContext.Global, 'setTimeout', @SetTimeout_Callback, Self);\n  JsSetCallback(FContext.Global, 'setInterval', @SetInterval_Callback, Self);\n\n  FProcess := TProcess.Create;\n  JsSetProperty(FContext.Global, 'process', FProcess.Instance);\n\n  JsSetCallback(FContext.Global, 'require', @Require_Callback, Self);\nend;\n\nprocedure TDataModuleMain.ContextLoadModule(Sender: TObject; Module: TChakraModule);\nbegin\n  // TODO ES6 modules\nend;\n\nprocedure TDataModuleMain.ContextNativeObjectCreated(Sender: TObject; NativeObject: TNativeObject);\nbegin\n  if NativeObject is TConsole then\n    TConsole(NativeObject).OnLog := ConsoleLog;\nend;\n\nfunction TDataModuleMain.FindModule(ARequire: JsValueRef): TNodeModule;\nvar\n  I: Integer;\nbegin\n  Result := nil;\n\n  for I := 0 to FModules.Count - 1 do\n    if TNodeModule(FModules[I]).Require = ARequire then\n    begin\n      Result := TNodeModule(FModules[I]);\n      Break;\n    end;\nend;\n\nfunction TDataModuleMain.FindModule(const AFileName: UnicodeString): TNodeModule;\nvar\n  I: Integer;\nbegin\n  Result := nil;\n\n  for I := 0 to FModules.Count - 1 do\n    if WideSameText(AFileName, TNodeModule(FModules[I]).FileName) then\n    begin\n      Result := TNodeModule(FModules[I]);\n      Break;\n    end;\nend;\n\nprocedure TDataModuleMain.LoadModule(Module: TNodeModule; const FileName: UnicodeString);\nvar\n  WrapScript: UnicodeString;\nbegin\n  if ExtractFileExt(FileName) = '.json' then\n    WrapScript := '(function (exports, require, module, __filename, __dirname) {' + sLineBreak +\n      'module.exports = ' + LoadFile(FileName) + ';' + sLineBreak + '})'\n  else\n    WrapScript := '(function (exports, require, module, __filename, __dirname) {' + sLineBreak +\n      LoadFile(FileName) + sLineBreak + '})';\n  Module.FFileName := FileName;\n  Module.FHandle := FContext.RunScript(WrapScript, FileName);\n  JsSetProperty(Module.Handle, 'exports', JsCreateObject);\n  JsSetProperty(Module.Handle, '__dirname', StringToJsString(ExtractFilePath(FileName)));\n  JsSetProperty(Module.Handle, '__filename', StringToJsString(FileName));\n  Module.FRequire := JsSetCallback(Module.Handle, 'require', @Require_Callback, Self);\n\n  ConsoleLog(FConsole, WideFormat('Loaded module ''%s''', [ExtractRelativePath(FBaseDir, Module.FileName)]), ilInfo);\nend;\n\nfunction TDataModuleMain.LoadPackage(const FileName: UnicodeString): JsValueRef;\nbegin\n  Result := FContext.CallFunction('parse', [StringToJsString(LoadFile(FileName))], JsGetProperty(JsGlobal, 'JSON'));\nend;\n\nfunction TDataModuleMain.Require(CallerModule: TNodeModule; const Path: UnicodeString): JsValueRef;\nvar\n  FileName: UnicodeString;\n  Module: TNodeModule;\nbegin\n  if Assigned(CallerModule) then\n    FileName := Resolve(Path, ExtractFilePath(CallerModule.FileName))\n  else\n    FileName := Resolve(Path, FBaseDir);\n\n  if FileName = '' then\n    raise Exception.CreateFmt('Module ''%s'' not found', [Path]);\n\n  FileName := ExpandFileName(FileName);\n\n  Module := FindModule(FileName);\n  if not Assigned(Module) then\n  begin\n    Module := TNodeModule.Create(CallerModule);\n    try\n      FModules.Add(Module);\n      LoadModule(Module, FileName);\n      RunModule(Module);\n    except\n      on E: Exception do\n      begin\n        if Module <> FMainModule then\n          FModules.Remove(Module);\n        raise;\n      end;\n    end;\n  end;\n  \n  Result := JsGetProperty(Module.Handle, 'exports');\nend;\n\nfunction TDataModuleMain.Resolve(const Request, CurrentPath: UnicodeString): UnicodeString;\nvar\n  BasePaths: array[0..1] of UnicodeString;\n  SRequest: UnicodeString;\n  I: Integer;\nbegin\n  Result := '';\n  if Request = '' then\n    Exit;\n\n  if Request[1] = '/' then\n    BasePaths[0] := {$ifdef MSWINDOWS}ExtractFileDrive(CurrentPath){$else}''{$endif};\n  if (Request[1] = PathDelim) or\n    ((Length(Request) > 1) and (Request[1] = '.') and (Request[2] = PathDelim)) or\n    ((Length(Request) > 2) and (Request[1] = '.') and (Request[2] = '.') and (Request[3] = PathDelim)) then\n    BasePaths[0] := CurrentPath;\n  BasePaths[1] := ExtractFilePath(ParamStr(0)) + '..' + PathDelim + '..' + PathDelim + '..' + PathDelim +\n    'ext' + PathDelim + 'node' + PathDelim + 'lib';\n\n  SRequest := Request;\n  if PathDelim <> '/' then\n    SRequest := UnicodeStringReplace(SRequest, '/', PathDelim, [rfReplaceAll]);\n\n  for I := Low(BasePaths) to High(BasePaths) do\n  begin\n    if ResolveFile(IncludeTrailingPathDelimiter(BasePaths[I]) + SRequest, Result) then\n      Exit;\n    if ResolveDirectory(IncludeTrailingPathDelimiter(BasePaths[I]) + SRequest, Result) then\n      Exit;\n  end;\n\n  if not ResolveModules(Request, Result) then\n    Result := '';\nend;\n\nfunction TDataModuleMain.ResolveDirectory(const Request: UnicodeString; out FileName: UnicodeString): Boolean;\nvar\n  Package, Main: UnicodeString;\nbegin\n  FileName := '';\n\n  Package := IncludeTrailingPathDelimiter(Request) + 'package.json';\n  if FileExists(Package) then\n  begin\n    Main := IncludeTrailingPathDelimiter(Request) + JsStringToUnicodeString(JsGetProperty(LoadPackage(Package), 'main'));\n    if PathDelim <> '/' then\n      Main := UnicodeStringReplace(Main, '/', PathDelim, [rfReplaceAll]);\n\n    Result := ResolveFile(Main, FileName) or ResolveIndex(Main, FileName);\n    if Result then\n      Exit;\n  end;\n\n  Result := ResolveIndex(Request, FileName);\nend;\n\nfunction TDataModuleMain.ResolveFile(const Request: UnicodeString; out FileName: UnicodeString): Boolean;\nbegin\n  Result := False;\n  FileName := '';\n\n  if FileExists(Request) and not DirectoryExists(Request) then\n  begin\n    FileName := Request;\n    Result := True;\n  end\n  else if FileExists(Request + '.js') then\n  begin\n    FileName := Request + '.js';\n    Result := True;\n  end\n  else if FileExists(Request + '.json') then\n  begin\n    FileName := Request + '.json';\n    Result := True;\n  end\n  else if FileExists(Request + '.node') then\n  begin\n    FileName := Request + '.node';\n    Result := True;\n  end;\nend;\n\nfunction TDataModuleMain.ResolveIndex(const Request: UnicodeString; out FileName: UnicodeString): Boolean;\nbegin\n  Result := False;\n  FileName := '';\n\n  if FileExists(IncludeTrailingPathDelimiter(Request) + 'index.js') then\n  begin\n    FileName := IncludeTrailingPathDelimiter(Request) + 'index.js';\n    Result := True;\n  end\n  else if FileExists(IncludeTrailingPathDelimiter(Request) + 'index.json') then\n  begin\n    FileName := IncludeTrailingPathDelimiter(Request) + 'index.json';\n    Result := True;\n  end\n  else if FileExists(IncludeTrailingPathDelimiter(Request) + 'index.node') then\n  begin\n    FileName := IncludeTrailingPathDelimiter(Request) + 'index.node';\n    Result := True;\n  end\nend;\n\nfunction TDataModuleMain.ResolveModules(const Request: UnicodeString; out FileName: UnicodeString): Boolean;\nvar\n  NodeModulePaths: array of UnicodeString;\n  I: Integer;\nbegin\n  Result := False;\n  FileName := '';\n\n  // TODO global paths etc.\n  SetLength(NodeModulePaths, 1);\n  NodeModulePaths[0] := IncludeTrailingPathDelimiter(FBaseDir) + 'node_modules';\n\n  for I := 0 to High(NodeModulePaths) do\n  begin\n    Result := ResolveFile(IncludeTrailingPathDelimiter(NodeModulePaths[I]) + Request, FileName);\n    if Result then\n      Break;\n    Result := ResolveDirectory(IncludeTrailingPathDelimiter(NodeModulePaths[I]) + Request, FileName);\n    if Result then\n      Break;\n  end;\nend;\n\nfunction TDataModuleMain.RunModule(Module: TNodeModule): JsValueRef;\nbegin\n  FContext.CallFunction(Module.Handle, [JsGetProperty(Module.Handle, 'exports'), Module.Require, Module.Handle,\n    StringToJsString(Module.FileName), StringToJsString(ExtractFilePath(Module.FileName))], Module.Handle);\n  Result := JsGetProperty(Module.Handle, 'exports');\nend;\n\nprocedure TDataModuleMain.DataModuleCreate(Sender: TObject);\nbegin\n  try\n    JsInspectExceptionHandler := JsInspectHandler;\n    FRuntime := TChakraCoreRuntime.Create([ccroEnableExperimentalFeatures, ccroDispatchSetExceptionsToDebugger]);\n    FContext := TChakraCoreContext.Create(FRuntime);\n    FContext.OnActivate := ContextActivate;\n    FContext.OnLoadModule := ContextLoadModule;\n    FContext.OnNativeObjectCreated := ContextNativeObjectCreated;\n    FBaseDir := GetCurrentDir;\n    FModules := TObjectList.Create;\n  except\n    FreeAndNil(FConsole);\n    FreeAndNil(FContext);\n    FreeAndNil(FRuntime);\n    raise;\n  end;\nend;\n\nprocedure TDataModuleMain.DataModuleDestroy(Sender: TObject);\nbegin\n  FreeAndNil(FConsole);\n  FreeAndNil(FProcess);\n  FreeAndNil(FModules);\n  FreeAndNil(FContext);\n  FreeAndNil(FRuntime);\nend;\n\nprocedure TDataModuleMain.Execute(const FileName: UnicodeString);\nvar\n  FullFileName: UnicodeString;\nbegin\n  FullFileName := ExpandFileName(FileName);\n  FBaseDir := ExtractFilePath(FullFileName);\n\n  FMainModule := TNodeModule.Create(nil);\n  try\n    FModules.Add(FMainModule);\n    LoadModule(FMainModule, FullFileName);\n    RunModule(FMainModule);\n  except\n    FModules.Remove(FMainModule);\n    FMainModule := nil;\n    raise;\n  end;\nend;\n\n{ TNodeModule public }\n\nconstructor TNodeModule.Create(AParent: TNodeModule);\nbegin\n  inherited Create;\n  FParent := AParent;\nend;\n\nend.\n"
  },
  {
    "path": "samples/NodeSample/NodeProcess.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nunit NodeProcess;\n\ninterface\n\nuses\n  Classes, SysUtils,\n  Compat, ChakraCommon, ChakraCoreUtils, ChakraCoreClasses,\n  EventEmitter;\n\ntype\n\n  { TProcess }\n\n  TProcess = class(TEventEmitter)\n  protected\n    class procedure RegisterMethods(AInstance: JsValueRef); override;\n    class procedure RegisterProperties(AInstance: JsValueRef); override;\n\n    function _Binding(Args: PJsValueRef; ArgCount: Word): JsValueRef;\n    function _Cwd(Args: PJsValueRef; ArgCount: Word): JsValueRef;\n  public\n    function Binding(const ModuleName: UnicodeString): JsValueRef;\n  end;\n\nimplementation\n\nfunction _ArgV: JsValueRef;\nvar\n  I: Integer;\nbegin\n  Result := JsCreateArray(ParamCount);\n  for I := 0 to ParamCount do\n    JsSetIndexedProperty(Result, IntToJsNumber(I), StringToJsString(UnicodeString(ParamStr(I))));\nend;\n\nfunction _Env: JsValueRef;\n{$ifdef FPC}\nvar\n  I: Integer;\n  S: array of AnsiString;\n{$endif FPC}\nbegin\n  Result := JsCreateObject;\n// TODO: implement for Delphi\n{$ifdef FPC}\n  for I := 0 to GetEnvironmentVariableCount - 1 do\n  begin\n    S := GetEnvironmentString(I).Split(['=']);\n    if (Length(S) > 1) and (not S[0].IsEmpty) then\n      JsSetProperty(Result, S[0], StringToJsString(S[1]));\n  end;\n{$endif FPC}\nend;\n\n{ TProcess protected }\n\nclass procedure TProcess.RegisterMethods(AInstance: JsValueRef);\nbegin\n  RegisterMethod(AInstance, 'binding', @TProcess._Binding);\n  RegisterMethod(AInstance, 'cwd', @TProcess._Cwd);\nend;\n\nclass procedure TProcess.RegisterProperties(AInstance: JsValueRef);\nconst\n{$ifdef CPU64}\n  sArch = 'x64';\n{$else}\n  sArch = 'x32';\n{$endif}\n{$ifdef MSWINDOWS}\n  sPlatform = 'win32';\n{$endif}\n{$ifdef DARWIN}\n  sPlatform = 'darwin';\n{$endif}\n{$ifdef LINUX}\n  sPlatform = 'linux';\n{$endif}\nbegin\n  RegisterNamedProperty(AInstance, 'arch', False, True, False, StringToJsString(sArch));\n  RegisterNamedProperty(AInstance, 'argv', False, True, False, _ArgV);\n  RegisterNamedProperty(AInstance, 'execPath', False, True, False, StringToJsString(ParamStr(0)));\n  RegisterNamedProperty(AInstance, 'env', False, True, False, _Env);\n  RegisterNamedProperty(AInstance, 'pid', False, True, False, IntToJsNumber(0{GetProcessID}));\n  RegisterNamedProperty(AInstance, 'platform', False, True, False, StringToJsString(sPlatform));\nend;\n\nfunction TProcess._Binding(Args: PJsValueRef; ArgCount: Word): JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n  try\n    if not Assigned(Args) or (ArgCount <> 1) then\n      raise Exception.Create('Invalid arguments');\n\n    if (JsGetValueType(Args^) <> JsString) then\n      raise Exception.Create('Invalid arguments');\n\n    Result := Binding(JsStringToUnicodeString(Args^));\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TProcess._Cwd(Args: PJsValueRef; ArgCount: Word): JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n  try\n    Result := StringToJsString(GetCurrentDir);\n  except\n    on E: Exception do\n      JsThrowError(UnicodeFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction TProcess.Binding(const ModuleName: UnicodeString): JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n  // TODO: node.js native bindings: buffer, uv, ...\nend;\n\nend.\n"
  },
  {
    "path": "samples/NodeSample/NodeSample.XE.dproj",
    "content": "﻿\t<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\t\t<PropertyGroup>\n\t\t\t<ProjectGuid>{36d30f07-2980-4d75-905b-ab8c50757d35}</ProjectGuid>\n\t\t\t<MainSource>NodeSample.dpr</MainSource>\n\t\t\t<Config Condition=\"'$(Config)'==''\">Debug</Config>\n\t\t\t<DCC_DCCCompiler>DCC32</DCC_DCCCompiler>\n\t\t\t<ProjectVersion>12.3</ProjectVersion>\n\t\t\t<Base>True</Base>\n\t\t\t<Platform>Win32</Platform>\n\t\t\t<AppType>Application</AppType>\n\t\t\t<FrameworkType>VCL</FrameworkType>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Base' or '$(Base)'!=''\">\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Release' or '$(Cfg_1)'!=''\">\n\t\t\t<Cfg_1>true</Cfg_1>\n\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Debug' or '$(Cfg_2)'!=''\">\n\t\t\t<Cfg_2>true</Cfg_2>\n\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Base)'!=''\">\n\t\t\t<DCC_DependencyCheckOutputName>..\\..\\bin\\$(Platform)\\$(Config)\\ChakraCoreHostSample.exe</DCC_DependencyCheckOutputName>\n\t\t\t<DCC_ExeOutput>..\\..\\bin\\$(Platform)\\$(Config)</DCC_ExeOutput>\n\t\t\t<DCC_DcuOutput>..\\..\\lib\\$(Platform)\\$(Config)</DCC_DcuOutput>\n\t\t\t<DCC_ImageBase>00400000</DCC_ImageBase>\n\t\t\t<DCC_UsePackage>vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP;JclDeveloperTools;Jcl;JclVcl;JclContainers</DCC_UsePackage>\n\t\t\t<DCC_UnitAlias>WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;$(DCC_UnitAlias)</DCC_UnitAlias>\n\t\t\t<DCC_Platform>x86</DCC_Platform>\n\t\t\t<DCC_UnitSearchPath>..\\..\\src;..\\HostSample;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>\n\t\t\t<DCC_K>false</DCC_K>\n\t\t\t<DCC_N>true</DCC_N>\n\t\t\t<DCC_S>false</DCC_S>\n\t\t\t<DCC_SymbolReferenceInfo>1</DCC_SymbolReferenceInfo>\n\t\t\t<DCC_E>false</DCC_E>\n\t\t\t<DCC_F>false</DCC_F>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Cfg_1)'!=''\">\n\t\t\t<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>\n\t\t\t<DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>\n\t\t\t<DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>\n\t\t\t<DCC_DebugInformation>false</DCC_DebugInformation>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Cfg_2)'!=''\">\n\t\t\t<DCC_Define>DEBUG;$(DCC_Define)</DCC_Define>\n\t\t</PropertyGroup>\n\t\t<ItemGroup>\n\t\t\t<DelphiCompile Include=\"NodeSample.dpr\">\n\t\t\t\t<MainSource>MainSource</MainSource>\n\t\t\t</DelphiCompile>\n\t\t\t<DCCReference Include=\"NodeMainData.pas\">\n\t\t\t\t<Form>DataModuleMain</Form>\n\t\t\t\t<DesignClass>TDataModule</DesignClass>\n\t\t\t</DCCReference>\n\t\t\t<DCCReference Include=\"WasmMainForm.pas\">\n\t\t\t\t<Form>FormMain</Form>\n\t\t\t</DCCReference>\n\t\t\t<BuildConfiguration Include=\"Debug\">\n\t\t\t\t<Key>Cfg_2</Key>\n\t\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t</BuildConfiguration>\n\t\t\t<BuildConfiguration Include=\"Base\">\n\t\t\t\t<Key>Base</Key>\n\t\t\t</BuildConfiguration>\n\t\t\t<BuildConfiguration Include=\"Release\">\n\t\t\t\t<Key>Cfg_1</Key>\n\t\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t</BuildConfiguration>\n\t\t</ItemGroup>\n\t\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Delphi.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Delphi.Targets\"/>\n\t\t<Import Condition=\"Exists('$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj')\" Project=\"$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj\"/>\n\t\t<ProjectExtensions>\n\t\t\t<Borland.Personality>Delphi.Personality.12</Borland.Personality>\n\t\t\t<Borland.ProjectType>VCLApplication</Borland.ProjectType>\n\t\t\t<BorlandProject>\n\t\t\t\t<Delphi.Personality>\n\t\t\t\t\t<Source>\n\t\t\t\t\t\t<Source Name=\"MainSource\">NodeSample.dpr</Source>\n\t\t\t\t\t</Source>\n\t\t\t\t\t<Parameters>\n\t\t\t\t\t\t<Parameters Name=\"RunParams\">..\\..\\..\\samples\\NodeSample\\scripts\\main.js ..\\..\\..\\samples\\NodeSample\\scripts\\main.wasm</Parameters>\n\t\t\t\t\t</Parameters>\n\t\t\t\t\t<VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"IncludeVerInfo\">True</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"AutoIncBuild\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"MajorVer\">1</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"MinorVer\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Release\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Build\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Debug\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"PreRelease\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Special\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Private\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"DLL\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Locale\">1033</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"CodePage\">1252</VersionInfo>\n\t\t\t\t\t</VersionInfo>\n\t\t\t\t\t<VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"CompanyName\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"FileDescription\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"FileVersion\">1.0.0.0</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"InternalName\">NodeSample</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"LegalCopyright\">© 2021 Ondrej Kelle</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"LegalTrademarks\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"OriginalFilename\">NodeSample</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"ProductName\">chakracore-delphi</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"ProductVersion\">1.0.0.0</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"Comments\"/>\n\t\t\t\t\t</VersionInfoKeys>\n\t\t\t\t</Delphi.Personality>\n\t\t\t\t<Platforms>\n\t\t\t\t\t<Platform value=\"Win32\">True</Platform>\n\t\t\t\t</Platforms>\n\t\t\t</BorlandProject>\n\t\t\t<ProjectFileVersion>12</ProjectFileVersion>\n\t\t</ProjectExtensions>\n\t</Project>\n"
  },
  {
    "path": "samples/NodeSample/NodeSample.dof",
    "content": "[FileVersion]\nVersion=7.0\n[Compiler]\nA=8\nB=0\nC=1\nD=1\nE=0\nF=0\nG=1\nH=1\nI=1\nJ=0\nK=0\nL=1\nM=0\nN=1\nO=1\nP=1\nQ=0\nR=0\nS=0\nT=0\nU=0\nV=1\nW=0\nX=1\nY=1\nZ=1\nShowHints=1\nShowWarnings=1\nUnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;\nNamespacePrefix=\nSymbolDeprecated=1\nSymbolLibrary=1\nSymbolPlatform=1\nUnitLibrary=1\nUnitPlatform=1\nUnitDeprecated=1\nHResultCompat=1\nHidingMember=1\nHiddenVirtual=1\nGarbage=1\nBoundsError=1\nZeroNilCompat=1\nStringConstTruncated=1\nForLoopVarVarPar=1\nTypedConstVarPar=1\nAsgToTypedConst=1\nCaseLabelRange=1\nForVariable=1\nConstructingAbstract=1\nComparisonFalse=1\nComparisonTrue=1\nComparingSignedUnsigned=1\nCombiningSignedUnsigned=1\nUnsupportedConstruct=1\nFileOpen=1\nFileOpenUnitSrc=1\nBadGlobalSymbol=1\nDuplicateConstructorDestructor=1\nInvalidDirective=1\nPackageNoLink=1\nPackageThreadVar=1\nImplicitImport=1\nHPPEMITIgnored=1\nNoRetVal=1\nUseBeforeDef=1\nForLoopVarUndef=1\nUnitNameMismatch=1\nNoCFGFileFound=1\nMessageDirective=1\nImplicitVariants=1\nUnicodeToLocale=1\nLocaleToUnicode=1\nImagebaseMultiple=1\nSuspiciousTypecast=1\nPrivatePropAccessor=1\nUnsafeType=0\nUnsafeCode=0\nUnsafeCast=0\n[Linker]\nMapFile=0\nOutputObjs=0\nConsoleApp=1\nDebugInfo=0\nRemoteSymbols=0\nMinStackSize=16384\nMaxStackSize=1048576\nImageBase=4194304\nExeDescription=\n[Directories]\nOutputDir=..\\..\\bin\\Win32\\Debug\nUnitOutputDir=..\\..\\lib\\Win32\\Debug\nPackageDLLOutputDir=\nPackageDCPOutputDir=\nSearchPath=..\\..\\src;..\\..\\samples\\HostSample\nPackages=vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP\nConditionals=\nDebugSourceDirs=\nUsePackages=0\n[Parameters]\nRunParams=\nHostApplication=\nLauncher=\nUseLauncher=0\nDebugCWD=\n[Language]\nActiveLang=\nProjectLang=\nRootDir=\n[Version Info]\nIncludeVerInfo=1\nAutoIncBuild=0\nMajorVer=1\nMinorVer=0\nRelease=0\nBuild=0\nDebug=0\nPreRelease=0\nSpecial=0\nPrivate=0\nDLL=0\nLocale=1033\nCodePage=1252\n[Version Info Keys]\nCompanyName=\nFileDescription=\nFileVersion=1.0.0.0\nInternalName=NodeSample\nLegalCopyright=© 2021 Ondrej Kelle\nLegalTrademarks=\nOriginalFilename=NodeSample.exe\nProductName=chakracore-delphi\nProductVersion=1.0.0.0\nComments=\n[HistoryLists\\hlUnitAliases]\nCount=1\nItem0=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;\n[HistoryLists\\hlSearchPath]\nCount=1\nItem0=..\\..\\src;..\\..\\samples\\HostSample\n[HistoryLists\\hlUnitOutputDirectory]\nCount=1\nItem0=..\\..\\lib\\Win32\\Debug\n[HistoryLists\\hlOutputDirectorry]\nCount=1\nItem0=..\\..\\bin\\Win32\\Debug\n"
  },
  {
    "path": "samples/NodeSample/NodeSample.dpr",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nprogram NodeSample;\n\n{$APPTYPE CONSOLE}\n\n{$include common.inc}\n\nuses\n{$ifdef FPC}{$ifdef UNIX}\n  cthreads,\n{$endif}{$endif}\n  SysUtils,\n  Compat,\n  ChakraCoreVersion, ChakraCoreUtils,\n  NodeMainData in 'NodeMainData.pas'  {DataModuleMain: TDataModule};\n\n{$R *.res}\n\nprocedure ShowInfo;\nbegin\n  Writeln(Format('%s %s', [ExtractFileName(ParamStr(0)), GetExeFileVersionString]));\n  Writeln(Format('Built with %s', [GetBuildInfoString]));\n  Writeln(Format('Chakra Core version: %d.%d.%d', [CHAKRA_CORE_MAJOR_VERSION, CHAKRA_CORE_MINOR_VERSION, CHAKRA_CORE_PATCH_VERSION]));\n  Writeln;\nend;\n\nprocedure Main;\nvar\n  DataModule: TDataModuleMain;\nbegin\n  ShowInfo;\n  if ParamCount <> 1 then\n    raise Exception.CreateFmt('Usage: %s <filename>', [ExtractFileName(ParamStr(0))]);\n\n  DataModule := TDataModuleMain.Create(nil);\n  try\n    DataModule.Execute(UnicodeString(ParamStr(1)));\n  finally\n    DataModule.Free;\n  end;\nend;\n\nbegin\n{$ifdef DELPHI2006_UP}\n  ReportMemoryLeaksOnShutdown := True;\n{$endif}\n  try\n    Main;\n  except\n    on E: EChakraCoreScript do\n    begin\n      ExitCode := 1;\n      Writeln(Format('%s (%d, %d): [%s] ''%s''' + sLineBreak + '%s', [E.ScriptURL, E.Line + 1, E.Column + 1,\n        E.ClassName, E.Source, E.Message]));\n    end;\n    on E: Exception do\n    begin\n      ExitCode := 1;\n      Writeln(Format('[%s] %s', [E.ClassName, E.Message]));\n    end;\n  end;\nend."
  },
  {
    "path": "samples/NodeSample/NodeSample.lpi",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CONFIG>\n  <ProjectOptions>\n    <Version Value=\"11\"/>\n    <General>\n      <Flags>\n        <MainUnitHasCreateFormStatements Value=\"False\"/>\n        <MainUnitHasScaledStatement Value=\"False\"/>\n      </Flags>\n      <SessionStorage Value=\"InProjectDir\"/>\n      <MainUnit Value=\"0\"/>\n      <UseAppBundle Value=\"False\"/>\n      <ResourceType Value=\"res\"/>\n    </General>\n    <VersionInfo>\n      <UseVersionInfo Value=\"True\"/>\n      <MajorVersionNr Value=\"1\"/>\n      <StringTable InternalName=\"NodeSample\" LegalCopyright=\"© 2021 Ondrej Kelle\" OriginalFilename=\"NodeSample\"/>\n    </VersionInfo>\n    <BuildModes Count=\"2\">\n      <Item1 Name=\"Debug\" Default=\"True\"/>\n      <Item2 Name=\"Release\">\n        <CompilerOptions>\n          <Version Value=\"11\"/>\n          <Target>\n            <Filename Value=\"NodeSample\"/>\n          </Target>\n          <SearchPaths>\n            <UnitOutputDirectory Value=\"lib/$(TargetCPU)-$(TargetOS)\"/>\n          </SearchPaths>\n          <CodeGeneration>\n            <SmartLinkUnit Value=\"True\"/>\n            <Optimizations>\n              <OptimizationLevel Value=\"3\"/>\n            </Optimizations>\n          </CodeGeneration>\n          <Linking>\n            <Debugging>\n              <GenerateDebugInfo Value=\"False\"/>\n            </Debugging>\n            <LinkSmart Value=\"True\"/>\n          </Linking>\n        </CompilerOptions>\n      </Item2>\n    </BuildModes>\n    <PublishOptions>\n      <Version Value=\"2\"/>\n    </PublishOptions>\n    <RunParams>\n      <local>\n        <CommandLineParams Value=\"../../../samples/NodeSample/demo_commonmark.js\"/>\n      </local>\n      <FormatVersion Value=\"2\"/>\n      <Modes Count=\"1\">\n        <Mode0 Name=\"Debug\">\n          <local>\n            <CommandLineParams Value=\"../../../samples/NodeSample/demo_commonmark.js\"/>\n          </local>\n        </Mode0>\n      </Modes>\n    </RunParams>\n    <Units Count=\"2\">\n      <Unit0>\n        <Filename Value=\"NodeSample.dpr\"/>\n        <IsPartOfProject Value=\"True\"/>\n      </Unit0>\n      <Unit1>\n        <Filename Value=\"NodeMainData.pas\"/>\n        <IsPartOfProject Value=\"True\"/>\n        <ComponentName Value=\"DataModuleMain\"/>\n        <HasResources Value=\"True\"/>\n        <ResourceBaseClass Value=\"DataModule\"/>\n      </Unit1>\n    </Units>\n  </ProjectOptions>\n  <CompilerOptions>\n    <Version Value=\"11\"/>\n    <Target>\n      <Filename Value=\"../../bin/$(TargetCPU)-$(TargetOS)/$(BuildMode)/NodeSample\"/>\n    </Target>\n    <SearchPaths>\n      <IncludeFiles Value=\"$(ProjOutDir);../../src\"/>\n      <OtherUnitFiles Value=\"../../src;../../samples/HostSample\"/>\n      <UnitOutputDirectory Value=\"../../lib/$(TargetCPU)-$(TargetOS)/$(BuildMode)\"/>\n    </SearchPaths>\n    <Parsing>\n      <SyntaxOptions>\n        <IncludeAssertionCode Value=\"True\"/>\n      </SyntaxOptions>\n    </Parsing>\n    <CodeGeneration>\n      <Checks>\n        <IOChecks Value=\"True\"/>\n        <RangeChecks Value=\"True\"/>\n        <OverflowChecks Value=\"True\"/>\n        <StackChecks Value=\"True\"/>\n      </Checks>\n    </CodeGeneration>\n    <Linking>\n      <Debugging>\n        <UseHeaptrc Value=\"True\"/>\n        <TrashVariables Value=\"True\"/>\n        <UseExternalDbgSyms Value=\"True\"/>\n      </Debugging>\n    </Linking>\n  </CompilerOptions>\n  <Debugging>\n    <Exceptions Count=\"2\">\n      <Item1>\n        <Name Value=\"EAbort\"/>\n      </Item1>\n      <Item2>\n        <Name Value=\"ECodetoolError\"/>\n      </Item2>\n    </Exceptions>\n  </Debugging>\n</CONFIG>\n"
  },
  {
    "path": "samples/NodeSample/README.md",
    "content": "Limited support for [Node](https://nodejs.org/en/) [modules](https://nodejs.org/api/modules.html).\n\nBlog post: [Node modules with Delphi and Free Pascal](https://tondrej.blogspot.com/2019/01/node-modules-with-delphi-and-free-pascal.html)\n"
  },
  {
    "path": "samples/NodeSample/demo_commonmark.js",
    "content": "console.log('***** commonmark demo *****');\n\nvar commonmark = require('commonmark');\n\nvar reader = new commonmark.Parser();\nvar writer = new commonmark.HtmlRenderer();\nvar md = 'Hello, *world*!\\n\\nfrom [chakracore-delphi](https://github.com/tondrej/chakracore-delphi)';\nvar parsed = reader.parse(md); // parsed is a 'Node' tree\n// transform parsed if you like...\nvar result = writer.render(parsed); // result is a String\nconsole.log('md: ', JSON.stringify(md));\nconsole.log('result: ', JSON.stringify(result));\n"
  },
  {
    "path": "samples/NodeSample/demo_graphql.js",
    "content": "console.log('***** graphql demo *****');\n\nvar graphql = require('graphql');\n\nvar schema = new graphql.GraphQLSchema({\n  query: new graphql.GraphQLObjectType({\n    name: 'RootQueryType',\n    fields: {\n      hello: {\n        type: graphql.GraphQLString,\n        resolve() {\n          return 'world';\n        }\n      }\n    }\n  })\n});\n\nfunction run(query) {\n  graphql.graphql(schema, query).then(result => {\n    console.log('schema: ', JSON.stringify(schema));\n    console.log('query: ', JSON.stringify(query));\n    console.info('result: ', JSON.stringify(result));\n\tconsole.log();\n  }).catch(e => {\n    console.log('schema: ', JSON.stringify(schema));\n    console.log('query: ', JSON.stringify(query));\n    console.error('error: ', JSON.stringify(e));\n\tconsole.log();\n  });\n};\n\nrun('{ hello }');\nrun('{ boyhowdy }'); // schema error\n"
  },
  {
    "path": "samples/NodeSample/demo_json-query.js",
    "content": "console.log('***** json-query *****');\n\nvar jsonQuery = require('json-query');\n\nvar data = {\n  people: [\n    {name: 'Matt', country: 'NZ'},\n    {name: 'Pete', country: 'AU'},\n    {name: 'Mikey', country: 'NZ'}\n  ]\n};\nvar query = 'people[*country=NZ].name';\n\nconsole.log('data: ', JSON.stringify(data));\nconsole.log('query: ', JSON.stringify(query));\nconsole.log('result: ', JSON.stringify(jsonQuery(query, { data: data })));\n"
  },
  {
    "path": "samples/NodeSample/demo_lodash.js",
    "content": "console.log('***** lodash demo *****');\n\nvar lodash = require('lodash');\n\nvar users = [\n  { 'user': 'fred',   'age': 48 },\n  { 'user': 'barney', 'age': 36 },\n  { 'user': 'fred',   'age': 40 },\n  { 'user': 'barney', 'age': 34 }\n];\n \nconsole.log('users: ', JSON.stringify(users));\nconsole.log('by user: ', JSON.stringify(_.sortBy(users, ['user'])));\nconsole.log('by age: ', JSON.stringify(_.sortBy(users, ['age'])));\n"
  },
  {
    "path": "samples/NodeSample/demo_moment.js",
    "content": "console.log('***** moment demo *****');\n\nvar moment = require('moment');\n\nvar now = moment();\nvar fmt = 'dddd MMMM Do YYYY, h:mm:ss a';\nconsole.log(JSON.stringify(now.format(fmt)), JSON.stringify(now.utc().format(fmt)), 'UTC');\n"
  },
  {
    "path": "samples/Samples.XE.groupproj",
    "content": "﻿\t<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\t\t<PropertyGroup>\n\t\t\t<ProjectGuid>{AB33209C-912B-47E0-91BB-2B9A9F0D3456}</ProjectGuid>\n\t\t</PropertyGroup>\n\t\t<ItemGroup>\n\t\t\t<Projects Include=\"..\\tests\\ChakraCoreTests.XE.dproj\">\n\t\t\t\t<Dependencies/>\n\t\t\t</Projects>\n\t\t\t<Projects Include=\"..\\tests\\ChakraCoreTestsUI.XE.dproj\">\n\t\t\t\t<Dependencies/>\n\t\t\t</Projects>\n\t\t\t<Projects Include=\"SimpleHostSample\\SimpleHost.XE.dproj\">\n\t\t\t\t<Dependencies/>\n\t\t\t</Projects>\n\t\t\t<Projects Include=\"HostSample\\ChakraCoreHostSample.XE.dproj\">\n\t\t\t\t<Dependencies/>\n\t\t\t</Projects>\n\t\t\t<Projects Include=\"WasmSample\\WasmSample.XE.dproj\">\n\t\t\t\t<Dependencies/>\n\t\t\t</Projects>\n\t\t\t<Projects Include=\"NodeSample\\NodeSample.XE.dproj\">\n\t\t\t\t<Dependencies/>\n\t\t\t</Projects>\n\t\t</ItemGroup>\n\t\t<ProjectExtensions>\n\t\t\t<Borland.Personality>Default.Personality.12</Borland.Personality>\n\t\t\t<Borland.ProjectType/>\n\t\t\t<BorlandProject>\n\t\t\t\t<Default.Personality/>\n\t\t\t</BorlandProject>\n\t\t</ProjectExtensions>\n\t\t<Target Name=\"ChakraCoreTests_XE\">\n\t\t\t<MSBuild Projects=\"..\\tests\\ChakraCoreTests.XE.dproj\"/>\n\t\t</Target>\n\t\t<Target Name=\"ChakraCoreTests_XE:Clean\">\n\t\t\t<MSBuild Projects=\"..\\tests\\ChakraCoreTests.XE.dproj\" Targets=\"Clean\"/>\n\t\t</Target>\n\t\t<Target Name=\"ChakraCoreTests_XE:Make\">\n\t\t\t<MSBuild Projects=\"..\\tests\\ChakraCoreTests.XE.dproj\" Targets=\"Make\"/>\n\t\t</Target>\n\t\t<Target Name=\"ChakraCoreTestsUI_XE\">\n\t\t\t<MSBuild Projects=\"..\\tests\\ChakraCoreTestsUI.XE.dproj\"/>\n\t\t</Target>\n\t\t<Target Name=\"ChakraCoreTestsUI_XE:Clean\">\n\t\t\t<MSBuild Projects=\"..\\tests\\ChakraCoreTestsUI.XE.dproj\" Targets=\"Clean\"/>\n\t\t</Target>\n\t\t<Target Name=\"ChakraCoreTestsUI_XE:Make\">\n\t\t\t<MSBuild Projects=\"..\\tests\\ChakraCoreTestsUI.XE.dproj\" Targets=\"Make\"/>\n\t\t</Target>\n\t\t<Target Name=\"SimpleHost_XE\">\n\t\t\t<MSBuild Projects=\"SimpleHostSample\\SimpleHost.XE.dproj\"/>\n\t\t</Target>\n\t\t<Target Name=\"SimpleHost_XE:Clean\">\n\t\t\t<MSBuild Projects=\"SimpleHostSample\\SimpleHost.XE.dproj\" Targets=\"Clean\"/>\n\t\t</Target>\n\t\t<Target Name=\"SimpleHost_XE:Make\">\n\t\t\t<MSBuild Projects=\"SimpleHostSample\\SimpleHost.XE.dproj\" Targets=\"Make\"/>\n\t\t</Target>\n\t\t<Target Name=\"ChakraCoreHostSample_XE\">\n\t\t\t<MSBuild Projects=\"HostSample\\ChakraCoreHostSample.XE.dproj\"/>\n\t\t</Target>\n\t\t<Target Name=\"ChakraCoreHostSample_XE:Clean\">\n\t\t\t<MSBuild Projects=\"HostSample\\ChakraCoreHostSample.XE.dproj\" Targets=\"Clean\"/>\n\t\t</Target>\n\t\t<Target Name=\"ChakraCoreHostSample_XE:Make\">\n\t\t\t<MSBuild Projects=\"HostSample\\ChakraCoreHostSample.XE.dproj\" Targets=\"Make\"/>\n\t\t</Target>\n\t\t<Target Name=\"WasmSample_XE\">\n\t\t\t<MSBuild Projects=\"WasmSample\\WasmSample.XE.dproj\"/>\n\t\t</Target>\n\t\t<Target Name=\"WasmSample_XE:Clean\">\n\t\t\t<MSBuild Projects=\"WasmSample\\WasmSample.XE.dproj\" Targets=\"Clean\"/>\n\t\t</Target>\n\t\t<Target Name=\"WasmSample_XE:Make\">\n\t\t\t<MSBuild Projects=\"WasmSample\\WasmSample.XE.dproj\" Targets=\"Make\"/>\n\t\t</Target>\n\t\t<Target Name=\"NodeSample_XE\">\n\t\t\t<MSBuild Projects=\"NodeSample\\NodeSample.XE.dproj\"/>\n\t\t</Target>\n\t\t<Target Name=\"NodeSample_XE:Clean\">\n\t\t\t<MSBuild Projects=\"NodeSample\\NodeSample.XE.dproj\" Targets=\"Clean\"/>\n\t\t</Target>\n\t\t<Target Name=\"NodeSample_XE:Make\">\n\t\t\t<MSBuild Projects=\"NodeSample\\NodeSample.XE.dproj\" Targets=\"Make\"/>\n\t\t</Target>\n\t\t<Target Name=\"Build\">\n\t\t\t<CallTarget Targets=\"ChakraCoreTests_XE;ChakraCoreTestsUI_XE;SimpleHost_XE;ChakraCoreHostSample_XE;WasmSample_XE;NodeSample_XE\"/>\n\t\t</Target>\n\t\t<Target Name=\"Clean\">\n\t\t\t<CallTarget Targets=\"ChakraCoreTests_XE:Clean;ChakraCoreTestsUI_XE:Clean;SimpleHost_XE:Clean;ChakraCoreHostSample_XE:Clean;WasmSample_XE:Clean;NodeSample_XE:Clean\"/>\n\t\t</Target>\n\t\t<Target Name=\"Make\">\n\t\t\t<CallTarget Targets=\"ChakraCoreTests_XE:Make;ChakraCoreTestsUI_XE:Make;SimpleHost_XE:Make;ChakraCoreHostSample_XE:Make;WasmSample_XE:Make;NodeSample_XE:Make\"/>\n\t\t</Target>\n\t\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Group.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Group.Targets\"/>\n\t</Project>\n"
  },
  {
    "path": "samples/Samples.bpg",
    "content": "#------------------------------------------------------------------------------\nVERSION = BWS.01\n#------------------------------------------------------------------------------\n!ifndef ROOT\nROOT = $(MAKEDIR)\\..\n!endif\n#------------------------------------------------------------------------------\nMAKE = $(ROOT)\\bin\\make.exe -$(MAKEFLAGS) -f$**\nDCC = $(ROOT)\\bin\\dcc32.exe $**\nBRCC = $(ROOT)\\bin\\brcc32.exe $**\n#------------------------------------------------------------------------------\nPROJECTS = ChakraCoreTests.exe ChakraCoreTestsUI.exe SimpleHost.exe ChakraCoreHostSample.exe \\\n  WasmSample.exe NodeSample.exe\n#------------------------------------------------------------------------------\ndefault: $(PROJECTS)\n#------------------------------------------------------------------------------\n\nChakraCoreTests.exe: ..\\tests\\ChakraCoreTests.dpr\n  $(DCC)\n\nChakraCoreTestsUI.exe: ..\\tests\\ChakraCoreTestsUI.dpr\n  $(DCC)\n\nChakraCoreHostSample.exe: HostSample\\ChakraCoreHostSample.dpr\n  $(DCC)\n\nSimpleHost.exe: SimpleHostSample\\SimpleHost.dpr\n  $(DCC)\n\nWasmSample.exe: WasmSample\\WasmSample.dpr\n  $(DCC)\n\nNodeSample.exe: NodeSample\\NodeSample.dpr\n  $(DCC)\n\n"
  },
  {
    "path": "samples/Samples.lpg",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CONFIG>\n  <ProjectGroup FileVersion=\"1\">\n    <Targets Count=\"6\">\n      <Target0 FileName=\"..\\tests\\ChakraCoreTests.lpi\">\n        <BuildModes Count=\"2\"/>\n        <Mode1 Name=\"Debug\" Compile=\"True\"/>\n        <Mode2 Name=\"Release\"/>\n      </Target0>\n      <Target1 FileName=\"..\\tests\\ChakraCoreTestsUI.lpi\">\n        <BuildModes Count=\"2\"/>\n        <Mode1 Name=\"Debug\" Compile=\"True\"/>\n        <Mode2 Name=\"Release\"/>\n      </Target1>\n      <Target2 FileName=\"SimpleHostSample\\SimpleHost.lpi\">\n        <BuildModes Count=\"2\"/>\n        <Mode1 Name=\"Debug\" Compile=\"True\"/>\n        <Mode2 Name=\"Release\"/>\n      </Target2>\n      <Target3 FileName=\"HostSample\\ChakraCoreHostSample.lpi\">\n        <BuildModes Count=\"2\"/>\n        <Mode1 Name=\"Debug\" Compile=\"True\"/>\n        <Mode2 Name=\"Release\"/>\n      </Target3>\n      <Target4 FileName=\"WasmSample\\WasmSample.lpi\">\n        <BuildModes Count=\"2\"/>\n        <Mode1 Name=\"Debug\" Compile=\"True\"/>\n        <Mode2 Name=\"Release\"/>\n      </Target4>\n      <Target5 FileName=\"NodeSample\\NodeSample.lpi\">\n        <BuildModes Count=\"2\"/>\n        <Mode1 Name=\"Debug\" Compile=\"True\"/>\n        <Mode2 Name=\"Release\"/>\n      </Target5>\n    </Targets>\n  </ProjectGroup>\n</CONFIG>\n"
  },
  {
    "path": "samples/SimpleHostSample/SimpleHost.XE.dproj",
    "content": "﻿\t<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\t\t<PropertyGroup>\n\t\t\t<ProjectGuid>{01f91de3-a053-4032-ac0c-ba8b9af05f13}</ProjectGuid>\n\t\t\t<MainSource>SimpleHost.dpr</MainSource>\n\t\t\t<Config Condition=\"'$(Config)'==''\">Debug</Config>\n\t\t\t<DCC_DCCCompiler>DCC32</DCC_DCCCompiler>\n\t\t\t<ProjectVersion>12.3</ProjectVersion>\n\t\t\t<Base>True</Base>\n\t\t\t<Platform>Win32</Platform>\n\t\t\t<AppType>Console</AppType>\n\t\t\t<FrameworkType>None</FrameworkType>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Base' or '$(Base)'!=''\">\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Release' or '$(Cfg_1)'!=''\">\n\t\t\t<Cfg_1>true</Cfg_1>\n\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Debug' or '$(Cfg_2)'!=''\">\n\t\t\t<Cfg_2>true</Cfg_2>\n\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Base)'!=''\">\n\t\t\t<DCC_DependencyCheckOutputName>..\\..\\bin\\$(Platform)\\$(Config)\\SimpleHost.exe</DCC_DependencyCheckOutputName>\n\t\t\t<DCC_ExeOutput>..\\..\\bin\\$(Platform)\\$(Config)</DCC_ExeOutput>\n\t\t\t<DCC_DcuOutput>..\\..\\lib\\$(Platform)\\$(Config)</DCC_DcuOutput>\n\t\t\t<DCC_ImageBase>00400000</DCC_ImageBase>\n\t\t\t<DCC_UsePackage>vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP;JclDeveloperTools;Jcl;JclVcl;JclContainers</DCC_UsePackage>\n\t\t\t<DCC_UnitAlias>WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;$(DCC_UnitAlias)</DCC_UnitAlias>\n\t\t\t<DCC_Platform>x86</DCC_Platform>\n\t\t\t<DCC_UnitSearchPath>..\\..\\src;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>\n\t\t\t<DCC_K>false</DCC_K>\n\t\t\t<DCC_N>true</DCC_N>\n\t\t\t<DCC_S>false</DCC_S>\n\t\t\t<DCC_SymbolReferenceInfo>1</DCC_SymbolReferenceInfo>\n\t\t\t<DCC_E>false</DCC_E>\n\t\t\t<DCC_F>false</DCC_F>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Cfg_1)'!=''\">\n\t\t\t<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>\n\t\t\t<DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>\n\t\t\t<DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>\n\t\t\t<DCC_DebugInformation>false</DCC_DebugInformation>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Cfg_2)'!=''\">\n\t\t\t<DCC_Define>DEBUG;$(DCC_Define)</DCC_Define>\n\t\t</PropertyGroup>\n\t\t<ItemGroup>\n\t\t\t<DelphiCompile Include=\"SimpleHost.dpr\">\n\t\t\t\t<MainSource>MainSource</MainSource>\n\t\t\t</DelphiCompile>\n\t\t\t<BuildConfiguration Include=\"Debug\">\n\t\t\t\t<Key>Cfg_2</Key>\n\t\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t</BuildConfiguration>\n\t\t\t<BuildConfiguration Include=\"Base\">\n\t\t\t\t<Key>Base</Key>\n\t\t\t</BuildConfiguration>\n\t\t\t<BuildConfiguration Include=\"Release\">\n\t\t\t\t<Key>Cfg_1</Key>\n\t\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t</BuildConfiguration>\n\t\t</ItemGroup>\n\t\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Delphi.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Delphi.Targets\"/>\n\t\t<Import Condition=\"Exists('$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj')\" Project=\"$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj\"/>\n\t\t<ProjectExtensions>\n\t\t\t<Borland.Personality>Delphi.Personality.12</Borland.Personality>\n\t\t\t<Borland.ProjectType>VCLApplication</Borland.ProjectType>\n\t\t\t<BorlandProject>\n\t\t\t\t<Delphi.Personality>\n\t\t\t\t\t<Source>\n\t\t\t\t\t\t<Source Name=\"MainSource\">SimpleHost.dpr</Source>\n\t\t\t\t\t</Source>\n\t\t\t\t\t<Parameters>\n\t\t\t\t\t\t<Parameters Name=\"RunParams\">..\\..\\..\\samples\\SimpleHostSample\\scripts\\hello.js</Parameters>\n\t\t\t\t\t</Parameters>\n\t\t\t\t\t<VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"IncludeVerInfo\">True</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"AutoIncBuild\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"MajorVer\">1</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"MinorVer\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Release\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Build\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Debug\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"PreRelease\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Special\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Private\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"DLL\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Locale\">1033</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"CodePage\">1252</VersionInfo>\n\t\t\t\t\t</VersionInfo>\n\t\t\t\t\t<VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"CompanyName\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"FileDescription\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"FileVersion\">1.0.0.0</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"InternalName\">SimpleHost</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"LegalCopyright\">© 2021 Ondrej Kelle</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"LegalTrademarks\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"OriginalFilename\">SimpleHost.exe</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"ProductName\">chakracore-delphi</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"ProductVersion\">1.0.0.0</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"Comments\"/>\n\t\t\t\t\t</VersionInfoKeys>\n\t\t\t\t</Delphi.Personality>\n\t\t\t\t<Platforms>\n\t\t\t\t\t<Platform value=\"Win32\">True</Platform>\n\t\t\t\t</Platforms>\n\t\t\t</BorlandProject>\n\t\t\t<ProjectFileVersion>12</ProjectFileVersion>\n\t\t</ProjectExtensions>\n\t</Project>\n"
  },
  {
    "path": "samples/SimpleHostSample/SimpleHost.dof",
    "content": "[FileVersion]\nVersion=7.0\n[Compiler]\nA=8\nB=0\nC=1\nD=1\nE=0\nF=0\nG=1\nH=1\nI=1\nJ=0\nK=0\nL=1\nM=0\nN=1\nO=1\nP=1\nQ=0\nR=0\nS=0\nT=0\nU=0\nV=1\nW=0\nX=1\nY=1\nZ=1\nShowHints=1\nShowWarnings=1\nUnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;\nNamespacePrefix=\nSymbolDeprecated=1\nSymbolLibrary=1\nSymbolPlatform=1\nUnitLibrary=1\nUnitPlatform=1\nUnitDeprecated=1\nHResultCompat=1\nHidingMember=1\nHiddenVirtual=1\nGarbage=1\nBoundsError=1\nZeroNilCompat=1\nStringConstTruncated=1\nForLoopVarVarPar=1\nTypedConstVarPar=1\nAsgToTypedConst=1\nCaseLabelRange=1\nForVariable=1\nConstructingAbstract=1\nComparisonFalse=1\nComparisonTrue=1\nComparingSignedUnsigned=1\nCombiningSignedUnsigned=1\nUnsupportedConstruct=1\nFileOpen=1\nFileOpenUnitSrc=1\nBadGlobalSymbol=1\nDuplicateConstructorDestructor=1\nInvalidDirective=1\nPackageNoLink=1\nPackageThreadVar=1\nImplicitImport=1\nHPPEMITIgnored=1\nNoRetVal=1\nUseBeforeDef=1\nForLoopVarUndef=1\nUnitNameMismatch=1\nNoCFGFileFound=1\nMessageDirective=1\nImplicitVariants=1\nUnicodeToLocale=1\nLocaleToUnicode=1\nImagebaseMultiple=1\nSuspiciousTypecast=1\nPrivatePropAccessor=1\nUnsafeType=0\nUnsafeCode=0\nUnsafeCast=0\n[Linker]\nMapFile=0\nOutputObjs=0\nConsoleApp=1\nDebugInfo=0\nRemoteSymbols=0\nMinStackSize=16384\nMaxStackSize=1048576\nImageBase=4194304\nExeDescription=\n[Directories]\nOutputDir=..\\..\\bin\\Win32\\Debug\nUnitOutputDir=..\\..\\lib\\Win32\\Debug\nPackageDLLOutputDir=\nPackageDCPOutputDir=\nSearchPath=..\\..\\src\nPackages=vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP;JclDeveloperTools;Jcl;JclVcl;JclContainers;GR32_DSGN_D7;GR32_D7\nConditionals=\nDebugSourceDirs=\nUsePackages=0\n[Parameters]\nRunParams=..\\..\\..\\samples\\SimpleHostSample\\scripts\\hello.js\nHostApplication=\nLauncher=\nUseLauncher=0\nDebugCWD=\n[Language]\nActiveLang=\nProjectLang=\nRootDir=\n[Version Info]\nIncludeVerInfo=1\nAutoIncBuild=0\nMajorVer=1\nMinorVer=0\nRelease=0\nBuild=0\nDebug=0\nPreRelease=0\nSpecial=0\nPrivate=0\nDLL=0\nLocale=1031\nCodePage=1252\n[Version Info Keys]\nCompanyName=\nFileDescription=\nFileVersion=1.0.0.0\nInternalName=SimpleHost\nLegalCopyright=© 2021 Ondrej Kelle\nLegalTrademarks=\nOriginalFilename=SimpleHost.exe\nProductName=chakracore-delphi\nProductVersion=1.0.0.0\nComments=\n[HistoryLists\\hlUnitAliases]\nCount=1\nItem0=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;\n[HistoryLists\\hlSearchPath]\nCount=1\nItem0=..\\..\\src\n[HistoryLists\\hlUnitOutputDirectory]\nCount=1\nItem0=..\\..\\lib\\Win32\\Debug\n[HistoryLists\\hlOutputDirectorry]\nCount=1\nItem0=..\\..\\bin\\Win32\\Debug\n"
  },
  {
    "path": "samples/SimpleHostSample/SimpleHost.dpr",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nprogram SimpleHost;\n\n{$APPTYPE CONSOLE}\n\n{$include common.inc}\n\nuses\n  {$ifdef FPC}{$ifdef UNIX}\n  cthreads,\n  {$endif}{$endif}\n  SysUtils, Classes,\n  Compat,\n  ChakraCoreVersion, ChakraCommon, ChakraCoreUtils, ChakraCoreClasses;\n\n{$R *.res}\n\nfunction Console_Log(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRefArray; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := JsUndefinedValue;\n  try\n    if not Assigned(Args) or (ArgCount < 2) then\n      Exit;\n\n    Writeln(JsStringToUTF8String(Args^[1]));\n  except on E: Exception do\n    JsThrowError(WideFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction LoadFile(const FileName: UnicodeString): UnicodeString;\nvar\n  FileStream: TFileStream;\n  S: UTF8String;\nbegin\n  Result := '';\n\n  FileStream := TFileStream.Create(FileName, fmOpenRead);\n  try\n    if FileStream.Size = 0 then\n      Exit;\n\n    SetLength(S, FileStream.Size);\n    FileStream.Read(S[1], FileStream.Size);\n\n    Result := UTF8ToString(S);\n  finally\n    FileStream.Free;\n  end;\nend;\n\nprocedure Main;\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\n  Console: JsValueRef;\nbegin\n  if ParamCount = 0 then\n    Exit;\n\n  Runtime := nil;\n  Context := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n\n    Console := JsCreateObject;\n    JsSetCallback(Console, 'log', @Console_Log, nil);\n    JsSetProperty(Context.Global, 'console', Console);\n\n{$ifdef UNICODE}\n    Context.RunScript(LoadFile(ParamStr(1)), ExtractFileName(Paramstr(1)));\n{$else}\n    Context.RunScript(LoadFile(UTF8Decode(ParamStr(1))), ExtractFileName(UTF8Decode(Paramstr(1))));\n{$endif}\n  finally\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\nbegin\n{$ifdef DELPHI2006_UP}\n  ReportMemoryLeaksOnShutdown := True;\n{$endif}\n  try\n    Main;\n  except\n    on E: EChakraCoreScript do\n    begin\n      ExitCode := 1;\n      Writeln(Format('%s (%d, %d): [%s] %s', [E.ScriptURL, E.Line + 1, E.Column + 1, E.ClassName, E.Message]));\n    end;\n    on E: Exception do\n    begin\n      ExitCode := 1;\n      Writeln(Format('[%s] %s', [E.ClassName, E.Message]));\n    end;\n  end;\nend.\n"
  },
  {
    "path": "samples/SimpleHostSample/SimpleHost.lpi",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CONFIG>\n  <ProjectOptions>\n    <Version Value=\"10\"/>\n    <General>\n      <Flags>\n        <MainUnitHasCreateFormStatements Value=\"False\"/>\n        <MainUnitHasScaledStatement Value=\"False\"/>\n      </Flags>\n      <SessionStorage Value=\"InProjectDir\"/>\n      <MainUnit Value=\"0\"/>\n      <UseAppBundle Value=\"False\"/>\n      <ResourceType Value=\"res\"/>\n    </General>\n    <VersionInfo>\n      <UseVersionInfo Value=\"True\"/>\n      <MajorVersionNr Value=\"1\"/>\n      <StringTable InternalName=\"SimpleHost\" LegalCopyright=\"© 2021 Ondrej Kelle\" OriginalFilename=\"SimpleHost\"/>\n    </VersionInfo>\n    <BuildModes Count=\"2\">\n      <Item1 Name=\"Debug\" Default=\"True\"/>\n      <Item2 Name=\"Release\">\n        <CompilerOptions>\n          <Version Value=\"11\"/>\n          <Target>\n            <Filename Value=\"SimpleHost\"/>\n          </Target>\n          <SearchPaths>\n            <UnitOutputDirectory Value=\"lib/$(TargetCPU)-$(TargetOS)\"/>\n          </SearchPaths>\n          <CodeGeneration>\n            <SmartLinkUnit Value=\"True\"/>\n            <Optimizations>\n              <OptimizationLevel Value=\"3\"/>\n            </Optimizations>\n          </CodeGeneration>\n          <Linking>\n            <Debugging>\n              <GenerateDebugInfo Value=\"False\"/>\n            </Debugging>\n            <LinkSmart Value=\"True\"/>\n          </Linking>\n        </CompilerOptions>\n      </Item2>\n    </BuildModes>\n    <PublishOptions>\n      <Version Value=\"2\"/>\n    </PublishOptions>\n    <RunParams>\n      <local>\n        <FormatVersion Value=\"1\"/>\n        <CommandLineParams Value=\"../../../samples/SimpleHostSample/scripts/hello.js\"/>\n      </local>\n    </RunParams>\n    <Units Count=\"1\">\n      <Unit0>\n        <Filename Value=\"SimpleHost.dpr\"/>\n        <IsPartOfProject Value=\"True\"/>\n      </Unit0>\n    </Units>\n  </ProjectOptions>\n  <CompilerOptions>\n    <Version Value=\"11\"/>\n    <Target>\n      <Filename Value=\"../../bin/$(TargetCPU)-$(TargetOS)/$(BuildMode)/SimpleHost\"/>\n    </Target>\n    <SearchPaths>\n      <IncludeFiles Value=\"$(ProjOutDir);../../src\"/>\n      <OtherUnitFiles Value=\"../../src\"/>\n      <UnitOutputDirectory Value=\"../../lib/$(TargetCPU)-$(TargetOS)/$(BuildMode)\"/>\n    </SearchPaths>\n    <Parsing>\n      <SyntaxOptions>\n        <IncludeAssertionCode Value=\"True\"/>\n      </SyntaxOptions>\n    </Parsing>\n    <CodeGeneration>\n      <Checks>\n        <IOChecks Value=\"True\"/>\n        <RangeChecks Value=\"True\"/>\n        <OverflowChecks Value=\"True\"/>\n        <StackChecks Value=\"True\"/>\n      </Checks>\n    </CodeGeneration>\n    <Linking>\n      <Debugging>\n        <DebugInfoType Value=\"dsDwarf2Set\"/>\n        <UseHeaptrc Value=\"True\"/>\n        <TrashVariables Value=\"True\"/>\n        <UseExternalDbgSyms Value=\"True\"/>\n      </Debugging>\n    </Linking>\n  </CompilerOptions>\n  <Debugging>\n    <Exceptions Count=\"4\">\n      <Item1>\n        <Name Value=\"EAbort\"/>\n      </Item1>\n      <Item2>\n        <Name Value=\"ECodetoolError\"/>\n      </Item2>\n      <Item3>\n        <Name Value=\"EFOpenError\"/>\n      </Item3>\n      <Item4>\n        <Name Value=\"EChakraCore\"/>\n      </Item4>\n    </Exceptions>\n  </Debugging>\n</CONFIG>\n"
  },
  {
    "path": "samples/SimpleHostSample/scripts/hello.js",
    "content": "console.log(\"Hello, world!\");"
  },
  {
    "path": "samples/WasmSample/README.md",
    "content": "Based on Colin Eberhardt's [Writing WebAssembly By Hand](https://blog.scottlogic.com/2018/04/26/webassembly-by-hand.html)\n([code](https://webassembly.studio/?f=ivzzdwn7fcn))\n\n<a href=\"https://tondrej.blogspot.com/2019/01/webassembly-with-delphi-and-chakracore.html\"><img border=\"0\" src=\"https://3.bp.blogspot.com/-3ulLOnBml-0/XD0EqUMEYiI/AAAAAAAADHs/Vf4CoZQmcl0o6HxwEX7xdKsDPWEda2j9ACLcBGAs/s320/wasmsample.gif\" width=\"227\" height=\"320\" data-original-width=\"448\" data-original-height=\"631\" /></a>\n"
  },
  {
    "path": "samples/WasmSample/WasmMainData.dfm",
    "content": "object DataModuleMain: TDataModuleMain\n  OldCreateOrder = False\n  OnCreate = DataModuleCreate\n  Height = 265\n  Width = 368\n  object OpenDialog: TOpenDialog\n    DefaultExt = '.js'\n    Filter = 'Javascript files (*.js)|*.js|All files (*.*)|*.*'\n    FilterIndex = 0\n    Title = 'Open Javascript file'\n    Left = 24\n    Top = 8\n  end\nend\n"
  },
  {
    "path": "samples/WasmSample/WasmMainData.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nunit WasmMainData;\n\ninterface\n\n{$include common.inc}\n\nuses\n{$ifdef FPC}{$ifdef UNIX}\n  cwstring,\n{$endif}{$endif}\n{$ifdef WINDOWS}\n  Windows,\n{$endif}\n{$ifdef FPC}\n  LCLIntf, LCLType,\n{$endif}\n  SysUtils, Classes, Forms, Graphics, Dialogs,\n{$ifdef HAS_WIDESTRUTILS}\n  WideStrUtils,\n{$endif}\n  Compat, ChakraCommon, ChakraCore, ChakraCoreUtils, ChakraCoreClasses, Console;\n\ntype\n\n  { TDataModuleMain }\n\n  TDataModuleMain = class(TDataModule)\n    OpenDialog: TOpenDialog;\n\n    procedure DataModuleCreate(Sender: TObject);\n  private\n    FCanvas: JsValueRef;\n    FConsole: TConsole;\n    FContext: TChakraCoreContext;\n    FRuntime: TChakraCoreRuntime;\n    FScriptFileName: UnicodeString;\n    FTerminated: Boolean;\n    FThread: TThread;\n    FWasmFileName: UnicodeString;\n\n    procedure ConsoleLog(Sender: TObject; const Text: UnicodeString; Level: TInfoLevel = ilNone);\n    procedure ContextActivate(Sender: TObject);\n    procedure ContextNativeObjectCreated(Sender: TObject; NativeObject: TNativeObject);\n    procedure Finalize;\n    function GetActive: Boolean;\n    procedure Initialize;\n    function LoadWasmModule(const FileName: UnicodeString): JsValueRef;\n    procedure RunScript;\n    procedure SetActive(Value: Boolean);\n  public\n    property Active: Boolean read GetActive write SetActive;\n    property ScriptFileName: UnicodeString read FScriptFileName;\n  end;\n\nvar\n  DataModuleMain: TDataModuleMain;\n\nimplementation\n\n{$R *.dfm}\n\nuses\n  WasmMainForm;\n\ntype\n\n  { TTaskMessageEx }\n\n  TTaskMessageEx = class(TTaskMessage)\n  private\n    FDataModule: TDataModuleMain;\n  protected\n    function Process(out ResultValue: JsValueRef): Boolean; override;\n  end;\n\n  function TTaskMessageEx.Process(out ResultValue: JsValueRef): Boolean;\n  begin\n    Result := FDataModule.FTerminated or inherited Process(ResultValue);\n  end;\n\ntype\n\n  { TWasmThread }\n\n  TWasmThread = class(TThread)\n  private\n    FDataModule: TDataModuleMain;\n  protected\n    procedure Execute; override;\n  public\n    constructor Create(ADataModule: TDataModuleMain);\n    destructor Destroy; override;\n  end;\n\nconstructor TWasmThread.Create(ADataModule: TDataModuleMain);\nbegin\n  FDataModule := ADataModule;\n  FDataModule.FThread := Self;\n  FreeOnTerminate := True;\n  inherited Create(False);\nend;\n\ndestructor TWasmThread.Destroy;\nbegin\n  FDataModule.FThread := nil;\n  inherited Destroy;\nend;\n\nprocedure TWasmThread.Execute;\nbegin\n  FDataModule.Initialize;\n  try\n    FDataModule.RunScript;\n  finally\n    FDataModule.Finalize;\n  end;\nend;\n\nfunction LoadFile(const FileName: UnicodeString): UnicodeString;\nvar\n  FileStream: TFileStream;\n  S: UTF8String;\nbegin\n  Result := '';\n\n  FileStream := TFileStream.Create(FileName, fmOpenRead);\n  try\n    if FileStream.Size = 0 then\n      Exit;\n\n    SetLength(S, FileStream.Size);\n    FileStream.Read(S[1], FileStream.Size);\n\n    Result := UTF8ToString(S);\n  finally\n    FileStream.Free;\n  end;\nend;\n\nfunction PostTimedTask(Args: PJsValueRefArray; ArgCount: Word; CallbackState: Pointer; RepeatCount: Integer): JsValueRef;\nvar\n  DataModule: TDataModuleMain absolute CallbackState;\n  AMessage: TTaskMessageEx;\n  Delay: Cardinal;\n  FuncArgs: array of JsValueRef;\n  I: Integer;\nbegin\n  Result := JsUndefinedValue;\n  if DataModule.FTerminated then\n    Exit;\n\n  if ArgCount < 2 then // thisarg, function to call, optional: delay, function args\n    raise Exception.Create('Invalid arguments');\n\n  if ArgCount >= 3 then\n    Delay := JsNumberToInt(Args^[2])\n  else\n    Delay := 0;\n\n  if ArgCount >= 4 then\n  begin\n    SetLength(FuncArgs, ArgCount - 3);\n    for I := 0 to ArgCount - 4 do\n      FuncArgs[I] := Args^[I + 3];\n  end;\n\n  AMessage := TTaskMessageEx.Create(DataModule.FContext, Args^[1], Args^[0], FuncArgs, Delay, RepeatCount);\n  try\n    AMessage.FDataModule := DataModule;\n    DataModule.FContext.PostMessage(AMessage);\n  except\n    AMessage.Free;\n    raise;\n  end;\nend;\n\nfunction Canvas_FillRect_Callback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRefArray; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := JsUndefinedValue;\n  try\n    FormMain.FillRect(JsNumberToInt(Args^[1]), JsNumberToInt(Args^[2]), JsNumbertoInt(Args^[3]), JsNumberToInt(Args^[4]),\n      JsStringToUnicodeString(JsGetProperty(Args^[0], 'fillStyle')));\n  except on E: Exception do\n    JsThrowError(WideFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction LoadWasm_Callback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRefArray; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nvar\n  DataModule: TDataModuleMain absolute CallbackState;\nbegin\n  Result := JsUndefinedValue;\n  try\n    DataModule.FWasmFileName := ExtractFilePath(DataModule.FScriptFileName) + JsStringToUnicodeString(Args^[1]);\n    Result := DataModule.LoadWasmModule(DataModule.FWasmFileName);\n  except on E: Exception do\n    JsThrowError(WideFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction SetInterval_Callback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRefArray; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := JsUndefinedValue;\n  try\n    Result := PostTimedTask(Args, ArgCount, CallbackState, -1); // repeat endlessly\n  except on E: Exception do\n    JsThrowError(WideFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction SetTimeout_Callback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRefArray; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := JsUndefinedValue;\n  try\n    Result := PostTimedTask(Args, ArgCount, CallbackState, 1); // run once\n  except on E: Exception do\n    JsThrowError(WideFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nprocedure TDataModuleMain.DataModuleCreate(Sender: TObject);\nbegin\n  FScriptFileName := ParamStr(1);\nend;\n\nprocedure TDataModuleMain.ConsoleLog(Sender: TObject; const Text: UnicodeString; Level: TInfoLevel);\nvar\n  P: PUnicodeChar;\n  L: Integer;\nbegin\n  P := nil;\n  try\n    L := Length(Text);\n    P := AllocMem((L + 1) * SizeOf(UnicodeChar));\n    if L > 0 then\n      Move(Text[1], P^, L * SizeOf(UnicodeChar));\n    PostMessage(FormMain.Handle, WM_CONSOLELOG, WPARAM(P), 0);\n  except\n    if Assigned(P) then\n      FreeMem(P);\n    raise;\n  end;\nend;\n\nprocedure TDataModuleMain.ContextActivate(Sender: TObject);\nbegin\n  // expose additional functions\n  JsSetCallback(FContext.Global, 'setTimeout', @SetTimeout_Callback, Self);\n  JsSetCallback(FContext.Global, 'setInterval', @SetInterval_Callback, Self);\n  JsSetCallback(FContext.Global, 'loadWasm', @LoadWasm_Callback, Self);\n\n  // project TConsole class so scripts can create instances, e.g. var c = new Console();\n  TConsole.Project;\n\n  // expose global.console\n  FConsole := TConsole.Create;\n  JsSetProperty(FContext.Global, 'console', FConsole.Instance);\n\n  FCanvas := JsCreateObject;\n  JsSetProperty(FCanvas, 'fillStyle', StringToJsString('black'));\n  JsSetCallback(FCanvas, 'fillRect', @Canvas_FillRect_Callback, Self);\n  JsSetProperty(FContext.Global, 'ctx', FCanvas);\nend;\n\nprocedure TDataModuleMain.ContextNativeObjectCreated(Sender: TObject; NativeObject: TNativeObject);\nbegin\n  if NativeObject is TConsole then\n    TConsole(NativeObject).OnLog := ConsoleLog;\nend;\n\nfunction TDataModuleMain.LoadWasmModule(const FileName: UnicodeString): JsValueRef;\nvar\n  Buffer: TChakraCoreNativeArrayBuffer;\n  FileStream: TFileStream;\nbegin\n  Result := JsUndefinedValue;\n\n  FileStream := TFileStream.Create(FileName, fmOpenRead);\n  try\n    Buffer := TChakraCoreNativeArrayBuffer.Create(FileStream.Size);\n    try\n      FileStream.ReadBuffer(Buffer.Buffer^, Buffer.BufferSize);\n      Result := Buffer.Handle;\n      ConsoleLog(FConsole, Format('Loaded WebAssembly file ''%s''', [FWasmFileName]));\n    except\n      Buffer.Free;\n      raise;\n    end;\n  finally\n    FileStream.Free;\n  end;\nend;\n\nprocedure TDataModuleMain.RunScript;\nvar\n  Script: UnicodeString;\nbegin\n  try\n    Script := LoadFile(FScriptFileName);\n    ConsoleLog(FConsole, Format('Loaded Javascript file ''%s''', [FScriptFileName]));\n    FContext.RunScript(Script, FScriptFileName);\n  except\n    on E: EChakraCoreScript do\n      ConsoleLog(FConsole, Format('%s (%d, %d): [%s] %s', [E.ScriptURL, E.Line + 1, E.Column + 1, E.ClassName,\n        E.Message]));\n    on E: Exception do\n      ConsoleLog(FConsole, Format('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nprocedure TDataModuleMain.Finalize;\nbegin\n  FreeAndNil(FConsole);\n  FreeAndNil(FContext);\n  FreeAndNil(FRuntime);\nend;\n\nfunction TDataModuleMain.GetActive: Boolean;\nbegin\n  Result := Assigned(FThread);\nend;\n\nprocedure TDataModuleMain.Initialize;\nbegin\n  FRuntime := TChakraCoreRuntime.Create([ccroEnableExperimentalFeatures, ccroDispatchSetExceptionsToDebugger]);\n  FContext := TChakraCoreContext.Create(FRuntime);\n  FContext.OnActivate := ContextActivate;\n  FContext.OnNativeObjectCreated := ContextNativeObjectCreated;\nend;\n\nprocedure TDataModuleMain.SetActive(Value: Boolean);\nbegin\n  if Value <> Active then\n  begin\n    FTerminated := not Value;\n    if Value then\n    begin\n      if FScriptFileName = '' then\n      begin\n        OpenDialog.FileName := '';\n        if OpenDialog.Execute then\n          FScriptFileName := OpenDialog.FileName;\n      end;\n      FThread := TWasmThread.Create(Self);\n    end;\n  end;\nend;\n\nend.\n"
  },
  {
    "path": "samples/WasmSample/WasmMainForm.dfm",
    "content": "object FormMain: TFormMain\n  Left = 192\n  Top = 124\n  Width = 464\n  Height = 639\n  Caption = 'FormMain'\n  Color = clBtnFace\n  Constraints.MinHeight = 639\n  Constraints.MinWidth = 464\n  Font.Charset = DEFAULT_CHARSET\n  Font.Color = clWindowText\n  Font.Height = -11\n  Font.Name = 'MS Sans Serif'\n  Font.Style = []\n  OldCreateOrder = True\n  ShowHint = True\n  OnCloseQuery = FormCloseQuery\n  OnCreate = FormCreate\n  DesignSize = (\n    448\n    600)\n  PixelsPerInch = 96\n  TextHeight = 13\n  object PaintBox: TPaintBox\n    Left = 4\n    Top = 36\n    Width = 440\n    Height = 440\n    Anchors = [akLeft, akTop, akRight, akBottom]\n    OnPaint = PaintBoxPaint\n  end\n  object MemoLog: TMemo\n    Left = 4\n    Top = 480\n    Width = 440\n    Height = 109\n    Anchors = [akLeft, akRight, akBottom]\n    Font.Charset = ANSI_CHARSET\n    Font.Color = clWindowText\n    Font.Height = -12\n    Font.Name = 'Consolas'\n    Font.Style = []\n    ParentColor = True\n    ParentFont = False\n    ReadOnly = True\n    ScrollBars = ssBoth\n    TabOrder = 0\n  end\n  object ToolBar: TToolBar\n    Left = 0\n    Top = 0\n    Width = 448\n    Height = 41\n    ButtonHeight = 36\n    ButtonWidth = 29\n    Caption = 'ToolBar'\n    Images = ImageList\n    ShowCaptions = True\n    TabOrder = 1\n    object ToolButtonStartStop: TToolButton\n      Left = 0\n      Top = 2\n      Action = ActionStartStop\n    end\n  end\n  object ImageList: TImageList\n    Left = 80\n    Top = 56\n    Bitmap = {\n      494C010102000400040010001000FFFFFFFFFF10FFFFFFFFFFFFFFFF424D3600\n      0000000000003600000028000000400000001000000001002000000000000010\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000001810100008000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000800000028302000080000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      00000000000000000000008000002AB72A000284020000800000000000000000\n      00000000000000000000000000000000000000000000000000000000AA000000\n      AA000000AA000000AA000000AA000000AA000000AA000000AA000000AA000000\n      AA000000AA000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      000000000000000000000080000037C837002AB72A0002840200008000000000\n      00000000000000000000000000000000000000000000000000000000AA006B6B\n      FF005F5FFF005353FF004747FF003B3BFF002F2FFF002424FF001818FF000C0C\n      FF000000AA000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      000000000000000000000080000037C8370037C837002AB72A00028402000080\n      00000000000000000000000000000000000000000000000000000000AA007676\n      FF006B6BFF005F5FFF005353FF004747FF003B3BFF002F2FFF002424FF001818\n      FF000000AA000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      000000000000000000000080000037C8370037C8370037C837002AB72A000284\n      02000080000000000000000000000000000000000000000000000000AA008282\n      FF007676FF006B6BFF005F5FFF005353FF004747FF003B3BFF002F2FFF002424\n      FF000000AA000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      000000000000000000000080000037C8370037C8370037C8370037C8370029B6\n      29000283020000820000000000000000000000000000000000000000AA008E8E\n      FF008282FF007676FF006B6BFF005F5FFF005353FF004747FF003B3BFF002F2F\n      FF000000AA000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      000000000000000000000080000037C8370037C8370037C8370037C8370029B6\n      29000283020000820000000000000000000000000000000000000000AA009A9A\n      FF008E8EFF008282FF007676FF006B6BFF005F5FFF005353FF004747FF003B3B\n      FF000000AA000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      000000000000000000000080000037C8370037C8370037C837002AB72A000283\n      02000080000000000000000000000000000000000000000000000000AA00A6A6\n      FF009A9AFF008E8EFF008282FF007676FF006B6BFF005F5FFF005353FF004747\n      FF000000AA000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      000000000000000000000080000037C8370037C837002AB72A00028302000080\n      00000000000000000000000000000000000000000000000000000000AA00B2B2\n      FF00A6A6FF009A9AFF008E8EFF008282FF007676FF006B6BFF005F5FFF005353\n      FF000000AA000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      000000000000000000000080000037C837002AB72A0002830200008000000000\n      00000000000000000000000000000000000000000000000000000000AA00BDBD\n      FF00B2B2FF00A6A6FF009A9AFF008E8EFF008282FF007676FF006B6BFF005F5F\n      FF000000AA000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      00000000000000000000008000002AB72A000283020000800000000000000000\n      00000000000000000000000000000000000000000000000000000000AA00C9C9\n      FF00BDBDFF00B2B2FF00A6A6FF009A9AFF008E8EFF008282FF007676FF006B6B\n      FF000000AA000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000800000028302000080000000000000000000000000\n      00000000000000000000000000000000000000000000000000000000AA000000\n      AA000000AA000000AA000000AA000000AA000000AA000000AA000000AA000000\n      AA000000AA000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000001810100008000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      0000000000000000000000000000000000000000000000000000000000000000\n      000000000000000000000000000000000000424D3E000000000000003E000000\n      2800000040000000100000000100010000000000800000000000000000000000\n      000000000000000000000000FFFFFF00FFFFFFFF00000000FCFFFFFF00000000\n      FC7FFFFF00000000FC3FC00700000000FC1FC00700000000FC0FC00700000000\n      FC07C00700000000FC03C00700000000FC03C00700000000FC07C00700000000\n      FC0FC00700000000FC1FC00700000000FC3FC00700000000FC7FC00700000000\n      FCFFFFFF00000000FFFFFFFF0000000000000000000000000000000000000000\n      000000000000}\n  end\n  object ActionList: TActionList\n    Images = ImageList\n    Left = 120\n    Top = 56\n    object ActionStartStop: TAction\n      Caption = 'Start'\n      ImageIndex = 0\n      ShortCut = 120\n      OnExecute = ActionStartStopExecute\n      OnUpdate = ActionStartStopUpdate\n    end\n  end\nend\n"
  },
  {
    "path": "samples/WasmSample/WasmMainForm.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nunit WasmMainForm;\n\ninterface\n\n{$include common.inc}\n\nuses\n{$ifdef FPC}\n  LCLIntf, LCLType, LMessages,\n{$else}\n  Windows,\n{$endif}\n  SysUtils, Variants, Classes, Types, Messages,\n  Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ToolWin, ComCtrls, ActnList, ImgList, Compat;\n\nconst\n  Dimension = 50;\n\n  WM_CONSOLELOG = WM_USER + 1;\n\ntype\n\n  TWMConsoleLog = record\n    Msg: Cardinal;\n{$ifdef CPU64}\n    UnusedMsg: Cardinal;\n{$endif CPU64}\n    Text: PWideChar;\n    Unusedl: NativeInt;\n    Result: LRESULT;\n  end;\n\n  { TFormMain }\n\n  TFormMain = class(TForm)\n    ActionList: TActionList;\n    ActionStartStop: TAction;\n    ImageList: TImageList;\n    MemoLog: TMemo;\n    PaintBox: TPaintBox;\n    ToolBar: TToolBar;\n    ToolButtonStartStop: TToolButton;\n\n    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);\n    procedure FormCreate(Sender: TObject);\n\n    procedure ActionStartStopExecute(Sender: TObject);\n    procedure ActionStartStopUpdate(Sender: TObject);\n    procedure PaintBoxPaint(Sender: TObject);\n  private\n    FGame: array[0..Dimension - 1, 0..Dimension - 1] of Boolean;\n\n    procedure ApplicationIdle(Sender: TObject; var Done: Boolean);\n    procedure WMConsoleLog(var Message: TWMConsoleLog); message WM_CONSOLELOG;\n  public\n    procedure FillRect(X, Y, W, H: Integer; const Style: string);\n  end;\n\nvar\n  FormMain: TFormMain;\n\nimplementation\n\n{$R *.dfm}\n\nuses\n  ChakraCore, ChakraCoreVersion, ChakraCoreUtils,\n  WasmMainData;\n\nprocedure TFormMain.FillRect(X, Y, W, H: Integer; const Style: string);\nvar\n  I, J: Integer;\n  CellValue: Boolean;\nbegin\n  CellValue := Style = 'green';\n\n  if not CellValue and (W = Dimension) and (H = Dimension) then\n  begin\n    FillChar(FGame, SizeOf(FGame), 0);\n    Exit;\n  end;\n  \n  for I := X to X + W - 1 do\n    for J := Y to Y + H - 1 do\n      FGame[I, J] := CellValue;\n\n{$ifndef LINUX}\n  PaintBox.Invalidate;\n{$endif !LINUX}\nend;\n\nprocedure TFormMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);\nbegin\n  CanClose := True;\n  DataModuleMain.Active := False;\nend;\n\nprocedure TFormMain.FormCreate(Sender: TObject);\nbegin\n  PaintBox.Width := ClientWidth - 8;\n  MemoLog.Width := ClientWidth - 8;\n  DoubleBuffered := True;\n  Caption := Application.Title;\n{$ifdef LINUX}\n  Application.OnIdle := ApplicationIdle;\n{$endif LINUX}\n\n  MemoLog.Lines.Add(Format('%s %s', [ExtractFileName(ParamStr(0)), GetExeFileVersionString]));\n  MemoLog.Lines.Add(Format('Built with %s', [GetBuildInfoString]));\n  MemoLog.Lines.Add(Format('Chakra Core version: %d.%d.%d', [CHAKRA_CORE_MAJOR_VERSION, CHAKRA_CORE_MINOR_VERSION, CHAKRA_CORE_PATCH_VERSION]));\n  MemoLog.Lines.Add('');\nend;\n\nprocedure TFormMain.ActionStartStopExecute(Sender: TObject);\nbegin\n  DataModuleMain.Active := not DataModuleMain.Active;\nend;\n\nprocedure TFormMain.ActionStartStopUpdate(Sender: TObject);\nconst\n  StartStopCaptions: array[Boolean] of string = ('Start', 'Stop');\n  StartStopImageIndexes: array[Boolean] of Integer = (0, 1);\nvar\n  Action: TAction absolute Sender;\nbegin\n  Action.Caption := StartStopCaptions[DataModuleMain.Active];\n  Action.Hint := StartStopCaptions[DataModuleMain.Active];\n  Action.ImageIndex := StartStopImageIndexes[DataModuleMain.Active];\nend;\n\nprocedure TFormMain.PaintBoxPaint(Sender: TObject);\nvar\n  PaintBox: TPaintBox absolute Sender;\n  W, H, X, Y: Integer;\n  R: TRect;\nbegin\n  PaintBox.Canvas.Brush.Color := clBlack;\n  PaintBox.Canvas.FillRect(PaintBox.ClientRect);\n\n  PaintBox.Canvas.Brush.Color := clGreen;\n  W := PaintBox.ClientWidth div Dimension;\n  H := PaintBox.ClientHeight div Dimension;\n  R := Rect(0, 0, W, H);\n  for Y := 0 to Dimension - 1 do\n  begin\n    R.Left := 0;\n    R.Right := W;\n    for X := 0 to Dimension - 1 do\n    begin\n      if FGame[X, Y] then\n        PaintBox.Canvas.FillRect(R);\n      OffsetRect(R, W, 0);\n    end;\n    OffsetRect(R, 0, H);\n  end;\nend;\n\nprocedure TFormMain.ApplicationIdle(Sender: TObject; var Done: Boolean);\nbegin\n  PaintBox.Invalidate;\nend;\n\nprocedure TFormMain.WMConsoleLog(var Message: TWMConsoleLog);\nbegin\n  try\n    // inherited;\n    MemoLog.Lines.Add(Message.Text);\n  finally\n    if Assigned(Message.Text) then\n      FreeMem(Message.Text);\n  end;\nend;\n\nend.\n"
  },
  {
    "path": "samples/WasmSample/WasmSample.XE.dproj",
    "content": "﻿\t<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\t\t<PropertyGroup>\n\t\t\t<ProjectGuid>{6508e7aa-0c87-481c-ae23-258f81176312}</ProjectGuid>\n\t\t\t<MainSource>WasmSample.dpr</MainSource>\n\t\t\t<Config Condition=\"'$(Config)'==''\">Debug</Config>\n\t\t\t<DCC_DCCCompiler>DCC32</DCC_DCCCompiler>\n\t\t\t<ProjectVersion>12.3</ProjectVersion>\n\t\t\t<Base>True</Base>\n\t\t\t<Platform>Win32</Platform>\n\t\t\t<AppType>Application</AppType>\n\t\t\t<FrameworkType>VCL</FrameworkType>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Base' or '$(Base)'!=''\">\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Release' or '$(Cfg_1)'!=''\">\n\t\t\t<Cfg_1>true</Cfg_1>\n\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Debug' or '$(Cfg_2)'!=''\">\n\t\t\t<Cfg_2>true</Cfg_2>\n\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Base)'!=''\">\n\t\t\t<DCC_DependencyCheckOutputName>..\\..\\bin\\$(Platform)\\$(Config)\\WasmSample.exe</DCC_DependencyCheckOutputName>\n\t\t\t<DCC_ExeOutput>..\\..\\bin\\$(Platform)\\$(Config)</DCC_ExeOutput>\n\t\t\t<DCC_DcuOutput>..\\..\\lib\\$(Platform)\\$(Config)</DCC_DcuOutput>\n\t\t\t<DCC_ImageBase>00400000</DCC_ImageBase>\n\t\t\t<DCC_UsePackage>vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP;JclDeveloperTools;Jcl;JclVcl;JclContainers</DCC_UsePackage>\n\t\t\t<DCC_UnitAlias>WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;$(DCC_UnitAlias)</DCC_UnitAlias>\n\t\t\t<DCC_Platform>x86</DCC_Platform>\n\t\t\t<DCC_UnitSearchPath>..\\..\\src;..\\HostSample;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>\n\t\t\t<DCC_K>false</DCC_K>\n\t\t\t<DCC_N>true</DCC_N>\n\t\t\t<DCC_S>false</DCC_S>\n\t\t\t<DCC_SymbolReferenceInfo>1</DCC_SymbolReferenceInfo>\n\t\t\t<DCC_E>false</DCC_E>\n\t\t\t<DCC_F>false</DCC_F>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Cfg_1)'!=''\">\n\t\t\t<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>\n\t\t\t<DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>\n\t\t\t<DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>\n\t\t\t<DCC_DebugInformation>false</DCC_DebugInformation>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Cfg_2)'!=''\">\n\t\t\t<DCC_Define>DEBUG;$(DCC_Define)</DCC_Define>\n\t\t</PropertyGroup>\n\t\t<ItemGroup>\n\t\t\t<DelphiCompile Include=\"WasmSample.dpr\">\n\t\t\t\t<MainSource>MainSource</MainSource>\n\t\t\t</DelphiCompile>\n\t\t\t<DCCReference Include=\"WasmMainData.pas\">\n\t\t\t\t<Form>DataModuleMain</Form>\n\t\t\t\t<DesignClass>TDataModule</DesignClass>\n\t\t\t</DCCReference>\n\t\t\t<DCCReference Include=\"WasmMainForm.pas\">\n\t\t\t\t<Form>FormMain</Form>\n\t\t\t</DCCReference>\n\t\t\t<BuildConfiguration Include=\"Debug\">\n\t\t\t\t<Key>Cfg_2</Key>\n\t\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t</BuildConfiguration>\n\t\t\t<BuildConfiguration Include=\"Base\">\n\t\t\t\t<Key>Base</Key>\n\t\t\t</BuildConfiguration>\n\t\t\t<BuildConfiguration Include=\"Release\">\n\t\t\t\t<Key>Cfg_1</Key>\n\t\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t</BuildConfiguration>\n\t\t</ItemGroup>\n\t\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Delphi.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Delphi.Targets\"/>\n\t\t<Import Condition=\"Exists('$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj')\" Project=\"$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj\"/>\n\t\t<ProjectExtensions>\n\t\t\t<Borland.Personality>Delphi.Personality.12</Borland.Personality>\n\t\t\t<Borland.ProjectType>VCLApplication</Borland.ProjectType>\n\t\t\t<BorlandProject>\n\t\t\t\t<Delphi.Personality>\n\t\t\t\t\t<Source>\n\t\t\t\t\t\t<Source Name=\"MainSource\">WasmSample.dpr</Source>\n\t\t\t\t\t</Source>\n\t\t\t\t\t<Parameters>\n\t\t\t\t\t\t<Parameters Name=\"RunParams\">..\\..\\..\\samples\\WasmSample\\scripts\\main.js ..\\..\\..\\samples\\WasmSample\\scripts\\main.wasm</Parameters>\n\t\t\t\t\t</Parameters>\n\t\t\t\t\t<VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"IncludeVerInfo\">True</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"AutoIncBuild\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"MajorVer\">1</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"MinorVer\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Release\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Build\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Debug\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"PreRelease\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Special\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Private\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"DLL\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Locale\">1033</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"CodePage\">1252</VersionInfo>\n\t\t\t\t\t</VersionInfo>\n\t\t\t\t\t<VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"CompanyName\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"FileDescription\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"FileVersion\">1.0.0.0</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"InternalName\">WasmSample</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"LegalCopyright\">© 2021 Ondrej Kelle</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"LegalTrademarks\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"OriginalFilename\">WasmSample</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"ProductName\">chakracore-delphi</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"ProductVersion\">1.0.0.0</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"Comments\"/>\n\t\t\t\t\t</VersionInfoKeys>\n\t\t\t\t</Delphi.Personality>\n\t\t\t\t<Platforms>\n\t\t\t\t\t<Platform value=\"Win32\">True</Platform>\n\t\t\t\t</Platforms>\n\t\t\t</BorlandProject>\n\t\t\t<ProjectFileVersion>12</ProjectFileVersion>\n\t\t</ProjectExtensions>\n\t</Project>\n"
  },
  {
    "path": "samples/WasmSample/WasmSample.dof",
    "content": "[FileVersion]\nVersion=7.0\n[Compiler]\nA=8\nB=0\nC=1\nD=1\nE=0\nF=0\nG=1\nH=1\nI=1\nJ=0\nK=0\nL=1\nM=0\nN=1\nO=0\nP=1\nQ=0\nR=0\nS=0\nT=0\nU=0\nV=1\nW=0\nX=1\nY=1\nZ=1\nShowHints=1\nShowWarnings=1\nUnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;\nNamespacePrefix=\nSymbolDeprecated=1\nSymbolLibrary=1\nSymbolPlatform=1\nUnitLibrary=1\nUnitPlatform=1\nUnitDeprecated=1\nHResultCompat=1\nHidingMember=1\nHiddenVirtual=1\nGarbage=1\nBoundsError=1\nZeroNilCompat=1\nStringConstTruncated=1\nForLoopVarVarPar=1\nTypedConstVarPar=1\nAsgToTypedConst=1\nCaseLabelRange=1\nForVariable=1\nConstructingAbstract=1\nComparisonFalse=1\nComparisonTrue=1\nComparingSignedUnsigned=1\nCombiningSignedUnsigned=1\nUnsupportedConstruct=1\nFileOpen=1\nFileOpenUnitSrc=1\nBadGlobalSymbol=1\nDuplicateConstructorDestructor=1\nInvalidDirective=1\nPackageNoLink=1\nPackageThreadVar=1\nImplicitImport=1\nHPPEMITIgnored=1\nNoRetVal=1\nUseBeforeDef=1\nForLoopVarUndef=1\nUnitNameMismatch=1\nNoCFGFileFound=1\nMessageDirective=1\nImplicitVariants=1\nUnicodeToLocale=1\nLocaleToUnicode=1\nImagebaseMultiple=1\nSuspiciousTypecast=1\nPrivatePropAccessor=1\nUnsafeType=0\nUnsafeCode=0\nUnsafeCast=0\n[Linker]\nMapFile=0\nOutputObjs=0\nConsoleApp=1\nDebugInfo=0\nRemoteSymbols=0\nMinStackSize=16384\nMaxStackSize=1048576\nImageBase=4194304\nExeDescription=\n[Directories]\nOutputDir=..\\..\\bin\\Win32\\Debug\nUnitOutputDir=..\\..\\lib\\Win32\\Debug\nPackageDLLOutputDir=\nPackageDCPOutputDir=\nSearchPath=..\\..\\src;..\\..\\samples\\HostSample\nPackages=vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP;JclDeveloperTools;Jcl;JclVcl;JclContainers\nConditionals=\nDebugSourceDirs=\nUsePackages=0\n[Parameters]\nRunParams=..\\..\\..\\samples\\WasmSample\\scripts\\main.js\nHostApplication=\nLauncher=\nUseLauncher=0\nDebugCWD=\n[Language]\nActiveLang=\nProjectLang=\nRootDir=\n[Version Info]\nIncludeVerInfo=1\nAutoIncBuild=0\nMajorVer=1\nMinorVer=0\nRelease=0\nBuild=0\nDebug=0\nPreRelease=0\nSpecial=0\nPrivate=0\nDLL=0\nLocale=1033\nCodePage=1252\n[Version Info Keys]\nCompanyName=\nFileDescription=\nFileVersion=1.0.0.0\nInternalName=WasmSample\nLegalCopyright=© 2021 Ondrej Kelle\nLegalTrademarks=\nOriginalFilename=WasmSample.exe\nProductName=chakracore-delphi\nProductVersion=1.0.0.0\nComments=\n[HistoryLists\\hlUnitAliases]\nCount=1\nItem0=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;\n[HistoryLists\\hlSearchPath]\nCount=1\nItem0=..\\..\\src;..\\..\\samples\\HostSample\n[HistoryLists\\hlUnitOutputDirectory]\nCount=1\nItem0=..\\..\\lib\\Win32\\Debug\n[HistoryLists\\hlOutputDirectorry]\nCount=1\nItem0=..\\..\\bin\\Win32\\Debug\n"
  },
  {
    "path": "samples/WasmSample/WasmSample.dpr",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nprogram WasmSample;\n\n{$include common.inc}\n\nuses\n{$ifdef FPC}\n  {$apptype GUI}\n{$ifdef UNIX}\n  cthreads,\n{$endif UNIX}\n  Interfaces,\n{$endif FPC}\n  Classes, SysUtils, Forms,\n  Compat,\n  ChakraCoreVersion,\n  ChakraCoreUtils,\n  WasmMainData in 'WasmMainData.pas' {DataModuleMain: TDataModule},\n  WasmMainForm in 'WasmMainForm.pas' {FormMain};\n\n{$R *.res}\n\ntype\n  UnicodeStringDynArray = array of UnicodeString;\n\nfunction ParamStrings: UnicodeStringDynArray;\nvar\n  I: Integer;\nbegin\n  Result := nil;\n  SetLength(Result, ParamCount);\n  for I := 1 to ParamCount do\n    Result[I - 1] := UnicodeString(ParamStr(I));\nend;\n\nbegin\n{$ifdef DELPHI2006_UP}\n  ReportMemoryLeaksOnShutdown := True;\n{$endif DELPHI2006_UP}\n{$ifdef FPC}\n  RequireDerivedFormResource := True;\n{$endif FPC}\n  Application.Title := 'ChakraCore WebAssembly Sample';\n  Application.Initialize;\n  Application.CreateForm(TDataModuleMain, DataModuleMain);\n  Application.CreateForm(TFormMain, FormMain);\n  Application.Run;\nend.\n"
  },
  {
    "path": "samples/WasmSample/WasmSample.lpi",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CONFIG>\n  <ProjectOptions>\n    <Version Value=\"11\"/>\n    <General>\n      <Flags>\n        <MainUnitHasCreateFormStatements Value=\"False\"/>\n        <MainUnitHasScaledStatement Value=\"False\"/>\n      </Flags>\n      <SessionStorage Value=\"InProjectDir\"/>\n      <MainUnit Value=\"0\"/>\n      <Title Value=\"ChakraCore WebAssembly Sample\"/>\n      <Scaled Value=\"True\"/>\n      <ResourceType Value=\"res\"/>\n      <Icon Value=\"0\"/>\n    </General>\n    <VersionInfo>\n      <UseVersionInfo Value=\"True\"/>\n      <MajorVersionNr Value=\"1\"/>\n      <StringTable InternalName=\"WasmSample\" LegalCopyright=\"© 2021 Ondrej Kelle\" OriginalFilename=\"WasmSample\"/>\n    </VersionInfo>\n    <BuildModes Count=\"2\">\n      <Item1 Name=\"Debug\" Default=\"True\"/>\n      <Item2 Name=\"Release\">\n        <CompilerOptions>\n          <Version Value=\"11\"/>\n          <Target>\n            <Filename Value=\"WasmSample\"/>\n          </Target>\n          <SearchPaths>\n            <UnitOutputDirectory Value=\"lib/$(TargetCPU)-$(TargetOS)\"/>\n          </SearchPaths>\n          <CodeGeneration>\n            <SmartLinkUnit Value=\"True\"/>\n            <Optimizations>\n              <OptimizationLevel Value=\"3\"/>\n            </Optimizations>\n          </CodeGeneration>\n          <Linking>\n            <Debugging>\n              <GenerateDebugInfo Value=\"False\"/>\n            </Debugging>\n            <LinkSmart Value=\"True\"/>\n          </Linking>\n        </CompilerOptions>\n      </Item2>\n    </BuildModes>\n    <PublishOptions>\n      <Version Value=\"2\"/>\n    </PublishOptions>\n    <RunParams>\n      <local>\n        <CommandLineParams Value=\"../../../samples/WasmSample/scripts/main.js\"/>\n      </local>\n      <FormatVersion Value=\"2\"/>\n      <Modes Count=\"1\">\n        <Mode0 Name=\"Debug\">\n          <local>\n            <CommandLineParams Value=\"../../../samples/WasmSample/scripts/main.js\"/>\n          </local>\n        </Mode0>\n      </Modes>\n    </RunParams>\n    <RequiredPackages Count=\"2\">\n      <Item1>\n        <PackageName Value=\"LCL\"/>\n      </Item1>\n      <Item2>\n        <PackageName Value=\"LCLBase\"/>\n      </Item2>\n    </RequiredPackages>\n    <Units Count=\"3\">\n      <Unit0>\n        <Filename Value=\"WasmSample.dpr\"/>\n        <IsPartOfProject Value=\"True\"/>\n      </Unit0>\n      <Unit1>\n        <Filename Value=\"WasmMainData.pas\"/>\n        <IsPartOfProject Value=\"True\"/>\n        <ComponentName Value=\"DataModuleMain\"/>\n        <HasResources Value=\"True\"/>\n        <ResourceBaseClass Value=\"DataModule\"/>\n      </Unit1>\n      <Unit2>\n        <Filename Value=\"WasmMainForm.pas\"/>\n        <IsPartOfProject Value=\"True\"/>\n        <ComponentName Value=\"FormMain\"/>\n        <HasResources Value=\"True\"/>\n        <ResourceBaseClass Value=\"Form\"/>\n      </Unit2>\n    </Units>\n  </ProjectOptions>\n  <CompilerOptions>\n    <Version Value=\"11\"/>\n    <Target>\n      <Filename Value=\"../../bin/$(TargetCPU)-$(TargetOS)/$(BuildMode)/WasmSample\"/>\n    </Target>\n    <SearchPaths>\n      <IncludeFiles Value=\"$(ProjOutDir);../../src\"/>\n      <OtherUnitFiles Value=\"../../src;../../samples/HostSample\"/>\n      <UnitOutputDirectory Value=\"../../lib/$(TargetCPU)-$(TargetOS)/$(BuildMode)\"/>\n    </SearchPaths>\n    <Parsing>\n      <SyntaxOptions>\n        <IncludeAssertionCode Value=\"True\"/>\n      </SyntaxOptions>\n    </Parsing>\n    <CodeGeneration>\n      <Checks>\n        <IOChecks Value=\"True\"/>\n        <RangeChecks Value=\"True\"/>\n        <OverflowChecks Value=\"True\"/>\n        <StackChecks Value=\"True\"/>\n      </Checks>\n    </CodeGeneration>\n    <Linking>\n      <Debugging>\n        <DebugInfoType Value=\"dsDwarf2Set\"/>\n        <UseHeaptrc Value=\"True\"/>\n        <TrashVariables Value=\"True\"/>\n        <UseExternalDbgSyms Value=\"True\"/>\n      </Debugging>\n      <Options>\n        <Win32>\n          <GraphicApplication Value=\"True\"/>\n        </Win32>\n      </Options>\n    </Linking>\n  </CompilerOptions>\n  <Debugging>\n    <Exceptions Count=\"4\">\n      <Item1>\n        <Name Value=\"EAbort\"/>\n      </Item1>\n      <Item2>\n        <Name Value=\"ECodetoolError\"/>\n      </Item2>\n      <Item3>\n        <Name Value=\"EFOpenError\"/>\n      </Item3>\n      <Item4>\n        <Name Value=\"EChakraCore\"/>\n      </Item4>\n    </Exceptions>\n  </Debugging>\n</CONFIG>\n"
  },
  {
    "path": "samples/WasmSample/scripts/main.js",
    "content": "const DIMENSIONS = 50;\nconst verbose = false; // true;\n\nconst rand = () => Math.floor(Math.random() * DIMENSIONS);\n\nWebAssembly.instantiate(loadWasm('main.wasm'), {\n  console: {\n    log: (x, y) => console.log(x, y)\n  }\n}).then(results => {\n  const game = results.instance.exports;\n\n  for (let i = 0; i < 400; i++) {\n    game.setCell(rand(), rand(), 1);\n  }\n\n  let step = 0;\n\n  const render = () => {\n\tlet count = 0;\n    ctx.fillStyle = \"black\";\n    ctx.fillRect(0, 0, DIMENSIONS, DIMENSIONS);\n\n    ctx.fillStyle = \"green\";\n    for (let y = 0; y < DIMENSIONS; y++) {\n      for (let x = 0; x < DIMENSIONS; x++) {\n        if (game.getCell(x, y) > 0) {\n          ctx.fillRect(x, y, 1, 1);\n\t\t  count++;\n        }\n      }\n    }\n\t\n    if (verbose) {\n\t  console.log('Step %d: %d alive', step++, count);\n\t}\n  };\n\n  setInterval(() => {\n    game.tick();\n    render();\n  }, 50);\n\n});"
  },
  {
    "path": "src/ChakraCommon.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\n//-------------------------------------------------------------------------------------------------------\n// Copyright (C) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n//-------------------------------------------------------------------------------------------------------\n/// \\mainpage Chakra Hosting API Reference\n///\n/// Chakra is Microsoft's JavaScript engine. It is an integral part of Internet Explorer but can\n/// also be hosted independently by other applications. This reference describes the APIs available\n/// to applications to host Chakra.\n///\n/// This file contains the common API set shared among all Chakra releases.  For Windows-specific\n/// releases, see chakrart.h.\n\n/// \\file\n/// \\brief The base Chakra hosting API.\n///\n/// This file contains a flat C API layer. This is the API exported by chakra.dll.\n\nunit ChakraCommon;\n\n{$include common.inc}\n\n{$minenumsize 4}\n\ninterface\n\nuses\n  Compat;\n\ntype\n  bool = ByteBool;\n  Psize_t = ^size_t;\n  size_t = NativeUInt;\n\n  JsHandle = ^_JsHandle;\n  _JsHandle = record end;\n\n  ChakraCookie = UIntPtr;\n  ChakraBytePtr = PByte;\n\n  /// <summary>\n  ///     An error code returned from a Chakra hosting API.\n  /// </summary>\n  JsErrorCode = (\n    /// <summary>\n    ///     Success error code.\n    /// </summary>\n    JsNoError = 0,\n    /// <summary>\n    ///     Category of errors that relates to incorrect usage of the API itself.\n    /// </summary>\n    JsErrorCategoryUsage = $10000,\n    /// <summary>\n    ///     An argument to a hosting API was invalid.\n    /// </summary>\n    JsErrorInvalidArgument,\n    /// <summary>\n    ///     An argument to a hosting API was null in a context where null is not allowed.\n    /// </summary>\n    JsErrorNullArgument,\n    /// <summary>\n    ///     The hosting API requires that a context be current, but there is no current context.\n    /// </summary>\n    JsErrorNoCurrentContext,\n    /// <summary>\n    ///     The engine is in an exception state and no APIs can be called until the exception is\n    ///     cleared.\n    /// </summary>\n    JsErrorInExceptionState,\n    /// <summary>\n    ///     A hosting API is not yet implemented.\n    /// </summary>\n    JsErrorNotImplemented,\n    /// <summary>\n    ///     A hosting API was called on the wrong thread.\n    /// </summary>\n    JsErrorWrongThread,\n    /// <summary>\n    ///     A runtime that is still in use cannot be disposed.\n    /// </summary>\n    JsErrorRuntimeInUse,\n    /// <summary>\n    ///     A bad serialized script was used, or the serialized script was serialized by a\n    ///     different version of the Chakra engine.\n    /// </summary>\n    JsErrorBadSerializedScript,\n    /// <summary>\n    ///     The runtime is in a disabled state.\n    /// </summary>\n    JsErrorInDisabledState,\n    /// <summary>\n    ///     Runtime does not support reliable script interruption.\n    /// </summary>\n    JsErrorCannotDisableExecution,\n    /// <summary>\n    ///     A heap enumeration is currently underway in the script context.\n    /// </summary>\n    JsErrorHeapEnumInProgress,\n    /// <summary>\n    ///     A hosting API that operates on object values was called with a non-object value.\n    /// </summary>\n    JsErrorArgumentNotObject,\n    /// <summary>\n    ///     A script context is in the middle of a profile callback.\n    /// </summary>\n    JsErrorInProfileCallback,\n    /// <summary>\n    ///     A thread service callback is currently underway.\n    /// </summary>\n    JsErrorInThreadServiceCallback,\n    /// <summary>\n    ///     Scripts cannot be serialized in debug contexts.\n    /// </summary>\n    JsErrorCannotSerializeDebugScript,\n    /// <summary>\n    ///     The context cannot be put into a debug state because it is already in a debug state.\n    /// </summary>\n    JsErrorAlreadyDebuggingContext,\n    /// <summary>\n    ///     The context cannot start profiling because it is already profiling.\n    /// </summary>\n    JsErrorAlreadyProfilingContext,\n    /// <summary>\n    ///     Idle notification given when the host did not enable idle processing.\n    /// </summary>\n    JsErrorIdleNotEnabled,\n    /// <summary>\n    ///     The context did not accept the enqueue callback.\n    /// </summary>\n    JsCannotSetProjectionEnqueueCallback,\n    /// <summary>\n    ///     Failed to start projection.\n    /// </summary>\n    JsErrorCannotStartProjection,\n    /// <summary>\n    ///     The operation is not supported in an object before collect callback.\n    /// </summary>\n    JsErrorInObjectBeforeCollectCallback,\n    /// <summary>\n    ///     Object cannot be unwrapped to IInspectable pointer.\n    /// </summary>\n    JsErrorObjectNotInspectable,\n    /// <summary>\n    ///     A hosting API that operates on symbol property ids but was called with a non-symbol property id.\n    ///     The error code is returned by JsGetSymbolFromPropertyId if the function is called with non-symbol property id.\n    /// </summary>\n    JsErrorPropertyNotSymbol,\n    /// <summary>\n    ///     A hosting API that operates on string property ids but was called with a non-string property id.\n    ///     The error code is returned by existing JsGetPropertyNamefromId if the function is called with non-string property id.\n    /// </summary>\n    JsErrorPropertyNotString,\n    /// <summary>\n    ///     Module evaluation is called in wrong context.\n    /// </summary>\n    JsErrorInvalidContext,\n    /// <summary>\n    ///     Module evaluation is called in wrong context.\n    /// </summary>\n    JsInvalidModuleHostInfoKind,\n    /// <summary>\n    ///     Module was parsed already when JsParseModuleSource is called.\n    /// </summary>\n    JsErrorModuleParsed,\n    /// <summary>\n    ///     Module was evaluated already when JsModuleEvaluation is called.\n    /// </summary>\n    JsErrorModuleEvaluated,\n    /// <summary>\n    ///     Argument passed to JsCreateWeakReference is a primitive that is not managed by the GC.\n    ///     No weak reference is required, the value will never be collected.\n    /// </summary>\n    JsNoWeakRefRequired,\n    /// <summary>\n    ///     The <c>Promise</c> object is still in the pending state.\n    /// </summary>\n    JsErrorPromisePending,\n    /// <summary>\n    ///     Module was not yet evaluated when JsGetModuleNamespace was called.\n    /// </summary>\n    JsErrorModuleNotEvaluated,\n    /// <summary>\n    ///     Category of errors that relates to errors occurring within the engine itself.\n    /// </summary>\n    JsErrorCategoryEngine = $20000,\n    /// <summary>\n    ///     The Chakra engine has run out of memory.\n    /// </summary>\n    JsErrorOutOfMemory,\n    /// <summary>\n    ///     The Chakra engine failed to set the Floating Point Unit state.\n    /// </summary>\n    JsErrorBadFPUState,\n\n    /// <summary>\n    ///     Category of errors that relates to errors in a script.\n    /// </summary>\n    JsErrorCategoryScript = $30000,\n    /// <summary>\n    ///     A JavaScript exception occurred while running a script.\n    /// </summary>\n    JsErrorScriptException,\n    /// <summary>\n    ///     JavaScript failed to compile.\n    /// </summary>\n    JsErrorScriptCompile,\n    /// <summary>\n    ///     A script was terminated due to a request to suspend a runtime.\n    /// </summary>\n    JsErrorScriptTerminated,\n    /// <summary>\n    ///     A script was terminated because it tried to use <c>eval</c> or <c>function</c> and eval\n    ///     was disabled.\n    /// </summary>\n    JsErrorScriptEvalDisabled,\n\n    /// <summary>\n    ///     Category of errors that are fatal and signify failure of the engine.\n    /// </summary>\n    JsErrorCategoryFatal = $40000,\n    /// <summary>\n    ///     A fatal error in the engine has occurred.\n    /// </summary>\n    JsErrorFatal,\n    /// <summary>\n    ///     A hosting API was called with object created on different javascript runtime.\n    /// </summary>\n    JsErrorWrongRuntime,\n\n    /// <summary>\n    ///     Category of errors that are related to failures during diagnostic operations.\n    /// </summary>\n    JsErrorCategoryDiagError = $50000,\n    /// <summary>\n    ///     The object for which the debugging API was called was not found\n    /// </summary>\n    JsErrorDiagAlreadyInDebugMode,\n    /// <summary>\n    ///     The debugging API can only be called when VM is in debug mode\n    /// </summary>\n    JsErrorDiagNotInDebugMode,\n    /// <summary>\n    ///     The debugging API can only be called when VM is at a break\n    /// </summary>\n    JsErrorDiagNotAtBreak,\n    /// <summary>\n    ///     Debugging API was called with an invalid handle.\n    /// </summary>\n    JsErrorDiagInvalidHandle,\n    /// <summary>\n    ///     The object for which the debugging API was called was not found\n    /// </summary>\n    JsErrorDiagObjectNotFound,\n    /// <summary>\n    ///     VM was unable to perform the request action\n    /// </summary>\n    JsErrorDiagUnableToPerformAction\n  );\n\n  /// <summary>\n  ///     A handle to a Chakra runtime.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     Each Chakra runtime has its own independent execution engine, JIT compiler, and garbage\n  ///     collected heap. As such, each runtime is completely isolated from other runtimes.\n  ///     </para>\n  ///     <para>\n  ///     Runtimes can be used on any thread, but only one thread can call into a runtime at any\n  ///     time.\n  ///     </para>\n  ///     <para>\n  ///     NOTE: A <c>JsRuntimeHandle</c>, unlike other object references in the Chakra hosting API,\n  ///     is not garbage collected since it contains the garbage collected heap itself. A runtime\n  ///     will continue to exist until <c>JsDisposeRuntime</c> is called.\n  ///     </para>\n  /// </remarks>\n  JsRuntimeHandle = JsHandle;\n\nconst\n  /// <summary>\n  ///     An invalid runtime handle.\n  /// </summary>\n  JS_INVALID_RUNTIME_HANDLE = JsRuntimeHandle(nil);\n\n  /// <summary>\n  ///     A reference to an object owned by the Chakra garbage collector.\n  /// </summary>\n  /// <remarks>\n  ///     A Chakra runtime will automatically track <c>JsRef</c> references as long as they are\n  ///     stored in local variables or in parameters (i.e. on the stack). Storing a <c>JsRef</c>\n  ///     somewhere other than on the stack requires calling <c>JsAddRef</c> and <c>JsRelease</c> to\n  ///     manage the lifetime of the object, otherwise the garbage collector may free the object\n  ///     while it is still in use.\n  /// </remarks>\ntype\n  JsRef = JsHandle;\n\nconst\n  /// <summary>\n  ///     An invalid reference.\n  /// </summary>\n  JS_INVALID_REFERENCE = JsRef(nil);\n\ntype\n  /// <summary>\n  ///     A reference to a script context.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     Each script context contains its own global object, distinct from the global object in\n  ///     other script contexts.\n  ///     </para>\n  ///     <para>\n  ///     Many Chakra hosting APIs require an \"active\" script context, which can be set using\n  ///     <c>JsSetCurrentContext</c>. Chakra hosting APIs that require a current context to be set\n  ///     will note that explicitly in their documentation.\n  ///     </para>\n  /// </remarks>\n  JsContextRef = JsRef;\n\n  PJsValueRef = ^JsValueRef;\n  /// <summary>\n  ///     A reference to a JavaScript value.\n  /// </summary>\n  /// <remarks>\n  ///     A JavaScript value is one of the following types of values: undefined, null, Boolean,\n  ///     string, number, or object.\n  /// </remarks>\n  JsValueRef = JsRef;\n\n  /// <summary>\n  ///     A cookie that identifies a script for debugging purposes.\n  /// </summary>\n  JsSourceContext = ChakraCookie;\n\nconst\n    /// <summary>\n    ///     An empty source context.\n    /// </summary>\n  JS_SOURCE_CONTEXT_NONE = JsSourceContext(-1);\n\ntype\n  /// <summary>\n  ///     A property identifier.\n  /// </summary>\n  /// <remarks>\n  ///     Property identifiers are used to refer to properties of JavaScript objects instead of using\n  ///     strings.\n  /// </remarks>\n  JsPropertyIdRef = type JsRef;\n\n  /// <summary>\n  ///     Attributes of a runtime.\n  /// </summary>\n  JsRuntimeAttributes = Cardinal;\n\nconst\n  /// <summary>\n  ///     No special attributes.\n  /// </summary>\n  JsRuntimeAttributeNone = $00000000;\n  /// <summary>\n  ///     The runtime will not do any work (such as garbage collection) on background threads.\n  /// </summary>\n  JsRuntimeAttributeDisableBackgroundWork = $00000001;\n  /// <summary>\n  ///     The runtime should support reliable script interruption. This increases the number of\n  ///     places where the runtime will check for a script interrupt request at the cost of a\n  ///     small amount of runtime performance.\n  /// </summary>\n  JsRuntimeAttributeAllowScriptInterrupt = $00000002;\n  /// <summary>\n  ///     Host will call <c>JsIdle</c>, so enable idle processing. Otherwise, the runtime will\n  ///     manage memory slightly more aggressively.\n  /// </summary>\n  JsRuntimeAttributeEnableIdleProcessing = $00000004;\n  /// <summary>\n  ///     Runtime will not generate native code.\n  /// </summary>\n  JsRuntimeAttributeDisableNativeCodeGeneration = $00000008;\n  /// <summary>\n  ///     Using <c>eval</c> or <c>function</c> constructor will throw an exception.\n  /// </summary>\n  JsRuntimeAttributeDisableEval = $00000010;\n  /// <summary>\n  ///     Runtime will enable all experimental features.\n  /// </summary>\n  JsRuntimeAttributeEnableExperimentalFeatures = $00000020;\n  /// <summary>\n  ///     Calling <c>JsSetException</c> will also dispatch the exception to the script debugger\n  ///     (if any) giving the debugger a chance to break on the exception.\n  /// </summary>\n  JsRuntimeAttributeDispatchSetExceptionsToDebugger = $00000040;\n  /// <summary>\n  ///     Disable Failfast fatal error on OOM\n  /// </summary>\n  JsRuntimeAttributeDisableFatalOnOOM = $00000080;\n  /// <summary>\n  ///     Runtime will not allocate executable code pages\n  ///     This also implies that Native Code generation will be turned off\n  ///     Note that this will break JavaScript stack decoding in tools\n  //      like WPA since they rely on allocation of unique thunks to\n  //      interpret each function and allocation of those thunks will be\n  //      disabled as well\n  /// </summary>\n  JsRuntimeAttributeDisableExecutablePageAllocation = $00000100;\n\ntype\n  PJsTypedArrayType = ^JsTypedArrayType;\n  /// <summary>\n  ///     The type of a typed JavaScript array.\n  /// </summary>\n  JsTypedArrayType = (\n    /// <summary>\n    ///     An int8 array.\n    /// </summary>\n    JsArrayTypeInt8,\n    /// <summary>\n    ///     An uint8 array.\n    /// </summary>\n    JsArrayTypeUint8,\n    /// <summary>\n    ///     An uint8 clamped array.\n    /// </summary>\n    JsArrayTypeUint8Clamped,\n    /// <summary>\n    ///     An int16 array.\n    /// </summary>\n    JsArrayTypeInt16,\n    /// <summary>\n    ///     An uint16 array.\n    /// </summary>\n    JsArrayTypeUint16,\n    /// <summary>\n    ///     An int32 array.\n    /// </summary>\n    JsArrayTypeInt32,\n    /// <summary>\n    ///     An uint32 array.\n    /// </summary>\n    JsArrayTypeUint32,\n    /// <summary>\n    ///     A float32 array.\n    /// </summary>\n    JsArrayTypeFloat32,\n    /// <summary>\n    ///     A float64 array.\n    /// </summary>\n    JsArrayTypeFloat64\n  );\n\n  /// <summary>\n  ///     Allocation callback event type.\n  /// </summary>\n  JsMemoryEventType = (\n    /// <summary>\n    ///     Indicates a request for memory allocation.\n    /// </summary>\n    JsMemoryAllocate = 0,\n    /// <summary>\n    ///     Indicates a memory freeing event.\n    /// </summary>\n    JsMemoryFree = 1,\n    /// <summary>\n    ///     Indicates a failed allocation event.\n    /// </summary>\n    JsMemoryFailure = 2\n  );\n\n  /// <summary>\n  ///     Attribute mask for JsParseScriptWithAttributes\n  /// </summary>\n  JsParseScriptAttribute = (\n    /// <summary>\n    ///     Default attribute\n    /// </summary>\n    // JsParseScriptAttributeNone = $0,\n    /// <summary>\n    ///     Specified script is internal and non-user code. Hidden from debugger\n    /// </summary>\n    JsParseScriptAttributeLibraryCode, // = $1,\n    /// <summary>\n    ///     ChakraCore assumes ExternalArrayBuffer is Utf8 by default.\n    ///     This one needs to be set for Utf16\n    /// </summary>\n    JsParseScriptAttributeArrayBufferIsUtf16Encoded // = $2\n  );\n  JsParseScriptAttributes = set of JsParseScriptAttribute;\n\n  /// <summary>\n  ///     Type enumeration of a JavaScript property\n  /// </summary>\n  JsPropertyIdType = (\n    /// <summary>\n    ///     Type enumeration of a JavaScript string property\n    /// </summary>\n    JsPropertyIdTypeString,\n    /// <summary>\n    ///     Type enumeration of a JavaScript symbol property\n    /// </summary>\n    JsPropertyIdTypeSymbol\n  );\n\n  /// <summary>\n  ///     The JavaScript type of a JsValueRef.\n  /// </summary>\n  JsValueType = (\n    /// <summary>\n    ///     The value is the <c>undefined</c> value.\n    /// </summary>\n    JsUndefined = 0,\n    /// <summary>\n    ///     The value is the <c>null</c> value.\n    /// </summary>\n    JsNull = 1,\n    /// <summary>\n    ///     The value is a JavaScript number value.\n    /// </summary>\n    JsNumber = 2,\n    /// <summary>\n    ///     The value is a JavaScript string value.\n    /// </summary>\n    JsString = 3,\n    /// <summary>\n    ///     The value is a JavaScript Boolean value.\n    /// </summary>\n    JsBoolean = 4,\n    /// <summary>\n    ///     The value is a JavaScript object value.\n    /// </summary>\n    JsObject = 5,\n    /// <summary>\n    ///     The value is a JavaScript function object value.\n    /// </summary>\n    JsFunction = 6,\n    /// <summary>\n    ///     The value is a JavaScript error object value.\n    /// </summary>\n    JsError = 7,\n    /// <summary>\n    ///     The value is a JavaScript array object value.\n    /// </summary>\n    JsArray = 8,\n    /// <summary>\n    ///     The value is a JavaScript symbol value.\n    /// </summary>\n    JsSymbol = 9,\n    /// <summary>\n    ///     The value is a JavaScript ArrayBuffer object value.\n    /// </summary>\n    JsArrayBuffer = 10,\n    /// <summary>\n    ///     The value is a JavaScript typed array object value.\n    /// </summary>\n    JsTypedArray = 11,\n    /// <summary>\n    ///     The value is a JavaScript DataView object value.\n    /// </summary>\n    JsDataView = 12\n  );\n\n  /// <summary>\n  ///     User implemented callback routine for memory allocation events\n  /// </summary>\n  /// <remarks>\n  ///     Use <c>JsSetRuntimeMemoryAllocationCallback</c> to register this callback.\n  /// </remarks>\n  /// <param name=\"callbackState\">\n  ///     The state passed to <c>JsSetRuntimeMemoryAllocationCallback</c>.\n  /// </param>\n  /// <param name=\"allocationEvent\">The type of type allocation event.</param>\n  /// <param name=\"allocationSize\">The size of the allocation.</param>\n  /// <returns>\n  ///     For the <c>JsMemoryAllocate</c> event, returning <c>true</c> allows the runtime to continue\n  ///     with the allocation. Returning false indicates the allocation request is rejected. The\n  ///     return value is ignored for other allocation events.\n  /// </returns>\n  JsMemoryAllocationCallback = function(callbackState: Pointer; allocationEvent: JsMemoryEventType; allocationSize: size_t): bool; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     A callback called before collection.\n  /// </summary>\n  /// <remarks>\n  ///     Use <c>JsSetBeforeCollectCallback</c> to register this callback.\n  /// </remarks>\n  /// <param name=\"callbackState\">The state passed to <c>JsSetBeforeCollectCallback</c>.</param>\n  JsBeforeCollectCallback = procedure(callbackState: Pointer); {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     A callback called before collecting an object.\n  /// </summary>\n  /// <remarks>\n  ///     Use <c>JsSetObjectBeforeCollectCallback</c> to register this callback.\n  /// </remarks>\n  /// <param name=\"ref\">The object to be collected.</param>\n  /// <param name=\"callbackState\">The state passed to <c>JsSetObjectBeforeCollectCallback</c>.</param>\n  JsObjectBeforeCollectCallback = procedure(ref: JsRef; callbackState: Pointer); {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     A background work item callback.\n  /// </summary>\n  /// <remarks>\n  ///     This is passed to the host's thread service (if provided) to allow the host to\n  ///     invoke the work item callback on the background thread of its choice.\n  /// </remarks>\n  /// <param name=\"callbackState\">Data argument passed to the thread service.</param>\n  JsBackgroundWorkItemCallback = procedure(callbackState: Pointer); {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     A thread service callback.\n  /// </summary>\n  /// <remarks>\n  ///     The host can specify a background thread service when calling <c>JsCreateRuntime</c>. If\n  ///     specified, then background work items will be passed to the host using this callback. The\n  ///     host is expected to either begin executing the background work item immediately and return\n  ///     true or return false and the runtime will handle the work item in-thread.\n  /// </remarks>\n  /// <param name=\"callback\">The callback for the background work item.</param>\n  /// <param name=\"callbackState\">The data argument to be passed to the callback.</param>\n  JsThreadServiceCallback = function(callback: JsBackgroundWorkItemCallback; callbackState: Pointer): bool; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Called by the runtime when it is finished with all resources related to the script execution.\n  ///     The caller should free the source if loaded, the byte code, and the context at this time.\n  /// </summary>\n  /// <param name=\"sourceContext\">The context passed to Js[Parse|Run]SerializedScriptWithCallback</param>\n  JsSerializedScriptUnloadCallback = procedure(sourceContext: JsSourceContext); {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     A finalizer callback.\n  /// </summary>\n  /// <param name=\"data\">\n  ///     The external data that was passed in when creating the object being finalized.\n  /// </param>\n  JsFinalizeCallback = procedure(data: Pointer); {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     A function callback.\n  /// </summary>\n  /// <param name=\"callee\">\n  ///     A function object that represents the function being invoked.\n  /// </param>\n  /// <param name=\"isConstructCall\">Indicates whether this is a regular call or a 'new' call.</param>\n  /// <param name=\"arguments\">The arguments to the call.</param>\n  /// <param name=\"argumentCount\">The number of arguments.</param>\n  /// <param name=\"callbackState\">\n  ///     The state passed to <c>JsCreateFunction</c>.\n  /// </param>\n  /// <returns>The result of the call, if any.</returns>\n  JsNativeFunction = function(callee: JsValueRef; isConstructCall: bool; arguments: PJsValueRef; argumentCount: Word;\n    callbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     A promise continuation callback.\n  /// </summary>\n  /// <remarks>\n  ///     The host can specify a promise continuation callback in <c>JsSetPromiseContinuationCallback</c>. If\n  ///     a script creates a task to be run later, then the promise continuation callback will be called with\n  ///     the task and the task should be put in a FIFO queue, to be run when the current script is\n  ///     done executing.\n  /// </remarks>\n  /// <param name=\"task\">The task, represented as a JavaScript function.</param>\n  /// <param name=\"callbackState\">The data argument to be passed to the callback.</param>\n  JsPromiseContinuationCallback = procedure(task: JsValueRef; callbackState: Pointer); {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new runtime.\n  /// </summary>\n  /// <param name=\"attributes\">The attributes of the runtime to be created.</param>\n  /// <param name=\"threadService\">The thread service for the runtime. Can be null.</param>\n  /// <param name=\"runtime\">The runtime created.</param>\n  /// <remarks>In the edge-mode binary, chakra.dll, this function lacks the <c>runtimeVersion</c>\n  /// parameter (compare to jsrt9.h).</remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateRuntime(\n          attributes: JsRuntimeAttributes;\n          threadService: JsThreadServiceCallback;\n          out runtime: JsRuntimeHandle): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Performs a full garbage collection.\n  /// </summary>\n  /// <param name=\"runtime\">The runtime in which the garbage collection will be performed.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCollectGarbage(\n          runtime: JsRuntimeHandle): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Disposes a runtime.\n  /// </summary>\n  /// <remarks>\n  ///     Once a runtime has been disposed, all resources owned by it are invalid and cannot be used.\n  ///     If the runtime is active (i.e. it is set to be current on a particular thread), it cannot\n  ///     be disposed.\n  /// </remarks>\n  /// <param name=\"runtime\">The runtime to dispose.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsDisposeRuntime(\n          runtime: JsRuntimeHandle): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the current memory usage for a runtime.\n  /// </summary>\n  /// <remarks>\n  ///     Memory usage can be always be retrieved, regardless of whether or not the runtime is active\n  ///     on another thread.\n  /// </remarks>\n  /// <param name=\"runtime\">The runtime whose memory usage is to be retrieved.</param>\n  /// <param name=\"memoryUsage\">The runtime's current memory usage, in bytes.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetRuntimeMemoryUsage(\n          runtime: JsRuntimeHandle;\n          out memoryUsage: size_t): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the current memory limit for a runtime.\n  /// </summary>\n  /// <remarks>\n  ///     The memory limit of a runtime can be always be retrieved, regardless of whether or not the\n  ///     runtime is active on another thread.\n  /// </remarks>\n  /// <param name=\"runtime\">The runtime whose memory limit is to be retrieved.</param>\n  /// <param name=\"memoryLimit\">\n  ///     The runtime's current memory limit, in bytes, or -1 if no limit has been set.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetRuntimeMemoryLimit(\n          runtime: JsRuntimeHandle;\n          out memoryLimit: size_t): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets the current memory limit for a runtime.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     A memory limit will cause any operation which exceeds the limit to fail with an \"out of\n  ///     memory\" error. Setting a runtime's memory limit to -1 means that the runtime has no memory\n  ///     limit. New runtimes  default to having no memory limit. If the new memory limit exceeds\n  ///     current usage, the call will succeed and any future allocations in this runtime will fail\n  ///     until the runtime's memory usage drops below the limit.\n  ///     </para>\n  ///     <para>\n  ///     A runtime's memory limit can be always be set, regardless of whether or not the runtime is\n  ///     active on another thread.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"runtime\">The runtime whose memory limit is to be set.</param>\n  /// <param name=\"memoryLimit\">\n  ///     The new runtime memory limit, in bytes, or -1 for no memory limit.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetRuntimeMemoryLimit(\n          runtime: JsRuntimeHandle;\n          memoryLimit: size_t): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets a memory allocation callback for specified runtime\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     Registering a memory allocation callback will cause the runtime to call back to the host\n  ///     whenever it acquires memory from, or releases memory to, the OS. The callback routine is\n  ///     called before the runtime memory manager allocates a block of memory. The allocation will\n  ///     be rejected if the callback returns false. The runtime memory manager will also invoke the\n  ///     callback routine after freeing a block of memory, as well as after allocation failures.\n  ///     </para>\n  ///     <para>\n  ///     The callback is invoked on the current runtime execution thread, therefore execution is\n  ///     blocked until the callback completes.\n  ///     </para>\n  ///     <para>\n  ///     The return value of the callback is not stored; previously rejected allocations will not\n  ///     prevent the runtime from invoking the callback again later for new memory allocations.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"runtime\">The runtime for which to register the allocation callback.</param>\n  /// <param name=\"callbackState\">\n  ///     User provided state that will be passed back to the callback.\n  /// </param>\n  /// <param name=\"allocationCallback\">\n  ///     Memory allocation callback to be called for memory allocation events.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetRuntimeMemoryAllocationCallback(\n          runtime: JsRuntimeHandle;\n          callbackState: Pointer;\n          allocationCallback: JsMemoryAllocationCallback): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets a callback function that is called by the runtime before garbage collection.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     The callback is invoked on the current runtime execution thread, therefore execution is\n  ///     blocked until the callback completes.\n  ///     </para>\n  ///     <para>\n  ///     The callback can be used by hosts to prepare for garbage collection. For example, by\n  ///     releasing unnecessary references on Chakra objects.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"runtime\">The runtime for which to register the allocation callback.</param>\n  /// <param name=\"callbackState\">\n  ///     User provided state that will be passed back to the callback.\n  /// </param>\n  /// <param name=\"beforeCollectCallback\">The callback function being set.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetRuntimeBeforeCollectCallback(\n          runtime: JsRuntimeHandle;\n          callbackState: Pointer;\n          beforeCollectCallback: JsBeforeCollectCallback): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Adds a reference to a garbage collected object.\n  /// </summary>\n  /// <remarks>\n  ///     This only needs to be called on <c>JsRef</c> handles that are not going to be stored\n  ///     somewhere on the stack. Calling <c>JsAddRef</c> ensures that the object the <c>JsRef</c>\n  ///     refers to will not be freed until <c>JsRelease</c> is called.\n  /// </remarks>\n  /// <param name=\"ref\">The object to add a reference to.</param>\n  /// <param name=\"count\">The object's new reference count (can pass in null).</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsAddRef(\n          ref: JsRef;\n          count: PCardinal): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Releases a reference to a garbage collected object.\n  /// </summary>\n  /// <remarks>\n  ///     Removes a reference to a <c>JsRef</c> handle that was created by <c>JsAddRef</c>.\n  /// </remarks>\n  /// <param name=\"ref\">The object to add a reference to.</param>\n  /// <param name=\"count\">The object's new reference count (can pass in null).</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsRelease(\n          ref: JsRef;\n          count: PCardinal): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets a callback function that is called by the runtime before garbage collection of\n  ///     an object.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     The callback is invoked on the current runtime execution thread, therefore execution is\n  ///     blocked until the callback completes.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"ref\">The object for which to register the callback.</param>\n  /// <param name=\"callbackState\">\n  ///     User provided state that will be passed back to the callback.\n  /// </param>\n  /// <param name=\"objectBeforeCollectCallback\">The callback function being set. Use null to clear\n  ///     previously registered callback.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetObjectBeforeCollectCallback(\n          ref: JsRef;\n          callbackState: Pointer;\n          objectBeforeCollectCallback: JsObjectBeforeCollectCallback): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a script context for running scripts.\n  /// </summary>\n  /// <remarks>\n  ///     Each script context has its own global object that is isolated from all other script\n  ///     contexts.\n  /// </remarks>\n  /// <param name=\"runtime\">The runtime the script context is being created in.</param>\n  /// <param name=\"newContext\">The created script context.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateContext(\n          runtime: JsRuntimeHandle;\n          out newContext: JsContextRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the current script context on the thread.\n  /// </summary>\n  /// <param name=\"currentContext\">\n  ///     The current script context on the thread, null if there is no current script context.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetCurrentContext(\n          out currentContext: JsContextRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets the current script context on the thread.\n  /// </summary>\n  /// <param name=\"context\">The script context to make current.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetCurrentContext(\n          context: JsContextRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the script context that the object belongs to.\n  /// </summary>\n  /// <param name=\"object\">The object to get the context from.</param>\n  /// <param name=\"context\">The context the object belongs to.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetContextOfObject(\n          _object: JsValueRef;\n          out context: JsContextRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the internal data set on JsrtContext.\n  /// </summary>\n  /// <param name=\"context\">The context to get the data from.</param>\n  /// <param name=\"data\">The pointer to the data where data will be returned.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetContextData(\n          context: JsContextRef;\n          out data: Pointer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets the internal data of JsrtContext.\n  /// </summary>\n  /// <param name=\"context\">The context to set the data to.</param>\n  /// <param name=\"data\">The pointer to the data to be set.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetContextData(\n          context: JsContextRef;\n          data: Pointer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the runtime that the context belongs to.\n  /// </summary>\n  /// <param name=\"context\">The context to get the runtime from.</param>\n  /// <param name=\"runtime\">The runtime the context belongs to.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetRuntime(\n          context: JsContextRef;\n          out runtime: JsRuntimeHandle): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Tells the runtime to do any idle processing it need to do.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     If idle processing has been enabled for the current runtime, calling <c>JsIdle</c> will\n  ///     inform the current runtime that the host is idle and that the runtime can perform\n  ///     memory cleanup tasks.\n  ///     </para>\n  ///     <para>\n  ///     <c>JsIdle</c> can also return the number of system ticks until there will be more idle work\n  ///     for the runtime to do. Calling <c>JsIdle</c> before this number of ticks has passed will do\n  ///     no work.\n  ///     </para>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"nextIdleTick\">\n  ///     The next system tick when there will be more idle work to do. Can be null. Returns the\n  ///     maximum number of ticks if there no upcoming idle work to do.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsIdle(\n          nextIdleTick: PCardinal): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the symbol associated with the property ID.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"propertyId\">The property ID to get the symbol of.</param>\n  /// <param name=\"symbol\">The symbol associated with the property ID.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetSymbolFromPropertyId(\n          propertyId: JsPropertyIdRef;\n          out symbol: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the type of property\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"propertyId\">The property ID to get the type of.</param>\n  /// <param name=\"propertyIdType\">The JsPropertyIdType of the given property ID</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetPropertyIdType(\n          propertyId: JsPropertyIdRef;\n          out propertyIdType: JsPropertyIdType): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the property ID associated with the symbol.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     Property IDs are specific to a context and cannot be used across contexts.\n  ///     </para>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"symbol\">\n  ///     The symbol whose property ID is being retrieved.\n  /// </param>\n  /// <param name=\"propertyId\">The property ID for the given symbol.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetPropertyIdFromSymbol(\n          symbol: JsValueRef;\n          out propertyId: JsPropertyIdRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a Javascript symbol.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"description\">The string description of the symbol. Can be null.</param>\n  /// <param name=\"result\">The new symbol.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateSymbol(\n          description: JsValueRef;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the list of all symbol properties on the object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object from which to get the property symbols.</param>\n  /// <param name=\"propertySymbols\">An array of property symbols.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetOwnPropertySymbols(\n          _object: JsValueRef;\n          out propertySymbols: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the value of <c>undefined</c> in the current script context.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"undefinedValue\">The <c>undefined</c> value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetUndefinedValue(\n          out undefinedValue: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the value of <c>null</c> in the current script context.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"nullValue\">The <c>null</c> value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetNullValue(\n          out nullValue: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the value of <c>true</c> in the current script context.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"trueValue\">The <c>true</c> value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetTrueValue(\n          out trueValue: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the value of <c>false</c> in the current script context.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"falseValue\">The <c>false</c> value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetFalseValue(\n          out falseValue: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a Boolean value from a <c>bool</c> value.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"value\">The value to be converted.</param>\n  /// <param name=\"booleanValue\">The converted value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsBoolToBoolean(\n          value: bool;\n          out booleanValue: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Retrieves the <c>bool</c> value of a Boolean value.\n  /// </summary>\n  /// <param name=\"value\">The value to be converted.</param>\n  /// <param name=\"boolValue\">The converted value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsBooleanToBool(\n          value: JsValueRef;\n          out boolValue: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Converts the value to Boolean using standard JavaScript semantics.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"value\">The value to be converted.</param>\n  /// <param name=\"booleanValue\">The converted value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsConvertValueToBoolean(\n          value: JsValueRef;\n          out booleanValue: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the JavaScript type of a JsValueRef.\n  /// </summary>\n  /// <param name=\"value\">The value whose type is to be returned.</param>\n  /// <param name=\"type\">The type of the value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetValueType(\n          value: JsValueRef;\n          out _type: JsValueType): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a number value from a <c>double</c> value.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"doubleValue\">The <c>double</c> to convert to a number value.</param>\n  /// <param name=\"value\">The new number value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsDoubleToNumber(\n          doubleValue: Double;\n          out value: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a number value from an <c>int</c> value.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"intValue\">The <c>int</c> to convert to a number value.</param>\n  /// <param name=\"value\">The new number value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsIntToNumber(\n          intValue: Integer;\n          out value: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Retrieves the <c>double</c> value of a number value.\n  /// </summary>\n  /// <remarks>\n  ///     This function retrieves the value of a number value. It will fail with\n  ///     <c>JsErrorInvalidArgument</c> if the type of the value is not number.\n  /// </remarks>\n  /// <param name=\"value\">The number value to convert to a <c>double</c> value.</param>\n  /// <param name=\"doubleValue\">The <c>double</c> value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsNumberToDouble(\n          value: JsValueRef;\n          out doubleValue: Double): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Retrieves the <c>int</c> value of a number value.\n  /// </summary>\n  /// <remarks>\n  ///     This function retrieves the value of a number value and converts to an <c>int</c> value.\n  ///     It will fail with <c>JsErrorInvalidArgument</c> if the type of the value is not number.\n  /// </remarks>\n  /// <param name=\"value\">The number value to convert to an <c>int</c> value.</param>\n  /// <param name=\"intValue\">The <c>int</c> value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsNumberToInt(\n          value: JsValueRef;\n          out intValue: Integer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Converts the value to number using standard JavaScript semantics.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"value\">The value to be converted.</param>\n  /// <param name=\"numberValue\">The converted value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsConvertValueToNumber(\n          value: JsValueRef;\n          out numberValue: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the length of a string value.\n  /// </summary>\n  /// <param name=\"stringValue\">The string value to get the length of.</param>\n  /// <param name=\"length\">The length of the string.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetStringLength(\n          stringValue: JsValueRef;\n          out length: Integer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Converts the value to string using standard JavaScript semantics.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"value\">The value to be converted.</param>\n  /// <param name=\"stringValue\">The converted value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsConvertValueToString(\n          value: JsValueRef;\n          out stringValue: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the global object in the current script context.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"globalObject\">The global object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetGlobalObject(\n          out globalObject: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The new object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateObject(\n          out _object: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new object that stores some external data.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"data\">External data that the object will represent. May be null.</param>\n  /// <param name=\"finalizeCallback\">\n  ///     A callback for when the object is finalized. May be null.\n  /// </param>\n  /// <param name=\"object\">The new object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateExternalObject(\n          data: Pointer;\n          finalizeCallback: JsFinalizeCallback;\n          out _object: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Converts the value to object using standard JavaScript semantics.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"value\">The value to be converted.</param>\n  /// <param name=\"object\">The converted value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsConvertValueToObject(\n          value: JsValueRef;\n          out _object: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Returns the prototype of an object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object whose prototype is to be returned.</param>\n  /// <param name=\"prototypeObject\">The object's prototype.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetPrototype(\n          _object: JsValueRef;\n          out prototypeObject: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets the prototype of an object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object whose prototype is to be changed.</param>\n  /// <param name=\"prototypeObject\">The object's new prototype.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetPrototype(\n          _object: JsValueRef;\n          prototypeObject: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Performs JavaScript \"instanceof\" operator test.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object to test.</param>\n  /// <param name=\"constructor\">The constructor function to test against.</param>\n  /// <param name=\"result\">Whether \"object instanceof constructor\" is true.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsInstanceOf(\n          _object: JsValueRef;\n          constr: JsValueRef;\n          out result: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Returns a value that indicates whether an object is extensible or not.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object to test.</param>\n  /// <param name=\"value\">Whether the object is extensible or not.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetExtensionAllowed(\n          _object: JsValueRef;\n          out value: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Makes an object non-extensible.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object to make non-extensible.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsPreventExtension(\n          _object: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets an object's property.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that contains the property.</param>\n  /// <param name=\"propertyId\">The ID of the property.</param>\n  /// <param name=\"value\">The value of the property.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetProperty(\n          _object: JsValueRef;\n          propertyId: JsPropertyIdRef;\n          out value: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets a property descriptor for an object's own property.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that has the property.</param>\n  /// <param name=\"propertyId\">The ID of the property.</param>\n  /// <param name=\"propertyDescriptor\">The property descriptor.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetOwnPropertyDescriptor(\n          _object: JsValueRef;\n          propertyId: JsPropertyIdRef;\n          out propertyDescriptor: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the list of all properties on the object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object from which to get the property names.</param>\n  /// <param name=\"propertyNames\">An array of property names.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetOwnPropertyNames(\n          _object: JsValueRef;\n          out propertyNames: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Puts an object's property.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that contains the property.</param>\n  /// <param name=\"propertyId\">The ID of the property.</param>\n  /// <param name=\"value\">The new value of the property.</param>\n  /// <param name=\"useStrictRules\">The property set should follow strict mode rules.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetProperty(\n          _object: JsValueRef;\n          propertyId: JsPropertyIdRef;\n          value: JsValueRef;\n          useStrictRules: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Determines whether an object has a property.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that may contain the property.</param>\n  /// <param name=\"propertyId\">The ID of the property.</param>\n  /// <param name=\"hasProperty\">Whether the object (or a prototype) has the property.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsHasProperty(\n          _object: JsValueRef;\n          propertyId: JsPropertyIdRef;\n          out hasProperty: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Deletes an object's property.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that contains the property.</param>\n  /// <param name=\"propertyId\">The ID of the property.</param>\n  /// <param name=\"useStrictRules\">The property set should follow strict mode rules.</param>\n  /// <param name=\"result\">Whether the property was deleted.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsDeleteProperty(\n          _object: JsValueRef;\n          propertyId: JsPropertyIdRef;\n          useStrictRules: bool;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Defines a new object's own property from a property descriptor.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that has the property.</param>\n  /// <param name=\"propertyId\">The ID of the property.</param>\n  /// <param name=\"propertyDescriptor\">The property descriptor.</param>\n  /// <param name=\"result\">Whether the property was defined.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsDefineProperty(\n          _object: JsValueRef;\n          propertyId: JsPropertyIdRef;\n          propertyDescriptor: JsValueRef;\n          out result: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Tests whether an object has a value at the specified index.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object to operate on.</param>\n  /// <param name=\"index\">The index to test.</param>\n  /// <param name=\"result\">Whether the object has a value at the specified index.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsHasIndexedProperty(\n          _object: JsValueRef;\n          index: JsValueRef;\n          out result: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Retrieve the value at the specified index of an object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object to operate on.</param>\n  /// <param name=\"index\">The index to retrieve.</param>\n  /// <param name=\"result\">The retrieved value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetIndexedProperty(\n          _object: JsValueRef;\n          index: JsValueRef;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Set the value at the specified index of an object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object to operate on.</param>\n  /// <param name=\"index\">The index to set.</param>\n  /// <param name=\"value\">The value to set.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetIndexedProperty(\n          _object: JsValueRef;\n          index: JsValueRef;\n          value: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Delete the value at the specified index of an object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object to operate on.</param>\n  /// <param name=\"index\">The index to delete.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsDeleteIndexedProperty(\n          _object: JsValueRef;\n          index: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Determines whether an object has its indexed properties in external data.\n  /// </summary>\n  /// <param name=\"object\">The object.</param>\n  /// <param name=\"value\">Whether the object has its indexed properties in external data.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsHasIndexedPropertiesExternalData(\n          _object: JsValueRef;\n          out value: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Retrieves an object's indexed properties external data information.\n  /// </summary>\n  /// <param name=\"object\">The object.</param>\n  /// <param name=\"data\">The external data back store for the object's indexed properties.</param>\n  /// <param name=\"arrayType\">The array element type in external data.</param>\n  /// <param name=\"elementLength\">The number of array elements in external data.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetIndexedPropertiesExternalData(\n          _object: JsValueRef;\n          out data: Pointer;\n          out arrayType: JsTypedArrayType;\n          out elementLength: Cardinal): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets an object's indexed properties to external data. The external data will be used as back\n  ///     store for the object's indexed properties and accessed like a typed array.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object to operate on.</param>\n  /// <param name=\"data\">The external data to be used as back store for the object's indexed properties.</param>\n  /// <param name=\"arrayType\">The array element type in external data.</param>\n  /// <param name=\"elementLength\">The number of array elements in external data.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetIndexedPropertiesToExternalData(\n          _object: JsValueRef;\n          data: Pointer;\n          arrayType: JsTypedArrayType;\n          elementLength: Cardinal): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Compare two JavaScript values for equality.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     This function is equivalent to the <c>==</c> operator in Javascript.\n  ///     </para>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"object1\">The first object to compare.</param>\n  /// <param name=\"object2\">The second object to compare.</param>\n  /// <param name=\"result\">Whether the values are equal.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsEquals(\n          object1: JsValueRef;\n          object2: JsValueRef;\n          out result: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Compare two JavaScript values for strict equality.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     This function is equivalent to the <c>===</c> operator in Javascript.\n  ///     </para>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"object1\">The first object to compare.</param>\n  /// <param name=\"object2\">The second object to compare.</param>\n  /// <param name=\"result\">Whether the values are strictly equal.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsStrictEquals(\n          object1: JsValueRef;\n          object2: JsValueRef;\n          out result: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Determines whether an object is an external object.\n  /// </summary>\n  /// <param name=\"object\">The object.</param>\n  /// <param name=\"value\">Whether the object is an external object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsHasExternalData(\n          _object: JsValueRef;\n          out value: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Retrieves the data from an external object.\n  /// </summary>\n  /// <param name=\"object\">The external object.</param>\n  /// <param name=\"externalData\">\n  ///     The external data stored in the object. Can be null if no external data is stored in the\n  ///     object.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetExternalData(\n          _object: JsValueRef;\n          out externalData: Pointer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets the external data on an external object.\n  /// </summary>\n  /// <param name=\"object\">The external object.</param>\n  /// <param name=\"externalData\">\n  ///     The external data to be stored in the object. Can be null if no external data is\n  ///     to be stored in the object.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetExternalData(\n          _object: JsValueRef;\n          externalData: Pointer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a Javascript array object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"length\">The initial length of the array.</param>\n  /// <param name=\"result\">The new array object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateArray(\n          length: Cardinal;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a Javascript ArrayBuffer object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"byteLength\">\n  ///     The number of bytes in the ArrayBuffer.\n  /// </param>\n  /// <param name=\"result\">The new ArrayBuffer object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateArrayBuffer(\n          byteLength: Cardinal;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a Javascript ArrayBuffer object to access external memory.\n  /// </summary>\n  /// <remarks>Requires an active script context.</remarks>\n  /// <param name=\"data\">A pointer to the external memory.</param>\n  /// <param name=\"byteLength\">The number of bytes in the external memory.</param>\n  /// <param name=\"finalizeCallback\">A callback for when the object is finalized. May be null.</param>\n  /// <param name=\"callbackState\">User provided state that will be passed back to finalizeCallback.</param>\n  /// <param name=\"result\">The new ArrayBuffer object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateExternalArrayBuffer(\n          data: Pointer;\n          byteLength: Cardinal;\n          finalizeCallback: JsFinalizeCallback;\n          callbackState: Pointer;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a Javascript typed array object.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     The <c>baseArray</c> can be an <c>ArrayBuffer</c>, another typed array, or a JavaScript\n  ///     <c>Array</c>. The returned typed array will use the baseArray if it is an ArrayBuffer, or\n  ///     otherwise create and use a copy of the underlying source array.\n  ///     </para>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"arrayType\">The type of the array to create.</param>\n  /// <param name=\"baseArray\">\n  ///     The base array of the new array. Use <c>JS_INVALID_REFERENCE</c> if no base array.\n  /// </param>\n  /// <param name=\"byteOffset\">\n  ///     The offset in bytes from the start of baseArray (ArrayBuffer) for result typed array to reference.\n  ///     Only applicable when baseArray is an ArrayBuffer object. Must be 0 otherwise.\n  /// </param>\n  /// <param name=\"elementLength\">\n  ///     The number of elements in the array. Only applicable when creating a new typed array without\n  ///     baseArray (baseArray is <c>JS_INVALID_REFERENCE</c>) or when baseArray is an ArrayBuffer object.\n  ///     Must be 0 otherwise.\n  /// </param>\n  /// <param name=\"result\">The new typed array object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateTypedArray(\n          arrayType: JsTypedArrayType;\n          baseArray: JsValueRef;\n          byteOffset: Cardinal;\n          elementLength: Cardinal;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a Javascript DataView object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"arrayBuffer\">\n  ///     An existing ArrayBuffer object to use as the storage for the result DataView object.\n  /// </param>\n  /// <param name=\"byteOffset\">\n  ///     The offset in bytes from the start of arrayBuffer for result DataView to reference.\n  /// </param>\n  /// <param name=\"byteLength\">\n  ///     The number of bytes in the ArrayBuffer for result DataView to reference.\n  /// </param>\n  /// <param name=\"result\">The new DataView object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateDataView(\n          arrayBuffer: JsValueRef;\n          byteOffset: Cardinal;\n          byteLength: Cardinal;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Obtains frequently used properties of a typed array.\n  /// </summary>\n  /// <param name=\"typedArray\">The typed array instance.</param>\n  /// <param name=\"arrayType\">The type of the array.</param>\n  /// <param name=\"arrayBuffer\">The ArrayBuffer backstore of the array.</param>\n  /// <param name=\"byteOffset\">The offset in bytes from the start of arrayBuffer referenced by the array.</param>\n  /// <param name=\"byteLength\">The number of bytes in the array.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetTypedArrayInfo(\n          typedArray: JsValueRef;\n          arrayType: PJsTypedArrayType;\n          arrayBuffer: PJsValueRef;\n          byteOffset: PCardinal;\n          byteLength: PCardinal): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Obtains the underlying memory storage used by an <c>ArrayBuffer</c>.\n  /// </summary>\n  /// <param name=\"arrayBuffer\">The ArrayBuffer instance.</param>\n  /// <param name=\"buffer\">\n  ///     The ArrayBuffer's buffer. The lifetime of the buffer returned is the same as the lifetime of the\n  ///     the ArrayBuffer. The buffer pointer does not count as a reference to the ArrayBuffer for the purpose\n  ///     of garbage collection.\n  /// </param>\n  /// <param name=\"bufferLength\">The number of bytes in the buffer.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetArrayBufferStorage(\n          arrayBuffer: JsValueRef;\n          out buffer: ChakraBytePtr;\n          out bufferLength: Cardinal): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Obtains the underlying memory storage used by a typed array.\n  /// </summary>\n  /// <param name=\"typedArray\">The typed array instance.</param>\n  /// <param name=\"buffer\">\n  ///     The array's buffer. The lifetime of the buffer returned is the same as the lifetime of the\n  ///     the array. The buffer pointer does not count as a reference to the array for the purpose\n  ///     of garbage collection.\n  /// </param>\n  /// <param name=\"bufferLength\">The number of bytes in the buffer.</param>\n  /// <param name=\"arrayType\">The type of the array.</param>\n  /// <param name=\"elementSize\">\n  ///     The size of an element of the array.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetTypedArrayStorage(\n          typedArray: JsValueRef;\n          out buffer: ChakraBytePtr;\n          out bufferLength: Cardinal;\n          out arrayType: JsTypedArrayType;\n          out elementSize: Integer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Obtains the underlying memory storage used by a DataView.\n  /// </summary>\n  /// <param name=\"dataView\">The DataView instance.</param>\n  /// <param name=\"buffer\">\n  ///     The DataView's buffer. The lifetime of the buffer returned is the same as the lifetime of the\n  ///     the DataView. The buffer pointer does not count as a reference to the DataView for the purpose\n  ///     of garbage collection.\n  /// </param>\n  /// <param name=\"bufferLength\">The number of bytes in the buffer.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetDataViewStorage(\n          dataView: JsValueRef;\n          out buffer: ChakraBytePtr;\n          out bufferLength: Cardinal): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Invokes a function.\n  /// </summary>\n  /// <remarks>\n  ///     Requires thisArg as first argument of arguments.\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"function\">The function to invoke.</param>\n  /// <param name=\"arguments\">The arguments to the call.</param>\n  /// <param name=\"argumentCount\">The number of arguments being passed in to the function.</param>\n  /// <param name=\"result\">The value returned from the function invocation, if any.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCallFunction(\n          _function: JsValueRef;\n          arguments: PJsValueRef;\n          argumentCount: Word;\n          result: PJsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Invokes a function as a constructor.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"function\">The function to invoke as a constructor.</param>\n  /// <param name=\"arguments\">The arguments to the call.</param>\n  /// <param name=\"argumentCount\">The number of arguments being passed in to the function.</param>\n  /// <param name=\"result\">The value returned from the function invocation.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsConstructObject(\n          _function: JsValueRef;\n          arguments: PJsValueRef;\n          argumentCount: Word;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new JavaScript function.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"nativeFunction\">The method to call when the function is invoked.</param>\n  /// <param name=\"callbackState\">\n  ///     User provided state that will be passed back to the callback.\n  /// </param>\n  /// <param name=\"function\">The new function object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateFunction(\n          nativeFunction: JsNativeFunction;\n          callbackState: Pointer;\n          out _function: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new JavaScript function with name.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"name\">The name of this function that will be used for diagnostics and stringification purposes.</param>\n  /// <param name=\"nativeFunction\">The method to call when the function is invoked.</param>\n  /// <param name=\"callbackState\">\n  ///     User provided state that will be passed back to the callback.\n  /// </param>\n  /// <param name=\"function\">The new function object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateNamedFunction(\n          name: JsValueRef;\n          nativeFunction: JsNativeFunction;\n          callbackState: Pointer;\n          out _function: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new JavaScript error object\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"message\">Message for the error object.</param>\n  /// <param name=\"error\">The new error object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateError(\n          _message: JsValueRef;\n          out error: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new JavaScript RangeError error object\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"message\">Message for the error object.</param>\n  /// <param name=\"error\">The new error object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateRangeError(\n          _message: JsValueRef;\n          out error: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new JavaScript ReferenceError error object\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"message\">Message for the error object.</param>\n  /// <param name=\"error\">The new error object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateReferenceError(\n          _message: JsValueRef;\n          out error: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new JavaScript SyntaxError error object\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"message\">Message for the error object.</param>\n  /// <param name=\"error\">The new error object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateSyntaxError(\n          _message: JsValueRef;\n          out error: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new JavaScript TypeError error object\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"message\">Message for the error object.</param>\n  /// <param name=\"error\">The new error object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateTypeError(\n          _message: JsValueRef;\n          out error: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new JavaScript URIError error object\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"message\">Message for the error object.</param>\n  /// <param name=\"error\">The new error object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateURIError(\n          _message: JsValueRef;\n          out error: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Determines whether the runtime of the current context is in an exception state.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     If a call into the runtime results in an exception (either as the result of running a\n  ///     script or due to something like a conversion failure), the runtime is placed into an\n  ///     \"exception state.\" All calls into any context created by the runtime (except for the\n  ///     exception APIs) will fail with <c>JsErrorInExceptionState</c> until the exception is\n  ///     cleared.\n  ///     </para>\n  ///     <para>\n  ///     If the runtime of the current context is in the exception state when a callback returns\n  ///     into the engine, the engine will automatically rethrow the exception.\n  ///     </para>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"hasException\">\n  ///     Whether the runtime of the current context is in the exception state.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsHasException(\n          out hasException: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Returns the exception that caused the runtime of the current context to be in the\n  ///     exception state and resets the exception state for that runtime.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     If the runtime of the current context is not in an exception state, this API will return\n  ///     <c>JsErrorInvalidArgument</c>. If the runtime is disabled, this will return an exception\n  ///     indicating that the script was terminated, but it will not clear the exception (the\n  ///     exception will be cleared if the runtime is re-enabled using\n  ///     <c>JsEnableRuntimeExecution</c>).\n  ///     </para>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"exception\">The exception for the runtime of the current context.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetAndClearException(\n          out exception: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets the runtime of the current context to an exception state.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     If the runtime of the current context is already in an exception state, this API will\n  ///     return <c>JsErrorInExceptionState</c>.\n  ///     </para>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"exception\">\n  ///     The JavaScript exception to set for the runtime of the current context.\n  /// </param>\n  /// <returns>\n  ///     JsNoError if the engine was set into an exception state, a failure code otherwise.\n  /// </returns>\n  function JsSetException(\n          exception: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Suspends script execution and terminates any running scripts in a runtime.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     Calls to a suspended runtime will fail until <c>JsEnableRuntimeExecution</c> is called.\n  ///     </para>\n  ///     <para>\n  ///     This API does not have to be called on the thread the runtime is active on. Although the\n  ///     runtime will be set into a suspended state, an executing script may not be suspended\n  ///     immediately; a running script will be terminated with an uncatchable exception as soon as\n  ///     possible.\n  ///     </para>\n  ///     <para>\n  ///     Suspending execution in a runtime that is already suspended is a no-op.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"runtime\">The runtime to be suspended.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsDisableRuntimeExecution(\n          runtime: JsRuntimeHandle): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Enables script execution in a runtime.\n  /// </summary>\n  /// <remarks>\n  ///     Enabling script execution in a runtime that already has script execution enabled is a\n  ///     no-op.\n  /// </remarks>\n  /// <param name=\"runtime\">The runtime to be enabled.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsEnableRuntimeExecution(\n          runtime: JsRuntimeHandle): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Returns a value that indicates whether script execution is disabled in the runtime.\n  /// </summary>\n  /// <param name=\"runtime\">Specifies the runtime to check if execution is disabled.</param>\n  /// <param name=\"isDisabled\">If execution is disabled, <c>true</c>, <c>false</c> otherwise.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsIsRuntimeExecutionDisabled(\n          runtime: JsRuntimeHandle;\n          out isDisabled: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets a promise continuation callback function that is called by the context when a task\n  ///     needs to be queued for future execution\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"promiseContinuationCallback\">The callback function being set.</param>\n  /// <param name=\"callbackState\">\n  ///     User provided state that will be passed back to the callback.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetPromiseContinuationCallback(\n          promiseContinuationCallback: JsPromiseContinuationCallback;\n          callbackState: Pointer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\nimplementation\n\n{$ifdef MSWINDOWS}\nconst\n  chakracore = 'chakracore.dll';\n{$endif}\n\n{$ifdef DARWIN}\nconst\n  chakracore = 'libChakraCore.dylib';\n{$endif}\n\n{$ifdef LINUX}\nconst\n  chakracore = 'libChakraCore.so';\n{$endif}\n\nfunction JsCreateRuntime; external chakracore;\nfunction JsCollectGarbage; external chakracore;\nfunction JsDisposeRuntime; external chakracore;\nfunction JsGetRuntimeMemoryUsage; external chakracore;\nfunction JsGetRuntimeMemoryLimit; external chakracore;\nfunction JsSetRuntimeMemoryLimit; external chakracore;\nfunction JsSetRuntimeMemoryAllocationCallback; external chakracore;\nfunction JsSetRuntimeBeforeCollectCallback; external chakracore;\nfunction JsAddRef; external chakracore;\nfunction JsRelease; external chakracore;\nfunction JsSetObjectBeforeCollectCallback; external chakracore;\nfunction JsCreateContext; external chakracore;\nfunction JsGetCurrentContext; external chakracore;\nfunction JsSetCurrentContext; external chakracore;\nfunction JsGetContextOfObject; external chakracore;\nfunction JsGetContextData; external chakracore;\nfunction JsSetContextData; external chakracore;\nfunction JsGetRuntime; external chakracore;\nfunction JsIdle; external chakracore;\nfunction JsGetSymbolFromPropertyId; external chakracore;\nfunction JsGetPropertyIdType; external chakracore;\nfunction JsGetPropertyIdFromSymbol; external chakracore;\nfunction JsCreateSymbol; external chakracore;\nfunction JsGetOwnPropertySymbols; external chakracore;\nfunction JsGetUndefinedValue; external chakracore;\nfunction JsGetNullValue; external chakracore;\nfunction JsGetTrueValue; external chakracore;\nfunction JsGetFalseValue; external chakracore;\nfunction JsBoolToBoolean; external chakracore;\nfunction JsBooleanToBool; external chakracore;\nfunction JsConvertValueToBoolean; external chakracore;\nfunction JsGetValueType; external chakracore;\nfunction JsDoubleToNumber; external chakracore;\nfunction JsIntToNumber; external chakracore;\nfunction JsNumberToDouble; external chakracore;\nfunction JsNumberToInt; external chakracore;\nfunction JsConvertValueToNumber; external chakracore;\nfunction JsGetStringLength; external chakracore;\nfunction JsConvertValueToString; external chakracore;\nfunction JsGetGlobalObject; external chakracore;\nfunction JsCreateObject; external chakracore;\nfunction JsCreateExternalObject; external chakracore;\nfunction JsConvertValueToObject; external chakracore;\nfunction JsGetPrototype; external chakracore;\nfunction JsSetPrototype; external chakracore;\nfunction JsInstanceOf; external chakracore;\nfunction JsGetExtensionAllowed; external chakracore;\nfunction JsPreventExtension; external chakracore;\nfunction JsGetProperty; external chakracore;\nfunction JsGetOwnPropertyDescriptor; external chakracore;\nfunction JsGetOwnPropertyNames; external chakracore;\nfunction JsSetProperty; external chakracore;\nfunction JsHasProperty; external chakracore;\nfunction JsDeleteProperty; external chakracore;\nfunction JsDefineProperty; external chakracore;\nfunction JsHasIndexedProperty; external chakracore;\nfunction JsGetIndexedProperty; external chakracore;\nfunction JsSetIndexedProperty; external chakracore;\nfunction JsDeleteIndexedProperty; external chakracore;\nfunction JsHasIndexedPropertiesExternalData; external chakracore;\nfunction JsGetIndexedPropertiesExternalData; external chakracore;\nfunction JsSetIndexedPropertiesToExternalData; external chakracore;\nfunction JsEquals; external chakracore;\nfunction JsStrictEquals; external chakracore;\nfunction JsHasExternalData; external chakracore;\nfunction JsGetExternalData; external chakracore;\nfunction JsSetExternalData; external chakracore;\nfunction JsCreateArray; external chakracore;\nfunction JsCreateArrayBuffer; external chakracore;\nfunction JsCreateExternalArrayBuffer; external chakracore;\nfunction JsCreateTypedArray; external chakracore;\nfunction JsCreateDataView; external chakracore;\nfunction JsGetTypedArrayInfo; external chakracore;\nfunction JsGetArrayBufferStorage; external chakracore;\nfunction JsGetTypedArrayStorage; external chakracore;\nfunction JsGetDataViewStorage; external chakracore;\nfunction JsCallFunction; external chakracore;\nfunction JsConstructObject; external chakracore;\nfunction JsCreateFunction; external chakracore;\nfunction JsCreateNamedFunction; external chakracore;\nfunction JsCreateError; external chakracore;\nfunction JsCreateRangeError; external chakracore;\nfunction JsCreateReferenceError; external chakracore;\nfunction JsCreateSyntaxError; external chakracore;\nfunction JsCreateTypeError; external chakracore;\nfunction JsCreateURIError; external chakracore;\nfunction JsHasException; external chakracore;\nfunction JsGetAndClearException; external chakracore;\nfunction JsSetException; external chakracore;\nfunction JsDisableRuntimeExecution; external chakracore;\nfunction JsEnableRuntimeExecution; external chakracore;\nfunction JsIsRuntimeExecutionDisabled; external chakracore;\nfunction JsSetPromiseContinuationCallback; external chakracore;\n\nend.\n"
  },
  {
    "path": "src/ChakraCore.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\n//-------------------------------------------------------------------------------------------------------\n// Copyright (C) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n//-------------------------------------------------------------------------------------------------------\n/// \\mainpage Chakra Hosting API Reference\n///\n/// Chakra is Microsoft's JavaScript engine. It is an integral part of Internet Explorer but can\n/// also be hosted independently by other applications. This reference describes the APIs available\n/// to applications to host Chakra.\n///\n\n/// \\file\n/// \\brief The Chakra Core hosting API.\n///\n/// This file contains a flat C API layer. This is the API exported by ChakraCore.dll.\n\nunit ChakraCore;\n\n{$include common.inc}\n\n{$minenumsize 4}\n\ninterface\n\nuses\n  Compat, ChakraCommon;\n\ntype\n  /// <summary>\n  ///     A reference to an ES module.\n  /// </summary>\n  /// <remarks>\n  ///     A module record represents an ES module.\n  /// </remarks>\n  JsModuleRecord = Pointer;\n\n  /// <summary>\n  ///     A reference to an object owned by the SharedArrayBuffer.\n  /// </summary>\n  /// <remarks>\n  ///     This represents SharedContents which is heap allocated object, it can be passed through\n  ///     different runtimes to share the underlying buffer.\n  /// </remarks>\n  JsSharedArrayBufferContentHandle = Pointer;\n\n  /// <summary>\n  ///     Flags for parsing a module.\n  /// </summary>\n  JsParseModuleSourceFlags = (\n    /// <summary>\n    ///     Module source is UTF16.\n    /// </summary>\n    JsParseModuleSourceFlags_DataIsUTF16LE = $00000000,\n    /// <summary>\n    ///     Module source is UTF8.\n    /// </summary>\n    JsParseModuleSourceFlags_DataIsUTF8 = $00000001\n  );\n\n  /// <summary>\n  ///     The types of host info that can be set on a module record with JsSetModuleHostInfo.\n  /// </summary>\n  /// <remarks>\n  ///     For more information see JsSetModuleHostInfo.\n  /// </remarks>\n  JsModuleHostInfoKind = (\n    /// <summary>\n    ///     An exception object - e.g. if the module file cannot be found.\n    /// </summary>\n    JsModuleHostInfo_Exception = $01,\n    /// <summary>\n    ///     Host defined info.\n    /// </summary>\n    JsModuleHostInfo_HostDefined = $02,\n    /// <summary>\n    ///     Callback for receiving notification when module is ready.\n    /// </summary>\n    JsModuleHostInfo_NotifyModuleReadyCallback = $03,\n    /// <summary>\n    ///     Callback for receiving notification to fetch a dependent module.\n    /// </summary>\n    JsModuleHostInfo_FetchImportedModuleCallback = $04,\n    /// <summary>\n    ///     Callback for receiving notification for calls to ```import()```\n    /// </summary>\n    JsModuleHostInfo_FetchImportedModuleFromScriptCallback = $05,\n    /// <summary>\n    ///     URL for use in error stack traces and debugging.\n    /// </summary>\n    JsModuleHostInfo_Url = $06\n  );\n\n  /// <summary>\n  ///     The possible states for a Promise object.\n  /// </summary>\n  JsPromiseState = (\n    JsPromiseStatePending = $0,\n    JsPromiseStateFulfilled = $1,\n    JsPromiseStateRejected = $2\n  );\n\n  /// <summary>\n  ///     User implemented callback to fetch additional imported modules in ES modules.\n  /// </summary>\n  /// <remarks>\n  ///     The callback is invoked on the current runtime execution thread, therefore execution is blocked until\n  ///     the callback completes. Notify the host to fetch the dependent module. This is the \"import\" part\n  ///     before HostResolveImportedModule in ES6 spec. This notifies the host that the referencing module has\n  ///     the specified module dependency, and the host needs to retrieve the module back.\n  ///\n  ///     Callback should:\n  ///     1. Check if the requested module has been requested before - if yes return the existing\n  ///         module record\n  ///     2. If no create and initialize a new module record with JsInitializeModuleRecord to\n  ///         return and schedule a call to JsParseModuleSource for the new record.\n  /// </remarks>\n  /// <param name=\"referencingModule\">The referencing module that is requesting the dependent module.</param>\n  /// <param name=\"specifier\">The specifier coming from the module source code.</param>\n  /// <param name=\"dependentModuleRecord\">The ModuleRecord of the dependent module. If the module was requested\n  ///                                     before from other source, return the existing ModuleRecord, otherwise\n  ///                                     return a newly created ModuleRecord.</param>\n  /// <returns>\n  ///     Returns a <c>JsNoError</c> if the operation succeeded an error code otherwise.\n  /// </returns>\n  FetchImportedModuleCallBack = function(referencingModule: JsModuleRecord; specifier: JsValueRef;\n      out dependentModuleRecord: JsModuleRecord): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     User implemented callback to fetch imported modules dynamically in scripts.\n  /// </summary>\n  /// <remarks>\n  ///     The callback is invoked on the current runtime execution thread, therefore execution is blocked untill\n  ///     the callback completes. Notify the host to fetch the dependent module. This is used for the dynamic\n  ///     import() syntax.\n  ///\n  ///     Callback should:\n  ///     1. Check if the requested module has been requested before - if yes return the existing module record\n  ///     2. If no create and initialize a new module record with JsInitializeModuleRecord to return and\n  ///         schedule a call to JsParseModuleSource for the new record.\n  /// </remarks>\n  /// <param name=\"dwReferencingSourceContext\">The referencing script context that calls import()</param>\n  /// <param name=\"specifier\">The specifier provided to the import() call.</param>\n  /// <param name=\"dependentModuleRecord\">The ModuleRecord of the dependent module. If the module was requested\n  ///                                     before from other source, return the existing ModuleRecord, otherwise\n  ///                                     return a newly created ModuleRecord.</param>\n  /// <returns>\n  ///     Returns <c>JsNoError</c> if the operation succeeded or an error code otherwise.\n  /// </returns>\n  FetchImportedModuleFromScriptCallBack = function(dwReferencingSourceContext: JsSourceContext; specifier: JsValueRef;\n    out dependentModuleRecord: JsModuleRecord): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     User implemented callback to get notification when the module is ready.\n  /// </summary>\n  /// <remarks>\n  ///     The callback is invoked on the current runtime execution thread, therefore execution is blocked until the\n  ///     callback completes. This callback should schedule a call to JsEvaluateModule to run the module that has been loaded.\n  /// </remarks>\n  /// <param name=\"referencingModule\">The referencing module that has finished running ModuleDeclarationInstantiation step.</param>\n  /// <param name=\"exceptionVar\">If nullptr, the module is successfully initialized and host should queue the execution job\n  ///                            otherwise it's the exception object.</param>\n  /// <returns>\n  ///     Returns a JsErrorCode - note, the return value is ignored.\n  /// </returns>\n  NotifyModuleReadyCallback = function(referencingModule: JsModuleRecord; exceptionVar: JsValueRef): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     A structure containing information about a native function callback.\n  /// </summary>\n  PJsNativeFunctionInfo = ^JsNativeFunctionInfo;\n  JsNativeFunctionInfo = record\n    thisArg: JsValueRef;\n    newTargetArg: JsValueRef;\n    isConstructCall: bool;\n  end;\n\n  /// <summary>\n  ///     A function callback.\n  /// </summary>\n  /// <param name=\"callee\">\n  ///     A function object that represents the function being invoked.\n  /// </param>\n  /// <param name=\"arguments\">The arguments to the call.</param>\n  /// <param name=\"argumentCount\">The number of arguments.</param>\n  /// <param name=\"info\">Additional information about this function call.</param>\n  /// <param name=\"callbackState\">\n  ///     The state passed to <c>JsCreateFunction</c>.\n  /// </param>\n  /// <returns>The result of the call, if any.</returns>\n  JsEnhancedNativeFunction = function(callee: JsValueRef; arguments: PJsValueRef; argumentCount: Word;\n      info: PJsNativeFunctionInfo; callbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     A Promise Rejection Tracker callback.\n  /// </summary>\n  /// <remarks>\n  ///     The host can specify a promise rejection tracker callback in <c>JsSetHostPromiseRejectionTracker</c>.\n  ///     If a promise is rejected with no reactions or a reaction is added to a promise that was rejected\n  ///     before it had reactions by default nothing is done.\n  ///     A Promise Rejection Tracker callback may be set - which will then be called when this occurs.\n  ///     Note - per draft ECMASpec 2018 25.4.1.9 this function should not set or return an exception\n  ///     Note also the promise and reason parameters may be garbage collected after this function is called\n  ///     if you wish to make further use of them you will need to use JsAddRef to preserve them\n  ///     However if you use JsAddRef you must also call JsRelease and not hold unto them after\n  ///     a handled notification (both per spec and to avoid memory leaks)\n  /// </remarks>\n  /// <param name=\"promise\">The promise object, represented as a JsValueRef.</param>\n  /// <param name=\"reason\">The value/cause of the rejection, represented as a JsValueRef.</param>\n  /// <param name=\"handled\">Boolean - false for promiseRejected: i.e. if the promise has just been rejected with no handler,\n  ///                         true for promiseHandled: i.e. if it was rejected before without a handler and is now being handled.</param>\n  /// <param name=\"callbackState\">The state passed to <c>JsSetHostPromiseRejectionTracker</c>.</param>\n  JsHostPromiseRejectionTrackerCallback = procedure(promise, reason: JsValueRef; handled: bool; callbackState: Pointer);\n      {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new enhanced JavaScript function.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"nativeFunction\">The method to call when the function is invoked.</param>\n  /// <param name=\"metadata\">If this is not <c>JS_INVALID_REFERENCE</c>, it is converted to a string and used as the name of the function.</param>\n  /// <param name=\"callbackState\">\n  ///     User provided state that will be passed back to the callback.\n  /// </param>\n  /// <param name=\"function\">The new function object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateEnhancedFunction(nativeFunction: JsEnhancedNativeFunction; metadata: JsValueRef;\n      callbackState: Pointer; out _function: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Initialize a ModuleRecord from host\n  /// </summary>\n  /// <remarks>\n  ///     Bootstrap the module loading process by creating a new module record.\n  /// </remarks>\n  /// <param name=\"referencingModule\">The parent module of the new module - nullptr for a root module.</param>\n  /// <param name=\"normalizedSpecifier\">The normalized specifier for the module.</param>\n  /// <param name=\"moduleRecord\">The new module record. The host should not try to call this API twice\n  ///                            with the same normalizedSpecifier.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsInitializeModuleRecord(\n      referencingModule: JsModuleRecord;\n      normalizedSpecifier: JsValueRef;\n      out moduleRecord: JsModuleRecord): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Parse the source for an ES module\n  /// </summary>\n  /// <remarks>\n  ///     This is basically ParseModule operation in ES6 spec. It is slightly different in that:\n  ///     a) The ModuleRecord was initialized earlier, and passed in as an argument.\n  ///     b) This includes a check to see if the module being Parsed is the last module in the\n  /// dependency tree. If it is it automatically triggers Module Instantiation.\n  /// </remarks>\n  /// <param name=\"requestModule\">The ModuleRecord being parsed.</param>\n  /// <param name=\"sourceContext\">A cookie identifying the script that can be used by debuggable script contexts.</param>\n  /// <param name=\"script\">The source script to be parsed, but not executed in this code.</param>\n  /// <param name=\"scriptLength\">The length of sourceText in bytes. As the input might contain a embedded null.</param>\n  /// <param name=\"sourceFlag\">The type of the source code passed in. It could be utf16 or utf8 at this time.</param>\n  /// <param name=\"exceptionValueRef\">The error object if there is parse error.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsParseModuleSource(\n      requestModule: JsModuleRecord;\n      sourceContext: JsSourceContext;\n      script: PByte;\n      scriptLength: Cardinal;\n      sourceFlag: JsParseModuleSourceFlags;\n      out exceptionValueRef: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Execute module code.\n  /// </summary>\n  /// <remarks>\n  ///     This method implements 15.2.1.1.6.5, \"ModuleEvaluation\" concrete method.\n  ///     This method should be called after the engine notifies the host that the module is ready.\n  ///     This method only needs to be called on root modules - it will execute all of the dependent modules.\n  ///\n  ///     One moduleRecord will be executed only once. Additional execution call on the same moduleRecord will fail.\n  /// </remarks>\n  /// <param name=\"requestModule\">The ModuleRecord being executed.</param>\n  /// <param name=\"result\">The return value of the module.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsModuleEvaluation(\n      requestModule: JsModuleRecord;\n      out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Set host info for the specified module.\n  /// </summary>\n  /// <remarks>\n  ///     This is used for four things:\n  ///     1. Setting up the callbacks for module loading - note these are actually\n  ///         set on the current Context not the module so only have to be set for\n  ///         the first root module in any given context.\n  ///     2. Setting host defined info on a module record - can be anything that\n  ///         you wish to associate with your modules.\n  ///     3. Setting a URL for a module to be used for stack traces/debugging -\n  ///         note this must be set before calling JsParseModuleSource on the module\n  ///         or it will be ignored.\n  ///     4. Setting an exception on the module object - only relevant prior to it being Parsed.\n  /// </remarks>\n  /// <param name=\"requestModule\">The request module.</param>\n  /// <param name=\"moduleHostInfo\">The type of host info to be set.</param>\n  /// <param name=\"hostInfo\">The host info to be set.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetModuleHostInfo(\n      requestModule: JsModuleRecord;\n      moduleHostInfo: JsModuleHostInfoKind;\n      hostInfo: Pointer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Retrieve the host info for the specified module.\n  /// </summary>\n  /// <remarks>\n  ///     This can used to retrieve info previously set with JsSetModuleHostInfo.\n  /// </remarks>\n  /// <param name=\"requestModule\">The request module.</param>\n  /// <param name=\"moduleHostInfo\">The type of host info to be retrieved.</param>\n  /// <param name=\"hostInfo\">The retrieved host info for the module.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetModuleHostInfo(\n      requestModule: JsModuleRecord;\n      moduleHostInfo: JsModuleHostInfoKind;\n      out hostInfo: Pointer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Returns metadata relating to the exception that caused the runtime of the current context\n  ///     to be in the exception state and resets the exception state for that runtime. The metadata\n  ///     includes a reference to the exception itself.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     If the runtime of the current context is not in an exception state, this API will return\n  ///     <c>JsErrorInvalidArgument</c>. If the runtime is disabled, this will return an exception\n  ///     indicating that the script was terminated, but it will not clear the exception (the\n  ///     exception will be cleared if the runtime is re-enabled using\n  ///     <c>JsEnableRuntimeExecution</c>).\n  ///     </para>\n  ///     <para>\n  ///     The metadata value is a javascript object with the following properties: <c>exception</c>, the\n  ///     thrown exception object; <c>line</c>, the 0 indexed line number where the exception was thrown;\n  ///     <c>column</c>, the 0 indexed column number where the exception was thrown; <c>length</c>, the\n  ///     source-length of the cause of the exception; <c>source</c>, a string containing the line of\n  ///     source code where the exception was thrown; and <c>url</c>, a string containing the name of\n  ///     the script file containing the code that threw the exception.\n  ///     </para>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"metadata\">The exception metadata for the runtime of the current context.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetAndClearExceptionWithMetadata(\n      out metadata: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\ntype\n  /// <summary>\n  ///     Called by the runtime to load the source code of the serialized script.\n  /// </summary>\n  /// <param name=\"sourceContext\">The context passed to Js[Parse|Run]SerializedScriptCallback</param>\n  /// <param name=\"script\">The script returned.</param>\n  /// <returns>\n  ///     true if the operation succeeded, false otherwise.\n  /// </returns>\n  JsSerializedLoadScriptCallback = function(\n      sourceContext: JsSourceContext;\n      out value: JsValueRef;\n      out parseAttributes: JsParseScriptAttributes): bool; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Create JavascriptString variable from ASCII or Utf8 string\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///        Requires an active script context.\n  ///     </para>\n  ///     <para>\n  ///         Input string can be either ASCII or Utf8\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"content\">Pointer to string memory.</param>\n  /// <param name=\"length\">Number of bytes within the string</param>\n  /// <param name=\"value\">JsValueRef representing the JavascriptString</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateString(\n          content: PAnsiChar;\n          length: size_t;\n          out value: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Create JavascriptString variable from Utf16 string\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///         Requires an active script context.\n  ///     </para>\n  ///     <para>\n  ///         Expects Utf16 string\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"content\">Pointer to string memory.</param>\n  /// <param name=\"length\">Number of characters within the string</param>\n  /// <param name=\"value\">JsValueRef representing the JavascriptString</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateStringUtf16(\n          content: PUnicodeChar;\n          length: size_t;\n          out value: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Write JavascriptString value into C string buffer (Utf8)\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///         When size of the `buffer` is unknown,\n  ///         `buffer` argument can be nullptr.\n  ///         In that case, `length` argument will return the length needed.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"value\">JavascriptString value</param>\n  /// <param name=\"buffer\">Pointer to buffer</param>\n  /// <param name=\"bufferSize\">Buffer size</param>\n  /// <param name=\"length\">Total number of characters needed or written</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCopyString(\n          value: JsValueRef;\n          buffer: PAnsiChar;\n          bufferSize: size_t;\n          length: Psize_t): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Write string value into Utf16 string buffer\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///         When size of the `buffer` is unknown,\n  ///         `buffer` argument can be nullptr.\n  ///         In that case, `written` argument will return the length needed.\n  ///     </para>\n  ///     <para>\n  ///         when start is out of range or &lt; 0, returns JsErrorInvalidArgument\n  ///         and `written` will be equal to 0.\n  ///         If calculated length is 0 (It can be due to string length or `start`\n  ///         and length combination), then `written` will be equal to 0 and call\n  ///         returns JsNoError\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"value\">JavascriptString value</param>\n  /// <param name=\"start\">start offset of buffer</param>\n  /// <param name=\"length\">length to be written</param>\n  /// <param name=\"buffer\">Pointer to buffer</param>\n  /// <param name=\"written\">Total number of characters written</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCopyStringUtf16(\n          value: JsValueRef;\n          start: Integer;\n          length: Integer;\n          buffer: PUnicodeChar;\n          written: Psize_t): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Parses a script and returns a function representing the script.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///         Requires an active script context.\n  ///     </para>\n  ///     <para>\n  ///         Script source can be either JavascriptString or JavascriptExternalArrayBuffer.\n  ///         In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16,\n  ///         JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes.\n  ///     </para>\n  ///     <para>\n  ///         Use JavascriptExternalArrayBuffer with Utf8/ASCII script source\n  ///         for better performance and smaller memory footprint.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"script\">The script to run.</param>\n  /// <param name=\"sourceContext\">\n  ///     A cookie identifying the script that can be used by debuggable script contexts.\n  /// </param>\n  /// <param name=\"sourceUrl\">The location the script came from.</param>\n  /// <param name=\"parseAttributes\">Attribute mask for parsing the script</param>\n  /// <param name=\"result\">The result of the compiled script.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsParse(\n          script: JsValueRef;\n          sourceContext: JsSourceContext;\n          sourceUrl: JsValueRef;\n          parseAttributes: JsParseScriptAttributes;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Executes a script.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///         Requires an active script context.\n  ///     </para>\n  ///     <para>\n  ///         Script source can be either JavascriptString or JavascriptExternalArrayBuffer.\n  ///         In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16,\n  ///         JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes.\n  ///     </para>\n  ///     <para>\n  ///         Use JavascriptExternalArrayBuffer with Utf8/ASCII script source\n  ///         for better performance and smaller memory footprint.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"script\">The script to run.</param>\n  /// <param name=\"sourceContext\">\n  ///     A cookie identifying the script that can be used by debuggable script contexts.\n  /// </param>\n  /// <param name=\"sourceUrl\">The location the script came from</param>\n  /// <param name=\"parseAttributes\">Attribute mask for parsing the script</param>\n  /// <param name=\"result\">The result of the script, if any. This parameter can be null.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsRun(\n          script: JsValueRef;\n          sourceContext: JsSourceContext;\n          sourceUrl: JsValueRef;\n          parseAttributes: JsParseScriptAttributes;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates the property ID associated with the name.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///         Property IDs are specific to a context and cannot be used across contexts.\n  ///     </para>\n  ///     <para>\n  ///         Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"name\">\n  ///     The name of the property ID to get or create. The name may consist of only digits.\n  ///     The string is expected to be ASCII / utf8 encoded.\n  /// </param>\n  /// <param name=\"length\">length of the name in bytes</param>\n  /// <param name=\"propertyId\">The property ID in this runtime for the given name.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreatePropertyId(\n          name: PAnsiChar;\n          length: size_t;\n          out propertyId: JsPropertyIdRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Copies the name associated with the property ID into a buffer.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///         Requires an active script context.\n  ///     </para>\n  ///     <para>\n  ///         When size of the `buffer` is unknown,\n  ///         `buffer` argument can be nullptr.\n  ///         `length` argument will return the size needed.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"propertyId\">The property ID to get the name of.</param>\n  /// <param name=\"buffer\">The buffer holding the name associated with the property ID, encoded as utf8</param>\n  /// <param name=\"bufferSize\">Size of the buffer.</param>\n  /// <param name=\"written\">Total number of characters written or to be written</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCopyPropertyId(\n          propertyId: JsPropertyIdRef;\n          buffer: PAnsiChar;\n          bufferSize: size_t;\n          out length: size_t): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Serializes a parsed script to a buffer than can be reused.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     <c>JsSerializeScript</c> parses a script and then stores the parsed form of the script in a\n  ///     runtime-independent format. The serialized script then can be deserialized in any\n  ///     runtime without requiring the script to be re-parsed.\n  ///     </para>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  ///     <para>\n  ///         Script source can be either JavascriptString or JavascriptExternalArrayBuffer.\n  ///         In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16,\n  ///         JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes.\n  ///     </para>\n  ///     <para>\n  ///         Use JavascriptExternalArrayBuffer with Utf8/ASCII script source\n  ///         for better performance and smaller memory footprint.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"script\">The script to serialize</param>\n  /// <param name=\"buffer\">ArrayBuffer</param>\n  /// <param name=\"parseAttributes\">Encoding for the script.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSerialize(\n          script: JsValueRef;\n          out buffer: JsValueRef;\n          parseAttributes: JsParseScriptAttributes): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Parses a serialized script and returns a function representing the script.\n  ///     Provides the ability to lazy load the script source only if/when it is needed.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"buffer\">The serialized script as an ArrayBuffer (preferably ExternalArrayBuffer).</param>\n  /// <param name=\"scriptLoadCallback\">\n  ///     Callback called when the source code of the script needs to be loaded.\n  ///     This is an optional parameter, set to null if not needed.\n  /// </param>\n  /// <param name=\"sourceContext\">\n  ///     A cookie identifying the script that can be used by debuggable script contexts.\n  ///     This context will passed into scriptLoadCallback.\n  /// </param>\n  /// <param name=\"sourceUrl\">The location the script came from.</param>\n  /// <param name=\"result\">A function representing the script code.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsParseSerialized(\n          buffer: JsValueRef;\n          scriptLoadCallback: JsSerializedLoadScriptCallback;\n          sourceContext: JsSourceContext;\n          sourceUrl: JsValueRef;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Runs a serialized script.\n  ///     Provides the ability to lazy load the script source only if/when it is needed.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  ///     <para>\n  ///     The runtime will detach the data from the buffer and hold on to it until all\n  ///     instances of any functions created from the buffer are garbage collected.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"buffer\">The serialized script as an ArrayBuffer (preferably ExternalArrayBuffer).</param>\n  /// <param name=\"scriptLoadCallback\">Callback called when the source code of the script needs to be loaded.</param>\n  /// <param name=\"sourceContext\">\n  ///     A cookie identifying the script that can be used by debuggable script contexts.\n  ///     This context will passed into scriptLoadCallback.\n  /// </param>\n  /// <param name=\"sourceUrl\">The location the script came from.</param>\n  /// <param name=\"result\">\n  ///     The result of running the script, if any. This parameter can be null.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsRunSerialized(\n          buffer: JsValueRef;\n          scriptLoadCallback: JsSerializedLoadScriptCallback;\n          sourceContext: JsSourceContext;\n          sourceUrl: JsValueRef;\n          out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the state of a given Promise object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"promise\">The Promise object.</param>\n  /// <param name=\"state\">The current state of the Promise.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetPromiseState(\n      promise: JsValueRef;\n      out state: JsPromiseState): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the result of a given Promise object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"promise\">The Promise object.</param>\n  /// <param name=\"result\">The result of the Promise.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetPromiseResult(\n      promise: JsValueRef;\n      out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new JavaScript Promise object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"promise\">The new Promise object.</param>\n  /// <param name=\"resolveFunction\">The function called to resolve the created Promise object.</param>\n  /// <param name=\"rejectFunction\">The function called to reject the created Promise object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreatePromise(\n          out promise: JsValueRef;\n          out resolveFunction: JsValueRef;\n          out rejectFunction: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\ntype\n  /// <summary>\n  ///     A weak reference to a JavaScript value.\n  /// </summary>\n  /// <remarks>\n  ///     A value with only weak references is available for garbage-collection. A strong reference\n  ///     to the value (<c>JsValueRef</c>) may be obtained from a weak reference if the value happens\n  ///     to still be available.\n  /// </remarks>\n  JsWeakRef = JsRef;\n\n  /// <summary>\n  ///     Creates a weak reference to a value.\n  /// </summary>\n  /// <param name=\"value\">The value to be referenced.</param>\n  /// <param name=\"weakRef\">Weak reference to the value.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateWeakReference(\n          value: JsValueRef;\n          out weakRef: JsWeakRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets a strong reference to the value referred to by a weak reference.\n  /// </summary>\n  /// <param name=\"weakRef\">A weak reference.</param>\n  /// <param name=\"value\">Reference to the value, or <c>JS_INVALID_REFERENCE</c> if the value is\n  ///     no longer available.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetWeakReferenceValue(\n          weakRef: JsWeakRef;\n          value: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a Javascript SharedArrayBuffer object with shared content get from JsGetSharedArrayBufferContent.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"sharedContents\">\n  ///     The storage object of a SharedArrayBuffer which can be shared between multiple thread.\n  /// </param>\n  /// <param name=\"result\">The new SharedArrayBuffer object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateSharedArrayBufferWithSharedContent(\n      sharedContents: JsSharedArrayBufferContentHandle;\n      out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Get the storage object from a SharedArrayBuffer.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"sharedArrayBuffer\">The SharedArrayBuffer object.</param>\n  /// <param name=\"sharedContents\">\n  ///     The storage object of a SharedArrayBuffer which can be shared between multiple thread.\n  ///     User should call JsReleaseSharedArrayBufferContentHandle after finished using it.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetSharedArrayBufferContent(\n      sharedArrayBuffer: JsValueRef;\n      out sharedContents: JsSharedArrayBufferContentHandle): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Decrease the reference count on a SharedArrayBuffer storage object.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"sharedContents\">\n  ///     The storage object of a SharedArrayBuffer which can be shared between multiple thread.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsReleaseSharedArrayBufferContentHandle(\n      sharedContents: JsSharedArrayBufferContentHandle): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Determines whether an object has a non-inherited property.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that may contain the property.</param>\n  /// <param name=\"propertyId\">The ID of the property.</param>\n  /// <param name=\"hasOwnProperty\">Whether the object has the non-inherited property.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsHasOwnProperty(_object: JsValueRef; propertyId: JsPropertyIdRef; out hasOwnProperty: bool): JsErrorCode;\n      {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Write JS string value into char string buffer without a null terminator\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///         When size of the `buffer` is unknown,\n  ///         `buffer` argument can be nullptr.\n  ///         In that case, `written` argument will return the length needed.\n  ///     </para>\n  ///     <para>\n  ///         When start is out of range or &lt; 0, returns JsErrorInvalidArgument\n  ///         and `written` will be equal to 0.\n  ///         If calculated length is 0 (It can be due to string length or `start`\n  ///         and length combination), then `written` will be equal to 0 and call\n  ///         returns JsNoError\n  ///     </para>\n  ///     <para>\n  ///         The JS string `value` will be converted one utf16 code point at a time,\n  ///         and if it has code points that do not fit in one byte, those values\n  ///         will be truncated.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"value\">JavascriptString value</param>\n  /// <param name=\"start\">Start offset of buffer</param>\n  /// <param name=\"length\">Number of characters to be written</param>\n  /// <param name=\"buffer\">Pointer to buffer</param>\n  /// <param name=\"written\">Total number of characters written</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCopyStringOneByte(value: JsValueRef; start, length: Integer; buffer: PAnsiChar;\n      written: Psize_t): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Obtains frequently used properties of a data view.\n  /// </summary>\n  /// <param name=\"dataView\">The data view instance.</param>\n  /// <param name=\"arrayBuffer\">The ArrayBuffer backstore of the view.</param>\n  /// <param name=\"byteOffset\">The offset in bytes from the start of arrayBuffer referenced by the array.</param>\n  /// <param name=\"byteLength\">The number of bytes in the array.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetDataViewInfo(dataView: JsValueRef; arrayBuffer: PJsValueRef;\n      byteOffset, byteLength: PCardinal): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Determine if one JavaScript value is less than another JavaScript value.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     This function is equivalent to the <c>&lt;</c> operator in Javascript.\n  ///     </para>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"object1\">The first object to compare.</param>\n  /// <param name=\"object2\">The second object to compare.</param>\n  /// <param name=\"result\">Whether object1 is less than object2.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsLessThan(object1, object2: JsValueRef; out result: bool): JsErrorCode;\n      {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Determine if one JavaScript value is less than or equal to another JavaScript value.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     This function is equivalent to the <c>&lt;=</c> operator in Javascript.\n  ///     </para>\n  ///     <para>\n  ///     Requires an active script context.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"object1\">The first object to compare.</param>\n  /// <param name=\"object2\">The second object to compare.</param>\n  /// <param name=\"result\">Whether object1 is less than or equal to object2.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsLessThanOrEqual(object1, object2: JsValueRef; out result: bool): JsErrorCode;\n      {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Creates a new object (with prototype) that stores some external data.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"data\">External data that the object will represent. May be null.</param>\n  /// <param name=\"finalizeCallback\">\n  ///     A callback for when the object is finalized. May be null.\n  /// </param>\n  /// <param name=\"prototype\">Prototype object or nullptr.</param>\n  /// <param name=\"object\">The new object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsCreateExternalObjectWithPrototype(\n      data: Pointer;\n      finalizeCallback: JsFinalizeCallback;\n      prototype: JsValueRef;\n      out _object: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets an object's property.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that contains the property.</param>\n  /// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n  /// <param name=\"value\">The value of the property.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsObjectGetProperty(_object, key: JsValueRef; out value: JsValueRef): JsErrorCode;\n      {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Puts an object's property.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that contains the property.</param>\n  /// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n  /// <param name=\"value\">The new value of the property.</param>\n  /// <param name=\"useStrictRules\">The property set should follow strict mode rules.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsObjectSetProperty(_object, key, value: JsValueRef; useStrictRules: bool): JsErrorCode;\n      {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Determines whether an object has a property.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that may contain the property.</param>\n  /// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n  /// <param name=\"hasProperty\">Whether the object (or a prototype) has the property.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsObjectHasProperty(_object, key: JsValueRef; out hasProperty: bool): JsErrorCode;\n      {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Defines a new object's own property from a property descriptor.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that has the property.</param>\n  /// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n  /// <param name=\"propertyDescriptor\">The property descriptor.</param>\n  /// <param name=\"result\">Whether the property was defined.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsObjectDefineProperty(_object, key, propertyDescriptor: JsValueRef; out result: bool): JsErrorCode;\n      {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Deletes an object's property.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that contains the property.</param>\n  /// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n  /// <param name=\"useStrictRules\">The property set should follow strict mode rules.</param>\n  /// <param name=\"result\">Whether the property was deleted.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsObjectDeleteProperty(_object, key: JsValueRef; useStrictRules: bool; out result: JsValueRef): JsErrorCode;\n      {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets a property descriptor for an object's own property.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that has the property.</param>\n  /// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n  /// <param name=\"propertyDescriptor\">The property descriptor.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsObjectGetOwnPropertyDescriptor(_object, key: JsValueRef; out propertyDescriptor: JsValueRef): JsErrorCode;\n      {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Determines whether an object has a non-inherited property.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"object\">The object that may contain the property.</param>\n  /// <param name=\"key\">The key (JavascriptString or JavascriptSymbol) to the property.</param>\n  /// <param name=\"hasOwnProperty\">Whether the object has the non-inherited property.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsObjectHasOwnProperty(_object, key: JsValueRef; out hasOwnProperty: bool): JsErrorCode;\n      {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets whether any action should be taken when a promise is rejected with no reactions\n  ///     or a reaction is added to a promise that was rejected before it had reactions.\n  ///     By default in either of these cases nothing occurs.\n  ///     This function allows you to specify if something should occur and provide a callback\n  ///     to implement whatever should occur.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  /// </remarks>\n  /// <param name=\"promiseRejectionTrackerCallback\">The callback function being set.</param>\n  /// <param name=\"callbackState\">\n  ///     User provided state that will be passed back to the callback.\n  /// </param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSetHostPromiseRejectionTracker(\n      promiseRejectionTrackerCallback: JsHostPromiseRejectionTrackerCallback;\n      callbackState: Pointer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Retrieve the namespace object for a module.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context and that the module has already been evaluated.\n  /// </remarks>\n  /// <param name=\"requestModule\">The JsModuleRecord for which the namespace is being requested.</param>\n  /// <param name=\"moduleNamespace\">A JsValueRef - the requested namespace object.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetModuleNamespace(\n    requestModule: JsModuleRecord;\n    out moduleNamespace: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Determines if a provided object is a JavscriptProxy Object and\n  ///     provides references to a Proxy's target and handler.\n  /// </summary>\n  /// <remarks>\n  ///     Requires an active script context.\n  ///     If object is not a Proxy object the target and handler parameters are not touched.\n  ///     If nullptr is supplied for target or handler the function returns after\n  ///     setting the isProxy value.\n  ///     If the object is a revoked Proxy target and handler are set to JS_INVALID_REFERENCE.\n  ///     If it is a Proxy object that has not been revoked target and handler are set to the\n  ///     the object's target and handler.\n  /// </remarks>\n  /// <param name=\"object\">The object that may be a Proxy.</param>\n  /// <param name=\"isProxy\">Pointer to a Boolean - is the object a proxy?</param>\n  /// <param name=\"target\">Pointer to a JsValueRef - the object's target.</param>\n  /// <param name=\"handler\">Pointer to a JsValueRef - the object's handler.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsGetProxyProperties(\n      _object: JsValueRef;\n      out isProxy: bool;\n      out target: JsValueRef;\n      out handler: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Parses a script and stores the generated parser state cache into a buffer which can be reused.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///     <c>JsSerializeParserState</c> parses a script and then stores a cache of the parser state\n  ///     in a runtime-independent format. The parser state may be deserialized in any runtime along\n  ///     with the same script to skip the initial parse phase.\n  ///     </para>\n  ///     <para>\n  ///         Requires an active script context.\n  ///     </para>\n  ///     <para>\n  ///         Script source can be either JavascriptString or JavascriptExternalArrayBuffer.\n  ///         In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16,\n  ///         JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes.\n  ///     </para>\n  ///     <para>\n  ///         Use JavascriptExternalArrayBuffer with Utf8/ASCII script source\n  ///         for better performance and smaller memory footprint.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"scriptVal\">The script to parse.</param>\n  /// <param name=\"bufferVal\">The buffer to put the serialized parser state cache into.</param>\n  /// <param name=\"parseAttributes\">Encoding for the script.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsSerializeParserState(\n    scriptVal: JsValueRef;\n    out bufferVal: JsValueRef;\n    parseAttributes: JsParseScriptAttributes): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Deserializes the cache of initial parser state and (along with the same\n  ///     script source) executes the script and returns the result.\n  /// </summary>\n  /// <remarks>\n  ///     <para>\n  ///         Requires an active script context.\n  ///     </para>\n  ///     <para>\n  ///         Script source can be either JavascriptString or JavascriptExternalArrayBuffer.\n  ///         In case it is an ExternalArrayBuffer, and the encoding of the buffer is Utf16,\n  ///         JsParseScriptAttributeArrayBufferIsUtf16Encoded is expected on parseAttributes.\n  ///     </para>\n  ///     <para>\n  ///         Use JavascriptExternalArrayBuffer with Utf8/ASCII script source\n  ///         for better performance and smaller memory footprint.\n  ///     </para>\n  /// </remarks>\n  /// <param name=\"script\">The script to run.</param>\n  /// <param name=\"sourceContext\">\n  ///     A cookie identifying the script that can be used by debuggable script contexts.\n  /// </param>\n  /// <param name=\"sourceUrl\">The location the script came from</param>\n  /// <param name=\"parseAttributes\">Attribute mask for parsing the script</param>\n  /// <param name=\"parserState\">\n  ///     A buffer containing a cache of the parser state generated by <c>JsSerializeParserState</c>.\n  /// </param>\n  /// <param name=\"result\">The result of the script, if any. This parameter can be null.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsRunScriptWithParserState(\n    script: JsValueRef;\n    sourceContext: JsSourceContext;\n    sourceUrl: JsValueRef;\n    parseAttributes: JsParseScriptAttributes;\n    parserState: JsValueRef;\n    out result: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\nimplementation\n\nuses\n  Math;\n\n{$ifdef MSWINDOWS}\nconst\n  _chakracore = 'chakracore.dll';\n{$endif}\n\n{$ifdef DARWIN}\nconst\n  _chakracore = 'libChakraCore.dylib';\n{$endif}\n\n{$ifdef LINUX}\nconst\n  _chakracore = 'libChakraCore.so';\n{$endif}\n\n  function JsCreateEnhancedFunction; external _chakracore;\n  function JsInitializeModuleRecord; external _chakracore;\n  function JsParseModuleSource; external _chakracore;\n  function JsModuleEvaluation; external _chakracore;\n  function JsSetModuleHostInfo; external _chakracore;\n  function JsGetModuleHostInfo; external _chakracore;\n  function JsGetAndClearExceptionWithMetadata; external _chakracore;\n  function JsCreateString; external _chakracore;\n  function JsCreateStringUtf16; external _chakracore;\n  function JsCopyString; external _chakracore;\n  function JsCopyStringUtf16; external _chakracore;\n  function JsParse; external _chakracore;\n  function JsRun; external _chakracore;\n  function JsCreatePropertyId; external _chakracore;\n  function JsCopyPropertyId; external _chakracore;\n  function JsSerialize; external _chakracore;\n  function JsParseSerialized; external _chakracore;\n  function JsRunSerialized; external _chakracore;\n  function JsGetPromiseState; external _chakracore;\n  function JsGetPromiseResult; external _chakracore;\n  function JsCreatePromise; external _chakracore;\n  function JsCreateWeakReference; external _chakracore;\n  function JsGetWeakReferenceValue; external _chakracore;\n  function JsCreateSharedArrayBufferWithSharedContent; external _chakracore;\n  function JsGetSharedArrayBufferContent; external _chakracore;\n  function JsReleaseSharedArrayBufferContentHandle; external _chakracore;\n  function JsHasOwnProperty; external _chakracore;\n  function JsCopyStringOneByte; external _chakracore;\n  function JsGetDataViewInfo; external _chakracore;\n  function JsLessThan; external _chakracore;\n  function JsLessThanOrEqual; external _chakracore;\n  function JsCreateExternalObjectWithPrototype; external _chakracore;\n  function JsObjectGetProperty; external _chakracore;\n  function JsObjectSetProperty; external _chakracore;\n  function JsObjectHasProperty; external _chakracore;\n  function JsObjectDefineProperty; external _chakracore;\n  function JsObjectDeleteProperty; external _chakracore;\n  function JsObjectGetOwnPropertyDescriptor; external _chakracore;\n  function JsObjectHasOwnProperty; external _chakracore;\n  function JsSetHostPromiseRejectionTracker; external _chakracore;\n  function JsGetModuleNamespace; external _chakracore;\n  function JsGetProxyProperties; external _chakracore;\n  function JsSerializeParserState; external _chakracore;\n  function JsRunScriptWithParserState; external _chakracore;\n\ninitialization\n  SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]);\n\nfinalization\n\nend.\n"
  },
  {
    "path": "src/ChakraCoreClasses.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nunit ChakraCoreClasses;\n\n{$include common.inc}\n\ninterface\n\nuses\n{$ifdef FPC}\n  Types,\n{$else}\n  Windows,\n{$endif}\n  Classes, SysUtils, Contnrs,\n  Compat, ChakraCore, ChakraCommon, ChakraCoreUtils;\n\ntype\n  TChakraCoreContext = class;\n  TChakraModule = class;\n\n  TMemAllocEvent = procedure (Sender: TObject; Size: NativeUInt; var Allow: Boolean) of object;\n  TMemFreeEvent = procedure (Sender: TObject; Size: NativeUInt) of object;\n  TMemFailureEvent = procedure (Sender: TObject; Size: NativeUInt) of object;\n\n  TChakraCoreRuntimeOption = (\n    ccroDisableBackgroundWork,           // JsRuntimeAttributeDisableBackgroundWork           = $00000001;\n    ccroAllowScriptInterrupt,            // JsRuntimeAttributeAllowScriptInterrupt            = $00000002;\n    ccroEnableIdleProcessing,            // JsRuntimeAttributeEnableIdleProcessing            = $00000004;\n    ccroDisableNativeCodeGeneration,     // JsRuntimeAttributeDisableNativeCodeGeneration     = $00000008;\n    ccroDisableEval,                     // JsRuntimeAttributeDisableEval                     = $00000010;\n    ccroEnableExperimentalFeatures,      // JsRuntimeAttributeEnableExperimentalFeatures      = $00000020;\n    ccroDispatchSetExceptionsToDebugger, // JsRuntimeAttributeDispatchSetExceptionsToDebugger = $00000040;\n    ccroDisableFatalOnOOM,               // JsRuntimeAttributeDisableFatalOnOOM               = $00000080;\n    ccroDisableExecutablePageAllocation  // JsRuntimeAttributeDisableExecutablePageAllocation = $00000100;\n  );\n  TChakraCoreRuntimeOptions = set of TChakraCoreRuntimeOption;\n\n  TChakraCoreRuntime = class\n  private\n    FHandle: JsRuntimeHandle;\n    FMemoryLimit: NativeUInt;\n    FOptions: TChakraCoreRuntimeOptions;\n\n    FOnBeforeCollect: TNotifyEvent;\n    FOnMemAlloc: TMemAllocEvent;\n    FOnMemFailure: TMemFailureEvent;\n    FOnMemFree: TMemFreeEvent;\n\n    function GetEnabled: Boolean;\n    function GetHandle: JsRuntimeHandle;\n    function GetMemoryLimit: NativeUInt;\n    function GetMemoryUsage: NativeUInt;\n    procedure SetEnabled(Value: Boolean);\n    procedure SetMemoryLimit(Value: NativeUInt);\n\n    procedure SetOnBeforeCollect(Value: TNotifyEvent);\n    procedure SetOnMemAlloc(Value: TMemAllocEvent);\n    procedure SetOnMemFailure(Value: TMemFailureEvent);\n    procedure SetOnMemFree(Value: TMemFreeEvent);\n  protected\n    procedure CreateRuntime; virtual;\n    procedure DisposeRuntime; virtual;\n    procedure DoBeforeCollect; virtual;\n    function DoMemAlloc(Size: NativeUInt): Boolean; virtual;\n    procedure DoMemFailure(Size: NativeUInt); virtual;\n    procedure DoMemFree(Size: NativeUInt); virtual;\n  public\n    constructor Create(AOptions: TChakraCoreRuntimeOptions = []); virtual;\n    destructor Destroy; override;\n\n    procedure CollectGarbage;\n\n    property Enabled: Boolean read GetEnabled write SetEnabled;\n    property Handle: JsRuntimeHandle read GetHandle;\n    property MemoryLimit: NativeUInt read GetMemoryLimit write SetMemoryLimit;\n    property MemoryUsage: NativeUInt read GetMemoryUsage;\n    property Options: TChakraCoreRuntimeOptions read FOptions;\n\n    property OnBeforeCollect: TNotifyEvent read FOnBeforeCollect write SetOnBeforeCollect;\n    property OnMemAlloc: TMemAllocEvent read FOnMemAlloc write SetOnMemAlloc;\n    property OnMemFailure: TMemFailureEvent read FOnMemFailure write SetOnMemFailure;\n    property OnMemFree: TMemFreeEvent read FOnMemFree write SetOnMemFree;\n  end;\n\n  TBaseMessage = class\n  private\n    FContext: TChakraCoreContext;\n  protected\n    function Process(out ResultValue: JsValueRef): Boolean; virtual; abstract;\n  public\n    constructor Create(AContext: TChakraCoreContext); virtual;\n\n    property Context: TChakraCoreContext read FContext;\n  end;\n\n  TTaskMessage = class(TBaseMessage)\n  private\n    FArgCount: Integer;\n    FArgs: PJsValueRefArray;\n    FDelay: Cardinal;\n    FRepeatCount: Integer;\n    FTask: JsValueRef;\n    FTime: Cardinal;\n  protected\n    function Process(out ResultValue: JsValueRef): Boolean; override;\n  public\n    constructor Create(AContext: TChakraCoreContext; Task, ThisArg: JsValueRef; const Args: array of JsValueRef;\n      ADelay: Cardinal = 0; ARepeatCount: Integer = 1); reintroduce; virtual;\n    destructor Destroy; override;\n\n    property Delay: Cardinal read FDelay;\n    property RepeatCount: Integer read FRepeatCount;\n    property Task: JsValueRef read FTask;\n    property Time: Cardinal read FTime;\n  end;\n\n  TPromiseStatus = (psPending, psResolved, psRejected);\n\n  TPromiseMessage = class(TBaseMessage)\n  private\n    FArgs: array[0..1] of JsValueRef;\n    FPromise: JsValueRef;\n    FRejectTask: JsValueRef;\n    FResolveTask: JsValueRef;\n    FStatus: TPromiseStatus;\n  protected\n    function Process(out ResultValue: JsHandle): Boolean; override;\n    procedure SetStatus(Value: TPromiseStatus; StatusValue: JsValueRef);\n  public\n    constructor Create(AContext: TChakraCoreContext; ThisArg, ResolveTask, RejectTask: JsValueRef); reintroduce; virtual;\n    destructor Destroy; override;\n\n    property Promise: JsValueRef read FPromise;\n    property RejectTask: JsValueRef read FRejectTask;\n    property ResolveTask: JsValueRef read FResolveTask;\n    property Status: TPromiseStatus read FStatus;\n  end;\n\n  TModuleMessage = class(TBaseMessage)\n  private\n    FModule: TChakraModule;\n  protected\n    function Process(out ResultValue: JsValueRef): Boolean; override;\n  public\n    constructor Create(AContext: TChakraCoreContext; AModule: TChakraModule); reintroduce; virtual;\n\n    property Module: TChakraModule read FModule;\n  end;\n\n  { TChakraModule }\n\n  TChakraModule = class\n  private\n    FContext: TChakraCoreContext;\n    FHandle: JsModuleRecord;\n    FName: UnicodeString;\n    FParsed: Boolean;\n    FResult: JsvalueRef;\n    FURL: UnicodeString;\n\n    procedure SetURL(const Value: UnicodeString);\n  public\n    constructor Create(AContext: TChakraCoreContext; const AName: UnicodeString; ARefModule: JsModuleRecord);\n\n    procedure Parse(const Source: UTF8String); overload;\n    procedure Parse(const Source: UnicodeString); overload;\n\n    property Context: TChakraCoreContext read FContext;\n    property Handle: JsModuleRecord read FHandle;\n    property Name: UnicodeString read FName;\n    property Parsed: Boolean read FParsed;\n    property Result: JsValueRef read FResult;\n    property URL: UnicodeString read FURL write SetURL;\n  end;\n\n  TNativeObject = class;\n  TNativeClass = class of TNativeObject;\n\n  TLoadModuleEvent = procedure(Sender: TObject; Module: TChakraModule) of object;\n  TNativeObjectCreatedEvent = procedure(Sender: TObject; NativeObject: TNativeObject) of object;\n\n  { TChakraCoreContext }\n\n  TChakraCoreContext = class\n  private\n    FClassInfos: TList;\n    FGlobal: JsValueRef;\n    FHandle: JsContextRef;\n    FMessageQueue: TQueue;\n    FModules: TStringList;\n    FRuntime: TChakraCoreRuntime;\n    FSourceContext: NativeUInt;\n\n    FOnActivate: TNotifyEvent;\n    FOnLoadModule: TLoadModuleEvent;\n    FOnNativeObjectCreated: TNativeObjectCreatedEvent;\n\n    function AddClassInfo(AClass: TNativeClass; AConstructor, APrototype: JsValueRef): Integer;\n    function FindClassInfo(AClass: TNativeClass): Pointer; overload;\n    function FindClassInfo(AConstructor: JsValueRef): Pointer; overload;\n    function GetData: Pointer;\n    function GetHandle: JsContextRef;\n    function GetGlobal: JsValueRef;\n    function GetModuleCount: Integer;\n    function GetModuleNames(Index: Integer): UnicodeString;\n    function GetModules(Index: Integer): TChakraModule;\n    procedure SetData(Value: Pointer);\n  protected\n    procedure ClearModules;\n    function CreateModule(const AName: UnicodeString; ARefModule: JsModuleRecord): TChakraModule; virtual;\n    procedure DoActivate; virtual;\n    procedure DoLoadModule(Module: TChakraModule); virtual;\n    procedure DoNativeObjectCreated(NativeObject: TNativeObject); virtual;\n    procedure DoPromiseContinuation(Task: JsValueRef); virtual;\n    function HandleFetchImportedModuleCallback(referencingModule: JsModuleRecord; specifier: JsValueRef;\n      out dependentModuleRecord: JsModuleRecord): JsErrorCode; virtual;\n    function HandleFetchImportedModuleFromScriptCallback(dwReferencingSourceContext: JsSourceContext;\n      specifier: JsValueRef; out dependentModuleRecord: JsModuleRecord): JsErrorCode; virtual;\n    function HandleNotifyModuleReadyCallback(referencingModule: JsModuleRecord; exceptionVar: JsValueRef): JsErrorCode;\n      virtual;\n    function ModuleNeeded(const AName: UnicodeString; ARefModule: JsModuleRecord = nil): TChakraModule;\n    procedure ProcessMessages;\n  public\n    constructor Create(ARuntime: TChakraCoreRuntime);\n    destructor Destroy; override;\n\n    procedure Activate;\n    procedure AddModule(const AName: UTF8String); overload;\n    procedure AddModule(const AName: UnicodeString); overload;\n    function CallFunction(Func: JsValueRef; Args: PJsValueRef; ArgCount: Word): JsValueRef; overload;\n    function CallFunction(Func: JsValueRef; const Args: array of JsValueRef; ThisArg: JsValueRef = nil): JsValueRef;\n      overload;\n    function CallFunction(const AName: UTF8String; const Args: array of JsValueRef;\n      ThisArg: JsValueRef = nil): JsValueRef; overload;\n    function CallFunction(const AName: UnicodeString; const Args: array of JsValueRef;\n      ThisArg: JsValueRef = nil): JsValueRef; overload;\n    function CallNew(const AConstructorName: UTF8String; const Args: array of JsValueRef): JsValueRef; overload;\n    function CallNew(const AConstructorName: UnicodeString; const Args: array of JsValueRef): JsValueRef; overload;\n    class function CurrentContext: TChakraCoreContext;\n    function FindModule(const AName: UnicodeString): TChakraModule; overload;\n    function FindModule(AHandle: JsModuleRecord): TChakraModule; overload;\n    procedure PostMessage(AMessage: TBaseMessage);\n    function RunScript(const Script, AName: UTF8String; IsLibraryCode: Boolean = False): JsValueRef; overload;\n    function RunScript(const Script, AName: UnicodeString; IsLibraryCode: Boolean = False): JsValueRef; overload;\n\n    property Data: Pointer read GetData write SetData;\n    property Global: JsValueRef read GetGlobal;\n    property Handle: JsContextRef read GetHandle;\n    property ModuleCount: Integer read GetModuleCount;\n    property ModuleNames[Index: Integer]: UnicodeString read GetModuleNames;\n    property Modules[Index: Integer]: TChakraModule read GetModules;\n    property Runtime: TChakraCoreRuntime read FRuntime;\n\n    property OnActivate: TNotifyEvent read FOnActivate write FOnActivate;\n    property OnLoadModule: TLoadModuleEvent read FOnLoadModule write FOnLoadModule;\n    property OnNativeObjectCreated: TNativeObjectCreatedEvent read FOnNativeObjectCreated write FOnNativeObjectCreated;\n  end;\n\n  { TNativeArrayBuffer }\n\n  TChakraCoreNativeArrayBuffer = class\n  private\n    FBuffer: Pointer;\n    FBufferSize: Integer;\n    FHandle: JsValueRef;\n  public\n    constructor Create(ABufferSize: Integer); virtual;\n    destructor Destroy; override;\n\n    property Buffer: Pointer read FBuffer;\n    property BufferSize: Integer read FBufferSize;\n    property Handle: JsValueRef read FHandle;\n  end;\n\n  TNativeMethod = function(Args: PJsValueRef; ArgCount: Word): JsValueRef of object;\n  TNativeGetAccessorMethod = function: JsValueRef of object;\n  TNativeSetAccessorMethod = procedure(Value: JsValueRef) of object;\n\n  { TNativeObject }\n\n  TNativeObject = class\n  private\n    FInstance: JsValueRef;\n\n    function GetContext: TChakraCoreContext;\n    function GetContextHandle: JsContextRef;\n  protected\n    class function FindConstructor: JsValueRef;\n    class function FindParentConstructor: JsValueRef;\n    class function FindPrototype: JsValueRef;\n    class procedure InitializeInstance(AInstance: JsValueRef; Args: PJsValueRef; ArgCount: Word); virtual;\n    class function InitializePrototype(AConstructor: JsValueRef): JsValueRef; virtual;\n    class procedure RegisterClassMethod(AConstructor: JsValueRef; const AName: UnicodeString; AMethod: Pointer;\n      UseStrictRules: Boolean = True); virtual;\n    class procedure RegisterMethod(AInstance: JsValueRef; const AName: UnicodeString; AMethod: Pointer;\n      UseStrictRules: Boolean = True); virtual;\n    class procedure RegisterMethods(AInstance: JsValueRef); virtual;\n    class procedure RegisterNamedProperty(AInstance: JsValueRef; const AName: UnicodeString;\n      Configurable, Enumerable: Boolean; GetAccessor, SetAccessor: Pointer); overload; virtual;\n    class procedure RegisterNamedProperty(AInstance: JsValueRef; const AName: UnicodeString;\n      Configurable, Enumerable, Writable: Boolean; Value: JsValueRef); overload; virtual;\n    class procedure RegisterProperties(AInstance: JsValueRef); virtual;\n  public\n    constructor Create(Args: PJsValueRef = nil; ArgCount: Word = 0; AFinalize: Boolean = False); overload; virtual;\n    constructor Create(const Args: array of JsValueRef; AFinalize: Boolean = False); overload; virtual;\n    destructor Destroy; override;\n\n    function AddRef: Integer;\n    class procedure Project(const AName: UnicodeString = ''; Scope: JsValueRef = nil; UseStrictRules: Boolean = True);\n      overload; virtual;\n    function Release: Integer;\n\n    property Context: TChakraCoreContext read GetContext;\n    property ContextHandle: JsContextRef read GetContextHandle;\n    property Instance: JsValueRef read FInstance;\n  end;\n\nimplementation\n\ntype\n  PNativeClassInfo = ^TNativeClassInfo;\n  TNativeClassInfo = record\n    AClass: TNativeClass;\n    AConstructor: JsValueRef;\n    APrototype: JsValueRef;\n  end;\n\nprocedure BeforeCollectCallback(callbackState: Pointer); {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  if Assigned(callbackState) then\n    TChakraCoreRuntime(callbackState).DoBeforeCollect;\nend;\n\nfunction ThreadServiceCallback(callback: JsBackgroundWorkItemCallback; callbackState: Pointer): bool;\n  {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := False; // let ChakraCore handle this work item\n\n  // TODO\n  // Result := True;\n  // CurrentRuntime.DoBackgroundWork(callback, callbackState);\nend;\n\nfunction FetchImportedModuleCallBack(referencingModule: JsModuleRecord; specifier: JsValueRef;\n  out dependentModuleRecord: JsModuleRecord): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := TChakraCoreContext.CurrentContext.HandleFetchImportedModuleCallback(referencingModule, specifier,\n    dependentModuleRecord);\nend;\n\nfunction FetchImportedModuleFromScriptCallBack(dwReferencingSourceContext: JsSourceContext; specifier: JsValueRef;\n  out dependentModuleRecord: JsModuleRecord): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := TChakraCoreContext.CurrentContext.HandleFetchImportedModuleFromScriptCallback(dwReferencingSourceContext,\n    specifier, dependentModuleRecord);\nend;\n\nfunction MemoryAllocationCallback(callbackState: Pointer; allocationEvent: JsMemoryEventType;\n  allocationSize: size_t): bool; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := True;\n\n  if Assigned(callbackState) then\n    case allocationEvent of\n      JsMemoryAllocate:\n        Result := TChakraCoreRuntime(callbackState).DoMemAlloc(allocationSize);\n      JsMemoryFree:\n        TChakraCoreRuntime(callbackState).DoMemFree(allocationSize);\n      JsMemoryFailure:\n        TChakraCoreRuntime(callbackState).DoMemFailure(allocationSize);\n    end;\nend;\n\nprocedure Native_FinalizeCallback(data: Pointer); {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  TObject(data).Free;\nend;\n\nfunction Native_ConstructorCallback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRef; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nvar\n  NativeClass: TNativeClass absolute CallbackState;\n  NativeInstance: TNativeObject;\nbegin\n  Result := JsUndefinedValue;\n  try\n    if not Assigned(CallbackState) then\n      raise Exception.Create('Native constructor callback: state not assigned');\n\n    if not Assigned(Args) then\n      raise Exception.Create('Native constructor callback: arguments not assigned');\n\n    if ArgCount < 1 then\n      raise Exception.CreateFmt('Native constructor callback: invalid argument count %d', [ArgCount]);\n\n    if IsConstructCall then\n    begin\n      Inc(Args);\n      Dec(ArgCount);\n\n      NativeInstance := NativeClass.Create(Pointer(Args), ArgCount, True);\n      Result := NativeInstance.Instance;\n    end\n    else\n    begin\n      Result := Args^;\n\n      Inc(Args);\n      Dec(ArgCount);\n\n      NativeClass.InitializeInstance(Result, Args, ArgCount);\n    end;\n  except on E: Exception do\n    JsThrowError(WideFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction Native_GetConstructorCallback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRef; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nvar\n  NativeClass: TNativeClass absolute CallbackState;\n  Context: TChakraCoreContext;\n  Info: PNativeClassInfo;\n  AConstructor, APrototype: JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n  try\n    if not Assigned(CallbackState) then\n      raise Exception.Create('Native constructor getter callback: state not assigned');\n\n    if IsConstructCall then\n      raise Exception.Create('Native constructor getter callback: called as a constructor');\n\n    Context := TChakraCoreContext.CurrentContext;\n    Info := Context.FindClassInfo(NativeClass);\n    if Assigned(Info) then\n      Result := Info^.AConstructor\n    else\n    begin\n      AConstructor := JsCreateFunction(Native_ConstructorCallback, CallbackState,\n        JsStringToUnicodeString(JsGetProperty(Callee, 'name')));\n      JsAddRef(AConstructor);\n      APrototype := NativeClass.InitializePrototype(AConstructor);\n      NativeClass.RegisterMethods(APrototype);\n      NativeClass.RegisterProperties(APrototype);\n      JsSetProperty(AConstructor, 'prototype', APrototype);\n      JsSetProperty(APrototype, 'constructor', AConstructor);\n      Context.AddClassInfo(NativeClass, AConstructor, APrototype);\n      Result := AConstructor;\n    end;\n  except\n    on E: Exception do\n      JsThrowError(Format('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction Native_ClassMethodCallback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRef;\n  ArgCount: Word; CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nvar\n  Context: TChakraCoreContext;\n  Info: PNativeClassInfo;\n  NativeMethod: TNativeMethod;\nbegin\n  Result := JsUndefinedValue;\n  try\n    if not Assigned(CallbackState) then\n      raise Exception.Create('Native class method callback: state not assigned');\n\n    if IsConstructCall then\n      raise Exception.Create('Native class method callback: called as a constructor');\n\n    if not Assigned(Args) then\n      raise Exception.Create('Native class method callback: arguments not assigned');\n\n    if ArgCount < 1 then\n      raise Exception.CreateFmt('Native class method callback: invalid argument count %d', [ArgCount]);\n\n    if (JsGetValueType(Args^) <> JsFunction) then\n      raise Exception.Create('Native class method callback: thisarg not a function');\n\n    Context := TChakraCoreContext.CurrentContext;\n    Info := Context.FindClassInfo(Args^);\n    if not Assigned(Info) then\n      raise Exception.CreateFmt('Native class not found for %s', [JsStringToUnicodeString(JsGetProperty(Args^, 'name'))]);\n\n    TMethod(NativeMethod).Code := CallbackState;\n    TMethod(NativeMethod).Data := Info^.AClass;\n\n    Inc(Args);\n    Dec(ArgCount);\n\n    Result := NativeMethod(Args, ArgCount);\n  except\n    on E: Exception do\n      JsThrowError(WideFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction Native_MethodCallback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRef;\n  ArgCount: Word; CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nvar\n  NativeMethod: TNativeMethod;\nbegin\n  Result := JsUndefinedValue;\n  try\n    if not Assigned(CallbackState) then\n      raise Exception.Create('Native method callback: state not assigned');\n\n    if IsConstructCall then\n      raise Exception.Create('Native method callback: called as a constructor');\n\n    if not Assigned(Args) then\n      raise Exception.Create('Native method callback: arguments not assigned');\n\n    if ArgCount < 1 then\n      raise Exception.CreateFmt('Native method callback: invalid argument count %d', [ArgCount]);\n\n    if (JsGetValueType(Args^) <> JsObject) then\n      raise Exception.Create('Native method callback: thisarg not an object');\n\n    TMethod(NativeMethod).Code := CallbackState;\n    TMethod(NativeMethod).Data := JsGetExternalData(Args^);\n\n    if not Assigned(TMethod(NativeMethod).Data) then\n      raise Exception.Create('Native method callback: external data not assigned');\n\n    if Args^ <> TNativeObject(TMethod(NativeMethod).Data).Instance then\n      raise Exception.Create('Native method callback: thisarg not the registered instance');\n\n    Inc(Args);\n    Dec(ArgCount);\n\n    Result := NativeMethod(Args, ArgCount);\n  except\n    on E: Exception do\n      JsThrowError(WideFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction Native_PropGetCallback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRef; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nvar\n  NativeMethod: TNativeGetAccessorMethod;\nbegin\n  Result := JsUndefinedValue;\n  try\n    if not Assigned(CallbackState) then\n      raise Exception.Create('Native getter callback: state not assigned');\n\n    if IsConstructCall then\n      raise Exception.Create('Native getter callback: called as a constructor');\n\n    if not Assigned(Args) then\n      raise Exception.Create('Native getter callback: arguments not assigned');\n\n    if ArgCount <> 1 then // thisarg\n      raise Exception.CreateFmt('Native getter callback: invalid argument count %d', [ArgCount]);\n\n    TMethod(NativeMethod).Code := CallbackState;\n    TMethod(NativeMethod).Data := JsGetExternalData(Args^);\n\n    if not Assigned(TMethod(NativeMethod).Data) then\n      raise Exception.Create('Native getter callback: external data not assigned');\n\n    if Args^ <> TNativeObject(TMethod(NativeMethod).Data).Instance then\n      raise Exception.Create('Native getter callback: thisarg not the registered instance');\n\n    Result := NativeMethod;\n  except\n    on E: Exception do\n      JsThrowError(WideFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction Native_PropSetCallback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRefArray; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nvar\n  NativeMethod: TNativeSetAccessorMethod;\nbegin\n  Result := JsUndefinedValue;\n  try\n    if not Assigned(CallbackState) then\n      raise Exception.Create('Native setter callback: state not assigned');\n\n    if IsConstructCall then\n      raise Exception.Create('Native setter callback: called as a constructor');\n\n    if not Assigned(Args) then\n      raise Exception.Create('Native setter callback: arguments not assigned');\n\n    if ArgCount <> 2 then // thisarg, value\n      raise Exception.CreateFmt('Native setter callback: invalid argument count %d', [ArgCount]);\n\n    TMethod(NativeMethod).Code := CallbackState;\n    TMethod(NativeMethod).Data := JsGetExternalData(Args^[0]);\n\n    if not Assigned(TMethod(NativeMethod).Data) then\n      raise Exception.Create('Native setter callback: external data not assigned');\n\n    if Args^[0] <> TNativeObject(TMethod(NativeMethod).Data).Instance then\n      raise Exception.Create('Native setter callback: thisarg not the registered instance');\n\n    NativeMethod(Args^[1]);\n  except\n    on E: Exception do\n      JsThrowError(WideFormat('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction NotifyModuleReadyCallback(referencingModule: JsModuleRecord; exceptionVar: JsValueRef): JsErrorCode;\n  {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := TChakraCoreContext.CurrentContext.HandleNotifyModuleReadyCallback(referencingModule, exceptionVar);\nend;\n\nfunction RuntimeOptionsToJsRuntimeAttributes(Value: TChakraCoreRuntimeOptions): Cardinal;\nbegin\n  Result := JsRuntimeAttributeNone;\n  if ccroDisableBackgroundWork in Value then\n    Result := Result or JsRuntimeAttributeDisableBackgroundWork;\n  if ccroAllowScriptInterrupt in Value then\n    Result := Result or JsRuntimeAttributeAllowScriptInterrupt;\n  if ccroEnableIdleProcessing in Value then\n    Result := Result or JsRuntimeAttributeEnableIdleProcessing;\n  if ccroDisableNativeCodeGeneration in Value then\n    Result := Result or JsRuntimeAttributeDisableNativeCodeGeneration;\n  if ccroDisableEval in Value then\n    Result := Result or JsRuntimeAttributeDisableEval;\n  if ccroEnableExperimentalFeatures in Value then\n    Result := Result or JsRuntimeAttributeEnableExperimentalFeatures;\n  if ccroDispatchSetExceptionsToDebugger in Value then\n    Result := Result or JsRuntimeAttributeDispatchSetExceptionsToDebugger;\n  if ccroDisableFatalOnOOM in Value then\n    Result := Result or JsRuntimeAttributeDisableFatalOnOOM;\n  if ccroDisableExecutablePageAllocation in Value then\n    Result := Result or JsRuntimeAttributeDisableExecutablePageAllocation;\nend;\n\n{ TChakraCoreRuntime private }\n\nfunction TChakraCoreRuntime.GetEnabled: Boolean;\nvar\n  Disabled: ByteBool;\nbegin\n  if FHandle = JS_INVALID_RUNTIME_HANDLE then\n    Result := False\n  else\n  begin\n    ChakraCoreCheck(JsIsRuntimeExecutionDisabled(FHandle, Disabled));\n    Result := not Disabled;\n  end;\nend;\n\nfunction TChakraCoreRuntime.GetHandle: JsRuntimeHandle;\nbegin\n  if FHandle = JS_INVALID_RUNTIME_HANDLE then\n    CreateRuntime;\n  Result := FHandle;\nend;\n\nfunction TChakraCoreRuntime.GetMemoryLimit: NativeUInt;\nbegin\n  if FHandle <> JS_INVALID_RUNTIME_HANDLE then\n    ChakraCoreCheck(JsGetRuntimeMemoryLimit(FHandle, FMemoryLimit));\n  Result := FMemoryLimit;\nend;\n\nfunction TChakraCoreRuntime.GetMemoryUsage: NativeUInt;\nbegin\n  Result := 0;\n  if FHandle <> JS_INVALID_RUNTIME_HANDLE then\n    ChakraCoreCheck(JsGetRuntimeMemoryUsage(FHandle, Result));\nend;\n\nprocedure TChakraCoreRuntime.SetEnabled(Value: Boolean);\nbegin\n  if Value <> Enabled then\n  begin\n    if Value then\n      ChakraCoreCheck(JsEnableRuntimeExecution(Handle))\n    else\n      ChakraCoreCheck(JsDisableRuntimeExecution(Handle));\n  end;\nend;\n\nprocedure TChakraCoreRuntime.SetMemoryLimit(Value: NativeUInt);\nbegin\n  if Value <> FMemoryLimit then\n  begin\n    if FHandle <> JS_INVALID_RUNTIME_HANDLE then\n      ChakraCoreCheck(JsSetRuntimeMemoryLimit(FHandle, Value));\n\n    FMemoryLimit := Value;\n  end;\nend;\n\nprocedure TChakraCoreRuntime.SetOnBeforeCollect(Value: TNotifyEvent);\nbegin\n  if @Value <> @FOnBeforeCollect then\n  begin\n    FOnBeforeCollect := Value;\n  end;\nend;\n\nprocedure TChakraCoreRuntime.SetOnMemAlloc(Value: TMemAllocEvent);\nbegin\n  if @Value <> @FOnMemAlloc then\n  begin\n    if FHandle <> JS_INVALID_RUNTIME_HANDLE then\n    begin\n      if Assigned(Value) or Assigned(FOnMemFailure) or Assigned(FOnMemFree) then\n        ChakraCoreCheck(JsSetRuntimeMemoryAllocationCallback(FHandle, Self, MemoryAllocationCallback))\n      else\n        ChakraCoreCheck(JsSetRuntimeMemoryAllocationCallback(FHandle, Self, nil));\n    end;\n\n    FOnMemAlloc := Value;\n  end;\nend;\n\nprocedure TChakraCoreRuntime.SetOnMemFailure(Value: TMemFailureEvent);\nbegin\n  if @Value <> @FOnMemFailure then\n  begin\n    if FHandle <> JS_INVALID_RUNTIME_HANDLE then\n    begin\n      if Assigned(Value) or Assigned(FOnMemAlloc) or Assigned(FOnMemFree) then\n        ChakraCoreCheck(JsSetRuntimeMemoryAllocationCallback(FHandle, Self, MemoryAllocationCallback))\n      else\n        ChakraCoreCheck(JsSetRuntimeMemoryAllocationCallback(FHandle, Self, nil));\n    end;\n\n    FOnMemFailure := Value;\n  end;\nend;\n\nprocedure TChakraCoreRuntime.SetOnMemFree(Value: TMemFreeEvent);\nbegin\n  if @Value <> @FOnMemFree then\n  begin\n    if FHandle <> JS_INVALID_RUNTIME_HANDLE then\n    begin\n      if Assigned(Value) or Assigned(FOnMemAlloc) or Assigned(FOnMemFailure) then\n        ChakraCoreCheck(JsSetRuntimeMemoryAllocationCallback(FHandle, Self, MemoryAllocationCallback))\n      else\n        ChakraCoreCheck(JsSetRuntimeMemoryAllocationCallback(FHandle, Self, nil));\n    end;\n\n    FOnMemFree := Value;\n  end;\nend;\n\n{ TChakraCoreRuntime protected }\n\nprocedure TChakraCoreRuntime.CreateRuntime;\nbegin\n  if FHandle <> JS_INVALID_RUNTIME_HANDLE then\n    Exit;\n\n  ChakraCoreCheck(JsCreateRuntime(JsRuntimeAttributes(RuntimeOptionsToJsRuntimeAttributes(FOptions)),\n    ThreadServiceCallback, FHandle));\n  try\n    if NativeInt(FMemoryLimit) <> -1 then\n      ChakraCoreCheck(JsSetRuntimeMemoryLimit(FHandle, FMemoryLimit));\n    if Assigned(FOnMemAlloc) or Assigned(FOnMemFailure) or Assigned(FOnMemFree) then\n      ChakraCoreCheck(JsSetRuntimeMemoryAllocationCallback(FHandle, Self, MemoryAllocationCallback));\n    if Assigned(FOnBeforeCollect) then\n      ChakraCoreCheck(JsSetRuntimeBeforeCollectCallback(FHandle, Self, BeforeCollectCallback));\n  except\n    JsDisposeRuntime(FHandle);\n    FHandle := JS_INVALID_RUNTIME_HANDLE;\n    raise;\n  end;\nend;\n\nprocedure TChakraCoreRuntime.DisposeRuntime;\nbegin\n  if FHandle = JS_INVALID_RUNTIME_HANDLE then\n    Exit;\n\n  ChakraCoreCheck(JsSetCurrentContext(JS_INVALID_REFERENCE));\n  ChakraCoreCheck(JsSetRuntimeMemoryAllocationCallback(FHandle, Self, nil));\n  ChakraCoreCheck(JsDisposeRuntime(FHandle));\n  FHandle := JS_INVALID_RUNTIME_HANDLE;\nend;\n\nprocedure TChakraCoreRuntime.DoBeforeCollect;\nbegin\n  if Assigned(FOnBeforeCollect) then\n    FOnBeforeCollect(Self);\nend;\n\nfunction TChakraCoreRuntime.DoMemAlloc(Size: NativeUInt): Boolean;\nbegin\n  Result := True;\n  if Assigned(FOnMemAlloc) then\n    FOnMemAlloc(Self, Size, Result);\nend;\n\nprocedure TChakraCoreRuntime.DoMemFailure(Size: NativeUInt);\nbegin\n  if Assigned(FOnMemFailure) then\n    FOnMemFailure(Self, Size);\nend;\n\nprocedure TChakraCoreRuntime.DoMemFree(Size: NativeUInt);\nbegin\n  if Assigned(FOnMemFree) then\n    FOnMemFree(Self, Size);\nend;\n\n{ TChakraCoreRuntime public }\n\nconstructor TChakraCoreRuntime.Create(AOptions: TChakraCoreRuntimeOptions);\nbegin\n  inherited Create;\n  FHandle := JS_INVALID_RUNTIME_HANDLE;\n  FMemoryLimit := NativeUInt(NativeInt(-1));\n  FOnMemAlloc := nil;\n  FOnMemFailure := nil;\n  FOnMemFree := nil;\n  FOptions := AOptions;\nend;\n\ndestructor TChakraCoreRuntime.Destroy;\nbegin\n  DisposeRuntime;\n  inherited Destroy;\nend;\n\nprocedure TChakraCoreRuntime.CollectGarbage;\nbegin\n  if Enabled then\n    ChakraCoreCheck(JsCollectGarbage(Handle));\nend;\n\n{ TBaseMessage public }\n\nconstructor TBaseMessage.Create(AContext: TChakraCoreContext);\nbegin\n  inherited Create;\n  FContext := AContext;\nend;\n\n{ TCallbackMessage protected }\n\nfunction TTaskMessage.Process(out ResultValue: JsValueRef): Boolean;\nvar\n  Ticks: Cardinal;\nbegin\n  ResultValue := JsUndefinedValue;\n  Ticks := GetTickCount;\n  Result := Ticks >= FTime + FDelay;\n  if Result then\n  begin\n    ResultValue := JsCallFunction(FTask, @FArgs^[0], FArgCount + 1);\n\n    if FRepeatCount > 0 then\n      Dec(FRepeatCount);\n    if FRepeatCount = 0 then\n      Exit;\n\n    Result := False;\n    ResultValue := JsUndefinedValue;\n    FTime := GetTickCount;\n  end;\nend;\n\n{ TCallbackMessage public }\n\nconstructor TTaskMessage.Create(AContext: TChakraCoreContext; Task, ThisArg: JsValueRef;\n  const Args: array of JsValueRef; ADelay: Cardinal; ARepeatCount: Integer);\nvar\n  I: Integer;\nbegin\n  inherited Create(AContext);\n  FTask := Task;\n  JsAddRef(FTask);\n\n  FArgCount := Length(Args);\n  FArgs := AllocMem((FArgCount + 1) * SizeOf(PJsValueRef));\n  if Assigned(ThisArg) then\n    FArgs^[0] := ThisArg\n  else\n    FArgs^[0] := Context.Global;\n  JsAddRef(FArgs^[0]);\n\n  for I := 1 to FArgCount do\n  begin\n    FArgs^[I] := Args[I - 1];\n    JsAddRef(FArgs^[I]);\n  end;\n\n  FDelay := ADelay;\n  FRepeatCount := ARepeatCount;\n  FTime := GetTickCount;\nend;\n\ndestructor TTaskMessage.Destroy;\nvar\n  I: Integer;\nbegin\n  if Assigned(FArgs) then\n  begin\n    for I := 0 to FArgCount do\n      if Assigned(FArgs^[I]) then\n        JsRelease(FArgs^[I]);\n    FreeMem(FArgs);\n  end;\n  FArgs := nil;\n  FArgCount := 0;\n  if Assigned(FTask) then\n    JsRelease(FTask);\n  FTask := nil;\n  inherited Destroy;\nend;\n\n{ TPromiseMessage protected }\n\nfunction TPromiseMessage.Process(out ResultValue: JsHandle): Boolean;\nbegin\n  Result := False;\n  ResultValue := JsUndefinedValue;\n  case FStatus of\n    psPending:\n      Exit;\n    psResolved:\n      ResultValue := JsCallFunction(FResolveTask, @FArgs[0], 2);\n    psRejected:\n      ResultValue := JsCallFunction(FRejectTask, @Fargs[0], 2);\n  end;\n  Result := True;\nend;\n\nprocedure TPromiseMessage.SetStatus(Value: TPromiseStatus; StatusValue: JsValueRef);\nbegin\n  FArgs[1] := StatusValue;\n  FStatus := Value;\nend;\n\n{ TPromiseMessage public }\n\nconstructor TPromiseMessage.Create(AContext: TChakraCoreContext; ThisArg, ResolveTask, RejectTask: JsValueRef);\nbegin\n  inherited Create(AContext);\n  FArgs[0] := ThisArg;\n  JsAddRef(FArgs[0]);\n  FArgs[1] := nil;\n  FResolveTask := ResolveTask;\n  JsAddRef(FResolveTask);\n  FRejectTask := RejectTask;\n  JsAddRef(FRejectTask);\nend;\n\ndestructor TPromiseMessage.Destroy;\nbegin\n  if Assigned(FRejectTask) then\n    JsRelease(FRejectTask);\n  FRejectTask := nil;\n  if Assigned(FResolveTask) then\n    JsRelease(FResolveTask);\n  FResolveTask := nil;\n  if Assigned(FArgs[0]) then\n    JsRelease(FArgs[0]);\n  FArgs[0] := nil;\n  if Assigned(FArgs[1]) then\n    JsRelease(FArgs[1]);\n  FArgs[1] := nil;\n  inherited Destroy;\nend;\n\n{ TModuleMessage protected }\n\nfunction TModuleMessage.Process(out ResultValue: JsValueRef): Boolean;\nbegin\n  ChakraCoreCheck(JsModuleEvaluation(FModule.Handle, FModule.FResult));\n  Result := True;\n  ResultValue := FModule.FResult;\nend;\n\n{ TModuleMessage public }\n\nconstructor TModuleMessage.Create(AContext: TChakraCoreContext; AModule: TChakraModule);\nbegin\n  inherited Create(AContext);\n  FModule := AModule;\nend;\n\n{ TChakraModule public }\n\nconstructor TChakraModule.Create(AContext: TChakraCoreContext; const AName: UnicodeString; ARefModule: JsModuleRecord);\nvar\n  Specifier: JsValueRef;\nbegin\n  inherited Create;\n  FContext := AContext;\n  FName := AName;\n  FURL := '';\n\n  FResult := JsUndefinedValue;\n  Specifier := JS_INVALID_REFERENCE;\n  if AName <> '' then\n    Specifier := StringToJsString(AName);\n\n  ChakraCoreCheck(JsInitializeModuleRecord(ARefModule, Specifier, FHandle));\n  ChakraCoreCheck(JsSetModuleHostInfo(FHandle, JsModuleHostInfo_FetchImportedModuleCallback, @FetchImportedModuleCallback));\n  ChakraCoreCheck(JsSetModuleHostInfo(FHandle, JsModuleHostInfo_FetchImportedModuleFromScriptCallback, @FetchImportedModuleFromScriptCallback));\n  ChakraCoreCheck(JsSetModuleHostInfo(FHandle, JsModuleHostInfo_NotifyModuleReadyCallback, @NotifyModuleReadyCallback));\n  ChakraCoreCheck(JsSetModuleHostInfo(FHandle, JsModuleHostInfo_HostDefined, Specifier));\nend;\n\nprocedure TChakraModule.Parse(const Source: UTF8String);\nvar\n  Error: JsValueRef;\nbegin\n  if not FParsed then\n  begin\n    ChakraCoreCheck(JsParseModuleSource(Handle, 0, PByte(PAnsiChar(Source)), Length(Source),\n      JsParseModuleSourceFlags_DataIsUTF8, Error));\n    FParsed := True;\n  end;\nend;\n\nprocedure TChakraModule.Parse(const Source: UnicodeString);\nvar\n  Error: JsValueRef;\nbegin\n  if not FParsed then\n  begin\n    ChakraCoreCheck(JsParseModuleSource(Handle, 0, PByte(PUnicodeChar(Source)), Length(Source) * SizeOf(UnicodeChar),\n      JsParseModuleSourceFlags_DataIsUTF16LE, Error));\n    FParsed := True;\n  end;\nend;\n\nprocedure TChakraModule.SetURL(const Value: UnicodeString);\nvar\n  Specifier: JsValueRef;\nbegin\n  if Value <> FURL then\n  begin\n    Specifier := JS_INVALID_REFERENCE;\n    if Value <> '' then\n      Specifier := StringToJsString(Value);\n\n    ChakraCoreCheck(JsSetModuleHostInfo(FHandle, JsModuleHostInfo_Url, Specifier));\n\n    FURL := Value;\n  end;\nend;\n\nprocedure PromiseContinuation(task: JsValueRef; callbackState: Pointer); {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  if Assigned(callbackState) then\n    TChakraCoreContext(callbackState).DoPromiseContinuation(task);\nend;\n\n{ TChakraCoreContext private }\n\nfunction TChakraCoreContext.AddClassInfo(AClass: TNativeClass; AConstructor, APrototype: JsValueRef): Integer;\nvar\n  Info: PNativeClassInfo;\nbegin\n  if JsGetValueType(AConstructor) <> JsFunction then\n    raise Exception.CreateFmt('Constructor for native class ''%s'' not a function', [AClass.ClassName]);\n\n  if not Assigned(APrototype) then\n    APrototype := JsGetProperty(AConstructor, UnicodeString('prototype'));\n\n  if JsGetValueType(APrototype) <> JsObject then\n    raise Exception.CreateFmt('Prototype for native class ''%s'' not an object', [AClass.ClassName]);\n\n  GetMem(Info, SizeOf(TNativeClassInfo));\n  try\n    Info^.AClass := AClass;\n    Info^.AConstructor := AConstructor;\n    Info^.APrototype := APrototype;\n    Result := FClassInfos.Add(Info);\n  except\n    FreeMem(Info);\n    raise;\n  end;\nend;\n\nfunction TChakraCoreContext.FindClassInfo(AClass: TNativeClass): Pointer;\nvar\n  I: Integer;\n  Info: PNativeClassInfo;\nbegin\n  Result := nil;\n\n  for I := 0 to FClassInfos.Count - 1 do\n  begin\n    Info := FClassInfos[I];\n    if Info^.AClass = AClass then\n    begin\n      Result := Info;\n      Break;\n    end;\n  end;\nend;\n\nfunction TChakraCoreContext.FindClassInfo(AConstructor: JsValueRef): Pointer;\nvar\n  I: Integer;\n  Info: PNativeClassInfo;\nbegin\n  Result := nil;\n\n  for I := 0 to FClassInfos.Count - 1 do\n  begin\n    Info := FClassInfos[I];\n    if Info^.AConstructor = AConstructor then\n    begin\n      Result := Info;\n      Break;\n    end;\n  end;\nend;\n\nfunction TChakraCoreContext.GetData: Pointer;\nbegin\n  ChakraCoreCheck(JsGetContextData(FHandle, Result));\nend;\n\nfunction TChakraCoreContext.GetGlobal: JsValueRef;\nbegin\n  if FGlobal = JS_INVALID_REFERENCE then\n    FGlobal := JsGlobal;\n  Result := FGlobal;\nend;\n\nfunction TChakraCoreContext.GetHandle: JsContextRef;\nbegin\n  if FHandle = JS_INVALID_REFERENCE then\n  begin\n    ChakraCoreCheck(JsCreateContext(FRuntime.Handle, FHandle));\n    ChakraCoreCheck(JsSetContextData(FHandle, Self));\n  end;\n  Result := FHandle;\nend;\n\nfunction TChakraCoreContext.GetModuleCount: Integer;\nbegin\n  Result := FModules.Count;\nend;\n\nfunction TChakraCoreContext.GetModuleNames(Index: Integer): UnicodeString;\nbegin\n{$ifdef UNICODE}\n  Result := FModules[Index];\n{$else}\n  Result := UTF8Decode(FModules[Index]);\n{$endif}\nend;\n\nfunction TChakraCoreContext.GetModules(Index: Integer): TChakraModule;\nbegin\n  Result := TChakraModule(FModules.Objects[Index]);\nend;\n\nprocedure TChakraCoreContext.SetData(Value: Pointer);\nbegin\n  ChakraCoreCheck(JsSetContextData(FHandle, Value));\nend;\n\n{ TChakraCoreContext protected }\n\nprocedure TChakraCoreContext.ClearModules;\nvar\n  I: Integer;\nbegin\n  for I := 0 to FModules.Count - 1 do\n    FModules.Objects[I].Free;\n  FModules.Clear;\nend;\n\nfunction TChakraCoreContext.CreateModule(const AName: UnicodeString; ARefModule: JsModuleRecord): TChakraModule;\nbegin\n  Result := TChakraModule.Create(Self, AName, ARefModule);\n  try\n{$ifdef UNICODE}\n    FModules.AddObject(AName, Result);\n{$else}\n    FModules.AddObject(UTF8Encode(AName), Result);\n{$endif}\n  except\n    Result.Free;\n    raise;\n  end;\nend;\n\nprocedure TChakraCoreContext.DoActivate;\nbegin\n  if Assigned(FOnActivate) then\n    FOnActivate(Self);\nend;\n\nprocedure TChakraCoreContext.DoLoadModule(Module: TChakraModule);\nbegin\n  if Assigned(FOnLoadModule) then\n    FOnLoadModule(Self, Module);\nend;\n\nprocedure TChakraCoreContext.DoNativeObjectCreated(NativeObject: TNativeObject);\nbegin\n  if Assigned(FOnNativeObjectCreated) then\n    FOnNativeObjectCreated(Self, NativeObject);\nend;\n\nprocedure TChakraCoreContext.DoPromiseContinuation(Task: JsValueRef);\nvar\n  AMessage: TTaskMessage;\nbegin\n  AMessage := TTaskMessage.Create(Self, Task, nil, []);\n  try\n    PostMessage(AMessage);\n  except\n    AMessage.Free;\n    raise;\n  end;\nend;\n\nfunction TChakraCoreContext.HandleFetchImportedModuleCallback(referencingModule: JsModuleRecord; specifier: JsValueRef;\n  out dependentModuleRecord: JsModuleRecord): JsErrorCode;\nvar\n  ModuleName: UnicodeString;\n  Module: TChakraModule;\nbegin\n  Result := JsNoError;\n  dependentModuleRecord := JS_INVALID_REFERENCE;\n\n  ModuleName := JsStringToUnicodeString(specifier);\n  Module := ModuleNeeded(ModuleName, referencingModule);\n\n  dependentModuleRecord := Module.Handle;\nend;\n\nfunction TChakraCoreContext.HandleFetchImportedModuleFromScriptCallback(dwReferencingSourceContext: JsSourceContext;\n  specifier: JsValueRef; out dependentModuleRecord: JsModuleRecord): JsErrorCode;\nvar\n  ModuleName: UnicodeString;\n  Module: TChakraModule;\nbegin\n  Result := JsNoError;\n  dependentModuleRecord := JS_INVALID_REFERENCE;\n\n  ModuleName := JsStringToUnicodeString(specifier);\n  Module := ModuleNeeded(ModuleName);\n\n  dependentModuleRecord := Module.Handle;\nend;\n\nfunction TChakraCoreContext.HandleNotifyModuleReadyCallback(referencingModule: JsModuleRecord; exceptionVar: JsValueRef): JsErrorCode;\nvar\n  Module: TChakraModule;\n  AMessage: TModuleMessage;\nbegin\n  Result := JsNoError;\n  if Assigned(exceptionVar) then\n    RaiseError(exceptionVar);\n\n  Module := FindModule(referencingModule);\n\n  if Assigned(Module) then\n  begin\n    AMessage := TModuleMessage.Create(Self, Module);\n    try\n      FMessageQueue.Push(AMessage);\n    except\n      AMessage.Free;\n      raise;\n    end;\n  end;\nend;\n\nfunction TChakraCoreContext.ModuleNeeded(const AName: UnicodeString; ARefModule: JsModuleRecord): TChakraModule;\nbegin\n  Result := FindModule(AName);\n\n  if not Assigned(Result) then\n  begin\n    Result := CreateModule(AName, ARefModule);\n    if AName <> '' then\n      DoLoadModule(Result);\n  end;\nend;\n\nprocedure TChakraCoreContext.ProcessMessages;\nvar\n  AMessage: TBaseMessage;\n  ResultValue: JsValueRef;\nbegin\n  while FMessageQueue.Count > 0 do\n  begin\n    AMessage := FMessageQueue.Pop;\n    if AMessage.Process(ResultValue) then\n      AMessage.Free\n    else\n      FMessageQueue.Push(AMessage);\n  end;\nend;\n\n{ TChakraCoreContext public }\n\nconstructor TChakraCoreContext.Create(ARuntime: TChakraCoreRuntime);\nbegin\n  inherited Create;\n  FMessageQueue := nil;\n  FModules := nil;\n  FRuntime := ARuntime;\n  FHandle := JS_INVALID_REFERENCE;\n  FGlobal := JS_INVALID_REFERENCE;\n  FMessageQueue := TQueue.Create;\n  FModules := TStringList.Create;\n  FModules.Duplicates := dupError;\n  FModules.Sorted := True;\n  FSourceContext := 0;\n  FClassInfos := TList.Create;\nend;\n\ndestructor TChakraCoreContext.Destroy;\nvar\n  I: Integer;\nbegin\n  for I := FClassInfos.Count - 1 downto 0 do\n  begin\n    JsRelease(PNativeClassInfo(FClassInfos[I])^.AConstructor);\n    FreeMem(FClassInfos[I]);\n  end;\n  FreeAndNil(FClassInfos);\n  FGlobal := JS_INVALID_REFERENCE;\n  FHandle := JS_INVALID_REFERENCE;\n  FRuntime := nil;\n  ClearModules;\n  FModules.Free;\n  FMessageQueue.Free;\n  inherited Destroy;\nend;\n\nprocedure TChakraCoreContext.Activate;\nbegin\n  ChakraCoreCheck(JsSetCurrentContext(Handle));\n  ChakraCoreCheck(JsSetPromiseContinuationCallback(PromiseContinuation, Self));\n  DoActivate;\nend;\n\nprocedure TChakraCoreContext.AddModule(const AName: UTF8String);\nbegin\n  AddModule(UTF8ToString(AName));\nend;\n\nprocedure TChakraCoreContext.AddModule(const AName: UnicodeString);\nbegin\n  Activate;\n  ModuleNeeded(AName);\nend;\n\nfunction TChakraCoreContext.CallFunction(Func: JsValueRef; Args: PJsValueRef; ArgCount: Word): JsValueRef;\nbegin\n  Result := JsCallFunction(Func, Args, ArgCount);\n  ProcessMessages;\nend;\n\nfunction TChakraCoreContext.CallFunction(Func: JsValueRef; const Args: array of JsValueRef;\n  ThisArg: JsValueRef): JsValueRef;\nbegin\n  Result := JsCallFunction(Func, Args, ThisArg);\n  ProcessMessages;\nend;\n\nfunction TChakraCoreContext.CallFunction(const AName: UTF8String; const Args: array of JsValueRef;\n  ThisArg: JsValueRef): JsValueRef;\nbegin\n  Result := JsCallFunction(AName, Args, ThisArg);\n  ProcessMessages;\nend;\n\nfunction TChakraCoreContext.CallFunction(const AName: UnicodeString; const Args: array of JsValueRef;\n  ThisArg: JsValueRef): JsValueRef;\nbegin\n  Result := CallFunction(UTF8Encode(AName), Args, ThisArg);\nend;\n\nfunction TChakraCoreContext.CallNew(const AConstructorName: UTF8String; const Args: array of JsValueRef): JsValueRef;\nbegin\n  Result := JsNew(AConstructorName, Args);\n  ProcessMessages;\nend;\n\nfunction TChakraCoreContext.CallNew(const AConstructorName: UnicodeString; const Args: array of JsValueRef): JsValueRef;\nbegin\n  Result := JsNew(AConstructorName, Args);\n  ProcessMessages;\nend;\n\nclass function TChakraCoreContext.CurrentContext: TChakraCoreContext;\nbegin\n  ChakraCoreCheck(JsGetContextData(JsGetCurrentContext, Pointer(Result)));\nend;\n\nfunction TChakraCoreContext.FindModule(const AName: UnicodeString): TChakraModule;\nvar\n  Index: Integer;\nbegin\n  Result := nil;\n\n  ProcessMessages;\n\n{$ifdef UNICODE}\n  if FModules.Find(AName, Index) then\n{$else}\n  if FModules.Find(UTF8Encode(AName), Index) then\n{$endif}\n    Result := Modules[Index];\nend;\n\nfunction TChakraCoreContext.FindModule(AHandle: JsModuleRecord): TChakraModule;\nvar\n  I: Integer;\nbegin\n  Result := nil;\n\n  for I := 0 to ModuleCount - 1 do\n    if Modules[I].Handle = AHandle then\n    begin\n      Result := Modules[I];\n      Break;\n    end;\nend;\n\nprocedure TChakraCoreContext.PostMessage(AMessage: TBaseMessage);\nbegin\n  FMessageQueue.Push(AMessage);\nend;\n\nfunction TChakraCoreContext.RunScript(const Script, AName: UTF8String; IsLibraryCode: Boolean): JsValueRef;\nbegin\n  if ModuleCount = 0 then\n    AddModule('');\n\n  Result := JsRunScript(Script, AName, FSourceContext, IsLibraryCode);\n  Inc(FSourceContext);\n  ProcessMessages;\nend;\n\nfunction TChakraCoreContext.RunScript(const Script, AName: UnicodeString; IsLibraryCode: Boolean): JsValueRef;\nbegin\n  if ModuleCount = 0 then\n    AddModule('');\n\n  Result := JsRunScript(Script, AName, FSourceContext, IsLibraryCode);\n  Inc(FSourceContext);\n  ProcessMessages;\nend;\n\n{ TChakraCoreNativeArrayBuffer public }\n\nconstructor TChakraCoreNativeArrayBuffer.Create(ABufferSize: Integer);\nbegin\n  inherited Create;\n  FBuffer := AllocMem(ABufferSize);\n  FBufferSize := ABufferSize;\n  ChakraCoreCheck(JsCreateExternalArrayBuffer(FBuffer, FBufferSize, Native_FinalizeCallback, Self, FHandle));\nend;\n\ndestructor TChakraCoreNativeArrayBuffer.Destroy;\nbegin\n  if Assigned(FBuffer) then\n    FreeMem(FBuffer);\n  inherited Destroy;\nend;\n\n{ TNativeObject private }\n\nfunction TNativeObject.GetContext: TChakraCoreContext;\nvar\n  P: Pointer absolute Result;\nbegin\n  ChakraCoreCheck(JsGetContextData(ContextHandle, P));\nend;\n\nfunction TNativeObject.GetContextHandle: JsContextRef;\nbegin\n  ChakraCoreCheck(JsGetContextOfObject(FInstance, Result));\nend;\n\n{ TNativeObject protected }\n\nclass function TNativeObject.FindConstructor: JsValueRef;\nvar\n  Info: PNativeClassInfo;\nbegin\n  Result := nil;\n\n  if Self.ClassParent <> TNativeObject then\n  begin\n    Info := TChakraCoreContext.CurrentContext.FindClassInfo(Self);\n    if Assigned(Info) then\n      Result := Info^.AConstructor;\n  end;\nend;\n\nclass function TNativeObject.FindParentConstructor: JsValueRef;\nvar\n  Info: PNativeClassInfo;\nbegin\n  Result := nil;\n\n  if Self.ClassParent <> TNativeObject then\n  begin\n    Info := TChakraCoreContext.CurrentContext.FindClassInfo(TNativeClass(Self.ClassParent));\n    if Assigned(Info) then\n      Result := Info^.AConstructor;\n  end;\nend;\n\nclass function TNativeObject.FindPrototype: JsValueRef;\nvar\n  Info: PNativeClassInfo;\nbegin\n  Result := nil;\n  Info := TChakraCoreContext.CurrentContext.FindClassInfo(Self);\n  if Assigned(Info) then\n    Result := Info^.APrototype;\nend;\n\nclass procedure TNativeObject.InitializeInstance(AInstance: JsValueRef; Args: PJsValueRef; ArgCount: Word);\nvar\n  ParentConstructor: JsValueRef;\n  ParentArgs: JsValueRefArray;\nbegin\n  ParentConstructor := FindParentConstructor;\n  if Assigned(ParentConstructor) and (Self.ClassParent <> TNativeObject) then\n  begin\n    // pass thisarg + args\n    SetLength(ParentArgs, ArgCount + 1);\n    ParentArgs[0] := AInstance;\n    if ArgCount > 0 then\n      Move(Args^, ParentArgs[1], ArgCount * SizeOf(JsValueRef));\n    JsCallFunction(ParentConstructor, @ParentArgs[0], ArgCount + 1);\n  end;\nend;\n\nclass function TNativeObject.InitializePrototype(AConstructor: JsValueRef): JsValueRef;\nbegin\n  if Self.ClassParent = TNativeObject then\n    Result := JsGetProperty(AConstructor, 'prototype')\n  else\n    Result := JsCreateObject(JsGetProperty(FindParentConstructor, 'prototype'));\nend;\n\nclass procedure TNativeObject.RegisterClassMethod(AConstructor: JsValueRef; const AName: UnicodeString; AMethod: Pointer; UseStrictRules: Boolean);\nbegin\n  JsSetCallback(AConstructor, AName, Native_ClassMethodCallback, AMethod, UseStrictRules);\nend;\n\nclass procedure TNativeObject.RegisterMethod(AInstance: JsValueRef; const AName: UnicodeString;\n  AMethod: Pointer; UseStrictRules: Boolean);\nbegin\n  JsSetCallback(AInstance, AName, Native_MethodCallback, AMethod, UseStrictRules);\nend;\n\nclass procedure TNativeObject.RegisterMethods(AInstance: JsValueRef);\nbegin\n  // do nothing\nend;\n\nclass procedure TNativeObject.RegisterNamedProperty(AInstance: JsValueRef; const AName: UnicodeString;\n  Configurable, Enumerable: Boolean; GetAccessor, SetAccessor: Pointer);\nvar\n  GetFunc, SetFunc: JsValueRef;\nbegin\n  GetFunc := nil;\n  SetFunc := nil;\n  if Assigned(GetAccessor) then\n    GetFunc := JsCreateFunction(@Native_PropGetCallback, GetAccessor, UnicodeString(''));\n  if Assigned(SetAccessor) then\n    SetFunc := JsCreateFunction(@Native_PropSetCallback, SetAccessor, UnicodeString(''));\n    \n  JsDefineProperty(AName, Configurable, Enumerable, GetFunc, SetFunc, AInstance);\nend;\n\nclass procedure TNativeObject.RegisterNamedProperty(AInstance: JsValueRef; const AName: UnicodeString;\n  Configurable, Enumerable, Writable: Boolean; Value: JsValueRef);\nvar\n  Descriptor: JsValueRef;\n  PropName: UTF8String;\n  PropId: JsPropertyIdRef;\n  B: ByteBool;\nbegin\n  Descriptor := JsCreateObject;\n  JsSetProperty(Descriptor, 'configurable', BooleanToJsBoolean(Configurable), True);\n  JsSetProperty(Descriptor, 'enumerable', BooleanToJsBoolean(Enumerable), True);\n  JsSetProperty(Descriptor, 'writable', BooleanToJsBoolean(Writable));\n  JsSetProperty(Descriptor, 'value', Value, True);\n  PropName := UTF8Encode(AName);\n  ChakraCoreCheck(JsCreatePropertyId(PAnsiChar(PropName), Length(PropName), PropId));\n  ChakraCoreCheck(ChakraCommon.JsDefineProperty(AInstance, PropId, Descriptor, B));\nend;\n\nclass procedure TNativeObject.RegisterProperties(AInstance: JsValueRef);\nbegin\n  // do nothing\nend;\n\n{ TNativeObject public }\n\nconstructor TNativeObject.Create(Args: PJsValueRef; ArgCount: Word; AFinalize: Boolean);\nconst\n  Finalizers: array[Boolean] of JsFinalizeCallback = (nil, Native_FinalizeCallback);\nvar\n  APrototype: JsValueRef;\nbegin\n  inherited Create;\n  FInstance := nil;\n  APrototype := FindPrototype;\n  if Assigned(APrototype) then\n  begin\n    ChakraCoreCheck(JsCreateExternalObjectWithPrototype(Self, Finalizers[AFinalize], APrototype, FInstance));\n    JsSetExternalData(FInstance, Self);\n  end\n  else\n  begin\n    ChakraCoreCheck(JsCreateExternalObject(Self, Finalizers[AFinalize], FInstance));\n    JsSetExternalData(FInstance, Self);\n    RegisterMethods(FInstance);\n    RegisterProperties(FInstance);\n  end;\n  InitializeInstance(FInstance, Args, ArgCount);\n  Context.DoNativeObjectCreated(Self);\nend;\n\nconstructor TNativeObject.Create(const Args: array of JsValueRef; AFinalize: Boolean);\nvar\n  PArg: PJsValueRef;\n  Len: Integer;\nbegin\n  PArg := nil;\n  Len := Length(Args);\n  if Len > 0 then\n    PArg := @Args[0];\n  Create(PArg, Len, AFinalize);\nend;\n\ndestructor TNativeObject.Destroy;\nbegin\n  // TODO detect context already destroyed\n  if Assigned(FInstance) then\n    ChakraCommon.JsSetExternalData(FInstance, nil);\n  inherited;\nend;\n\nfunction TNativeObject.AddRef: Integer;\nbegin\n  Result := JsAddRef(FInstance);\nend;\n\nclass procedure TNativeObject.Project(const AName: UnicodeString; Scope: JsValueRef; UseStrictRules: Boolean);\nvar\n  ConstructorName: UnicodeString;\nbegin\n  if Self = TNativeObject then // only project descendants\n    Exit;\n\n  ConstructorName := AName;\n  if ConstructorName = '' then\n  begin\n    ConstructorName := UnicodeString(ClassName);\n    if (ConstructorName[1] = 'T') and (Length(ConstructorName) > 1) then\n      Delete(ConstructorName, 1, 1);\n  end;\n\n  if not Assigned(Scope) then\n    Scope := JsGlobal;\n  JsDefineProperty(ConstructorName, True, True, JsCreateFunction(Native_GetConstructorCallback, Self, ConstructorName),\n    nil, Scope);\nend;\n\nfunction TNativeObject.Release: Integer;\nbegin\n  Result := JsRelease(FInstance);\nend;\n\nend.\n"
  },
  {
    "path": "src/ChakraCoreUtils.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nunit ChakraCoreUtils;\n\n{$include common.inc}\n\ninterface\n\nuses\n  Classes, SysUtils,\n{$ifdef HAS_WIDESTRUTILS}\n  WideStrUtils,\n{$endif}\n  Compat, ChakraCommon, ChakraCore;\n\ntype\n  EChakraCore = class(Exception)\n    ErrorCode: JsErrorCode;\n    Error: JsValueRef;\n  public\n    constructor Create(AErrorCode: JsErrorCode; AError: JsValueRef = nil);\n  end;\n  EChakraCoreEngine = class(EChakraCore);\n  EChakraCoreScript = class(EChakraCore)\n    Line: Integer;\n    Column: Integer;\n    Source: UnicodeString;\n    ScriptURL: UnicodeString;\n  public\n    constructor Create(AErrorCode: JsErrorCode);\n  end;\n  EChakraCoreFatal = class(EChakraCore);\n  EChakraCoreDiag = class(EChakraCore);\n\n  TErrorType = (etGenericError, etRangeError, etReferenceError, etSyntaxError, etTypeError, etUriError);\n\n  TJsEnumArrayFunc = function(Value: JsValueRef; Index: Integer; ElementValue: JsValueRef; Data: Pointer): Boolean;\n  TJsEnumPropertyFunc = function(Value: JsValueRef; const PropName: UnicodeString; PropValue: JsValueRef;\n    Data: Pointer): Boolean;\n\n  PJsValueRefArray = ^TJsValueRefArray;\n  TJsValueRefArray = array[0..255] of JsValueRef;\n  JsValueRefArray = array of JsValueRef;\n\nprocedure ChakraCoreCheck(ErrorCode: JsErrorCode);\nprocedure RaiseChakraCoreError(ErrorCode: JsErrorCode);\nprocedure RaiseError(Error: JsValueRef);\n\nfunction BooleanToJsBoolean(Value: Boolean): JsValueRef;\nfunction DoubleToJsNumber(Value: Double): JsValueRef;\nfunction IntToJsNumber(Value: Integer): JsValueRef;\nfunction JsFalseValue: JsValueRef;\nfunction JsNullValue: JsValueRef;\nfunction JsUndefinedValue: JsValueRef;\nfunction JsTrueValue: JsValueRef;\nfunction StringToJsString(const S: UTF8String): JsValueRef; overload;\nfunction StringToJsString(const S: UnicodeString): JsValueRef; overload;\n\nfunction JsEscapeString(const S: UTF8String): UTF8String; overload;\nfunction JsEscapeString(const S: UnicodeString): UnicodeString; overload;\n\nfunction JsCreateArray(Length: Integer): JsValueRef;\nfunction JsArrayLength(Value: JsValueRef): Integer;\nfunction JsArrayGetElement(Value: JsValueRef; Index: Integer): JsValueRef;\nprocedure JsArraySetElement(Value: JsValueRef; Index: Integer; ElementValue: JsValueRef);\nfunction StringsToJsArray(const Strings: array of UnicodeString): JsValueRef; overload;\nfunction StringsToJsArray(const Strings: array of UTF8String): JsValueRef; overload;\n\nfunction JsBooleanToBoolean(Value: JsValueRef): Boolean;\nfunction JsNumberToDouble(Value: JsValueRef): Double;\nfunction JsNumberToInt(Value: JsValueRef): Integer;\nfunction JsStringToUnicodeString(Value: JsValueRef): UnicodeString;\nfunction JsStringToUTF8String(Value: JsValueRef): UTF8String;\nprocedure JsEnumArray(Value: JsValueRef; EnumFunc: TJsEnumArrayFunc; Data: Pointer = nil);\nprocedure JsEnumProperties(Value: JsValueRef; EnumFunc: TJsEnumPropertyFunc; Data: Pointer = nil);\n\nfunction JsInspect(Value: JsValueRef): UnicodeString;\nfunction JsInspectArray(Value: JsValueRef): UnicodeString;\nfunction JsInspectObject(Value: JsValueRef): UnicodeString;\n\nfunction JsContextOf(Instance: JsValueRef): JsContextRef;\nfunction JsGlobal: JsValueRef;\nfunction JsGetPrototype(Instance: JsValueRef): JsValueRef;\nfunction JsInstanceOf(Instance: JsValueRef; const ConstructorName: UnicodeString; ThisArg: JsValueRef = nil): Boolean;\n  overload;\nfunction JsInstanceOf(Instance, AConstructor: JsValueRef): Boolean; overload;\nfunction JsNew(const ConstructorName: UTF8String; const Args: array of JsValueRef;\n  ThisArg: JsValueRef = nil): JsValueRef; overload;\nfunction JsNew(const ConstructorName: UnicodeString; const Args: array of JsValueRef;\n  ThisArg: JsValueRef = nil): JsValueRef; overload;\nfunction JsNew(AConstructor, ACallee: JsValueRef; const Args: array of JsValueRef): JsValueRef; overload;\n\nfunction JsAddRef(Value: JsValueRef): Integer;\nfunction JsRelease(Value: JsValueRef): Integer;\n\nfunction JsValueAsJsBoolean(Value: JsValueRef): JsValueRef;\nfunction JsValueAsJsNumber(Value: JsValueRef): JsValueRef;\nfunction JsValueAsJsObject(Value: JsValueRef): JsValueRef;\nfunction JsValueAsJsString(Value: JsValueRef): JsValueRef;\n\nfunction JsEqual(Value1, Value2: JsValueRef; AStrict: Boolean = False): Boolean;\nfunction JsGetErrorMessage(ErrorCode: JsErrorCode): PResStringRec;\n\nfunction JsCreateObject(APrototype: JsValueRef = nil): JsValueRef;\nfunction JsCreateSymbol(const Description: UnicodeString = ''): JsValueRef;\nfunction JsCreateNativeTypedArray(AType: JsTypedArrayType; ALength: Integer): JsValueRef;\n\nfunction JsGetExternalData(Value: JsValueRef): Pointer;\nprocedure JsSetExternalData(Value: JsValueRef; Data: Pointer);\nfunction JsGetValueType(Value: JsValueRef): JsValueType;\nfunction JsGetTypedArrayType(Value: JsValueRef): JsTypedArrayType;\n\nfunction JsCallFunction(Func: JsValueRef; Args: PJsValueRef; ArgCount: Word): JsValueRef; overload;\nfunction JsCallFunction(Func: JsValueRef; const Args: array of JsValueRef; ThisArg: JsValueRef = nil): JsValueRef;\n  overload;\nfunction JsCallFunction(const FunctionName: UTF8String; const Args: array of JsValueRef;\n  ThisArg: JsValueRef = nil): JsValueRef; overload;\nfunction JsCallFunction(const FunctionName: UnicodeString; const Args: array of JsValueRef;\n  ThisArg: JsValueRef = nil): JsValueRef; overload;\n\nfunction JsGetProperty(Value, Prop: JsValueRef): JsValueRef; overload;\nfunction JsGetProperty(Value: JsValueRef; PropId: JsPropertyIdRef): JsValueRef; overload;\nfunction JsGetProperty(Value: JsValueRef; const PropName: UTF8String): JsValueRef; overload;\nfunction JsGetProperty(Value: JsValueRef; const PropName: UnicodeString): JsValueRef; overload;\nfunction JsTryGetProperty(Value, Prop: JsValueRef; out PropValue: JsValueRef): Boolean; overload;\nfunction JsTryGetProperty(Value: JsValueRef; const PropName: UTF8String; out PropValue: JsValueRef): Boolean; overload;\nfunction JsTryGetProperty(Value: JsValueRef; const PropName: UnicodeString; out PropValue: JsValueRef): Boolean;\n  overload;\nfunction JsHasException: Boolean;\nfunction JsHasExternalData(Value: JsValueRef): Boolean;\nfunction JsHasProperty(Value, Prop: JsValueRef): Boolean; overload;\nfunction JsHasProperty(Value: JsValueRef; const PropId: JsPropertyIdRef): Boolean; overload;\nfunction JsHasProperty(Value: JsValueRef; const PropName: UTF8String): Boolean; overload;\nfunction JsHasProperty(Value: JsValueRef; const PropName: UnicodeString): Boolean; overload;\nfunction JsCreatePropertyDescriptor(Configurable, Enumerable: Boolean; GetAccessor, SetAccessor: JsValueRef;\n  UseStrictRules: Boolean = True): JsValueRef; overload;\nfunction JsDefineProperty(PropId: JsPropertyIdRef; Configurable, Enumerable: Boolean;\n  GetAccessor, SetAccessor: JsValueRef; Scope: JsValueRef = nil; UseStrictRules: Boolean = True): Boolean; overload;\nfunction JsDefineProperty(const PropName: UTF8String; Configurable, Enumerable: Boolean;\n  GetAccessor, SetAccessor: JsValueRef; Scope: JsValueRef = nil; UseStrictRules: Boolean = True): Boolean; overload;\nfunction JsDefineProperty(const PropName: UnicodeString; Configurable, Enumerable: Boolean;\n  GetAccessor, SetAccessor: JsValueRef; Scope: JsValueRef = nil; UseStrictRules: Boolean = True): Boolean; overload;\nfunction JsDeleteProperty(Value, Prop: JsValueRef; UseStrictRules: Boolean = True): Boolean; overload;\nfunction JsDeleteProperty(Value: JsValueRef; PropId: JsPropertyIdRef; UseStrictRules: Boolean = True): Boolean; overload;\nfunction JsDeleteProperty(Value: JsValueRef; const PropName: UTF8String; UseStrictRules: Boolean = True): Boolean; overload;\nfunction JsDeleteProperty(Value: JsValueRef; const PropName: UnicodeString; UseStrictRules: Boolean = True): Boolean; overload;\n\nfunction JsParseScript(const Script, Name: UTF8String; SourceContext: NativeUInt = 0;\n  IsLibraryCode: Boolean = False): JsValueRef; overload;\nfunction JsParseScript(const Script, Name: UnicodeString; SourceContext: NativeUInt = 0;\n  IsLibraryCode: Boolean = False): JsValueRef; overload;\nfunction JsRunScript(const Script, Name: UTF8String; SourceContext: NativeUInt = 0;\n  IsLibraryCode: Boolean = False): JsValueRef; overload;\nfunction JsRunScript(const Script, Name: UnicodeString; SourceContext: NativeUInt = 0;\n  IsLibraryCode: Boolean = False): JsValueRef; overload;\nfunction JsCreateFunction(Callback: JsNativeFunction; CallbackState: Pointer; const Name: UTF8String = ''): JsValueRef;\n  overload;\nfunction JsCreateFunction(Callback: JsNativeFunction; CallbackState: Pointer;\n  const Name: UnicodeString = ''): JsValueRef; overload;\nprocedure JsCreatePromise(out Promise, ResolveFunc, RejectFunc: JsValueRef);\nfunction JsSetCallback(Instance: JsValueRef; const CallbackName: UTF8String; Callback: JsNativeFunction;\n  CallbackState: Pointer; UseStrictRules: Boolean = True): JsValueRef; overload;\nfunction JsSetCallback(Instance: JsValueRef; const CallbackName: UnicodeString; Callback: JsNativeFunction;\n  CallbackState: Pointer; UseStrictRules: Boolean = True): JsValueRef; overload;\nprocedure JsSetProperty(Instance, Prop, Value: JsValueRef; UseStrictRules: Boolean = True); overload;\nprocedure JsSetProperty(Instance: JsValueRef; PropId: JsPropertyIdRef; Value: JsValueRef;\n  UseStrictRules: Boolean = True); overload;\nprocedure JsSetProperty(Instance: JsValueRef; const PropName: UTF8String; Value: JsValueRef;\n  UseStrictRules: Boolean = True); overload;\nprocedure JsSetProperty(Instance: JsValueRef; const PropName: UnicodeString; Value: JsValueRef;\n  UseStrictRules: Boolean = True); overload;\nfunction JsCreateError(const AMessage: UTF8String; ErrorType: TErrorType = etGenericError): JsValueRef; overload;\nfunction JsCreateError(const AMessage: UnicodeString; ErrorType: TErrorType = etGenericError): JsValueRef; overload;\nprocedure JsThrowError(const AMessage: UTF8String; ErrorType: TErrorType = etGenericError); overload;\nprocedure JsThrowError(const AMessage: UnicodeString; ErrorType: TErrorType = etGenericError); overload;\nprocedure JsThrowError(Error: JsValueRef); overload;\n\nfunction JsGetCurrentContext: JsContextRef;\nfunction JsGetCurrentRuntime: JsRuntimeHandle;\nfunction JsIsDebugging: Boolean;\n\ntype\n  TJsInspectExceptionHandler = function (Value: JsValueRef; E: Exception): UnicodeString;\n\nvar\n  JsInspectExceptionHandler: TJsInspectExceptionHandler = nil;\n\nimplementation\n\nuses\n  ChakraDebug, ChakraCoreClasses;\n\nresourcestring\n  // Category of errors that relates to incorrect usage of the API itself\n  SJsErrorInvalidArgument = 'An argument to a hosting API was invalid';\n  SJsErrorNullArgument = 'An argument to a hosting API was null in a context where null is not allowed';\n  SJsErrorNoCurrentContext = 'The hosting API requires that a context be current, but there is no current context';\n  SJsErrorInExceptionState = 'The engine is in an exception state and no APIs can be called until the exception is cleared';\n  SJsErrorNotImplemented = 'A hosting API is not yet implemented';\n  SJsErrorWrongThread = 'A hosting API was called on the wrong thread';\n  SJsErrorRuntimeInUse = 'A runtime that is still in use cannot be disposed';\n  SJsErrorBadSerializedScript = 'A bad serialized script was used, or the serialized script was serialized by a different version of the Chakra engine';\n  SJsErrorInDisabledState = 'The runtime is in a disabled state';\n  SJsErrorCannotDisableExecution = 'Runtime does not support reliable script interruption';\n  SJsErrorHeapEnumInProgress = 'A heap enumeration is currently underway in the script context';\n  SJsErrorArgumentNotObject = 'A hosting API that operates on object values was called with a non-object value';\n  SJsErrorInProfileCallback = 'A script context is in the middle of a profile callback';\n  SJsErrorInThreadServiceCallback = 'A thread service callback is currently underway';\n  SJsErrorCannotSerializeDebugScript = 'Scripts cannot be serialized in debug contexts';\n  SJsErrorAlreadyDebuggingContext = 'The context cannot be put into a debug state because it is already in a debug state';\n  SJsErrorAlreadyProfilingContext = 'The context cannot start profiling because it is already profiling';\n  SJsErrorIdleNotEnabled = 'Idle notification given when the host did not enable idle processing';\n  SJsCannotSetProjectionEnqueueCallback = 'The context did not accept the enqueue callback';\n  SJsErrorCannotStartProjection = 'Failed to start projection';\n  SJsErrorInObjectBeforeCollectCallback = 'The operation is not supported in an object before collect callback';\n  SJsErrorObjectNotInspectable = 'Object cannot be unwrapped to IInspectable pointer';\n  SJsErrorPropertyNotSymbol = 'A hosting API that operates on symbol property ids but was called with a non-symbol property id';\n  SJsErrorPropertyNotString = 'A hosting API that operates on string property ids but was called with a non-string property id';\n  SJsErrorInvalidContext = 'Module evaulation is called in wrong context';\n  SJsInvalidModuleHostInfoKind = 'Invalid module host info kind';\n  SJsErrorModuleParsed = 'Module was parsed already when JsParseModuleSource is called';\n  SJsErrorModuleEvaluated = 'Module was evaluated already when JsModuleEvaluation is called';\n  SJsNoWeakRefRequired = 'Argument passed to JsCreateWeakReference is a primitive that is not managed by the GC. No weak reference is required, the value will never be collected.';\n  SJsErrorPromisePending = 'The Promise object is still in the pending state.';\n  SJsErrorModuleNotEvaluated = 'Module was not yet evaluated when JsGetModuleNamespace was called.';\n\n  // Category of errors that relates to errors occurring within the engine itself\n  SJsErrorOutOfMemory = 'The Chakra engine has run out of memory';\n  SJsErrorBadFPUState = 'The Chakra engine failed to set the Floating Point Unit state';\n\n  // Category of errors that relates to errors in a script\n  SJsErrorScriptException = 'A JavaScript exception occurred while running a script';\n  SJsErrorScriptCompile = 'JavaScript failed to compile';\n  SJsErrorScriptTerminated = 'A script was terminated due to a request to suspend a runtime';\n  SJsErrorScriptEvalDisabled = 'A script was terminated because it tried to use eval or function and eval was disabled';\n\n  // Category of errors that are fatal and signify failure of the engine\n  SJsErrorFatal = 'A fatal error in the engine has occurred';\n  SJsErrorWrongRuntime = 'A hosting API was called with object created on different javascript runtime';\n\n  // Category of errors that are related to failures during diagnostic operations\n  SJsErrorDiagAlreadyInDebugMode = 'The object for which the debugging API was called was not found';\n  SJsErrorDiagNotInDebugMode = 'The debugging API can only be called when VM is in debug mode';\n  SJsErrorDiagNotAtBreak = 'The debugging API can only be called when VM is at a break';\n  SJsErrorDiagInvalidHandle = 'Debugging API was called with an invalid handle';\n  SJsErrorDiagObjectNotFound = 'The object for which the debugging API was called was not found';\n  SJsErrorDiagUnableToPerformAction = 'VM was unable to perfom the request action';\n\ntype\n  JsErrorConstructor = function(_message: JsValueRef; out error: JsValueRef): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n{ EChakra public }\n\nconstructor EChakraCore.Create(AErrorCode: JsErrorCode; AError: JsValueRef);\nbegin\n  inherited CreateRes(JsGetErrorMessage(AErrorCode));\n  ErrorCode := AErrorCode;\n  Error := AError;\n  if not Assigned(Error) then\n    JsGetAndClearException(Error);\nend;\n\n{ EChakraCoreScript public }\n\nconstructor EChakraCoreScript.Create(AErrorCode: JsErrorCode);\nvar\n  PropValue, MetaData: JsValueRef;\n  SException: UnicodeString;\nbegin\n  SException := '';\n  if JsGetAndClearExceptionWithMetadata(MetaData) = JsNoError then\n  begin\n    Line := JsNumberToInt(JsGetProperty(MetaData, 'line'));\n    Column := JsNumberToInt(JsGetProperty(MetaData, 'column'));\n    Source := JsStringToUnicodeString(JsGetProperty(MetaData, 'source'));\n    ScriptURL := JsStringToUnicodeString(JsGetProperty(MetaData, 'url'));\n    Error := JsGetProperty(MetaData, 'exception');\n  end\n  else if JsGetAndClearException(Error) = JsNoError then\n  begin\n    if JsTryGetProperty(Error, 'line', PropValue) and (JsGetValueType(PropValue) = JsNumber) then\n      Line := JsNumberToInt(PropValue);\n    if JsTryGetProperty(Error, 'column', PropValue) and (JsGetValueType(PropValue) = JsNumber) then\n      Column := JsNumberToInt(PropValue);\n    if JsTryGetProperty(Error, 'source', PropValue) and (JsGetValueType(PropValue) = JsString) then\n      Source := JsStringToUnicodeString(PropValue);\n    if JsTryGetProperty(Error, 'url', PropValue) and (JsGetValueType(PropValue) = JsString) then\n      ScriptURL := JsStringToUnicodeString(PropValue);\n  end;\n  inherited Create(AErrorCode, Error);\n  if Assigned(Error) then\n    SException := JsStringToUnicodeString(Error);\n  if SException <> '' then\n{$ifdef UNICODE}\n    Message := Message + sLineBreak + SException;\n{$else}\n    Message := Message + sLineBreak + UTF8Encode(SException);\n{$endif}\nend;\n\nfunction BooleanToJsBoolean(Value: Boolean): JsValueRef;\nbegin\n  ChakraCoreCheck(JsBoolToBoolean(Value, Result));\nend;\n\nprocedure ChakraCoreCheck(ErrorCode: JsErrorCode);\nbegin\n  if ErrorCode <> JsNoError then\n    RaiseChakraCoreError(ErrorCode);\nend;\n\nprocedure RaiseChakraCoreError(ErrorCode: JsErrorCode);\nbegin\n  case JsErrorCode(Ord(ErrorCode) and $F0000) of\n    // JsErrorCategoryUsage: ;\n    JsErrorCategoryEngine:\n      raise EChakraCoreEngine.Create(ErrorCode);\n    JsErrorCategoryScript:\n      raise EChakraCoreScript.Create(ErrorCode);\n    JsErrorCategoryFatal:\n      raise EChakraCoreFatal.Create(ErrorCode);\n    JsErrorCategoryDiagError:\n      raise EChakraCoreDiag.Create(ErrorCode);\n    else\n      raise EChakraCore.Create(ErrorCode);\n  end;\nend;\n\nprocedure RaiseError(Error: JsValueRef);\nbegin\n  if not Assigned(Error) then\n    Exit;\n\n{$ifdef UNICODE}\n  raise Exception.Create(JsInspect(Error));\n{$else}\n  raise Exception.Create(UTF8Encode(JsInspect(Error)));\n{$endif}\nend;\n\nfunction DoubleToJsNumber(Value: Double): JsValueRef;\nbegin\n  ChakraCoreCheck(JsDoubleToNumber(Value, Result));\nend;\n\nfunction IntToJsNumber(Value: Integer): JsValueRef;\nbegin\n  ChakraCoreCheck(JsIntToNumber(Value, Result));\nend;\n\nfunction JsFalseValue: JsValueRef;\nbegin\n  ChakraCoreCheck(JsGetFalseValue(Result));\nend;\n\nfunction JsNullValue: JsValueRef;\nbegin\n  ChakraCoreCheck(JsGetNullValue(Result));\nend;\n\nfunction JsUndefinedValue: JsValueRef;\nbegin\n  ChakraCoreCheck(JsGetUndefinedValue(Result));\nend;\n\nfunction JsTrueValue: JsValueRef;\nbegin\n  ChakraCoreCheck(JsGetTrueValue(Result));\nend;\n\nfunction StringToJsString(const S: UTF8String): JsValueRef;\nbegin\n  ChakraCoreCheck(JsCreateString(PAnsiChar(S), Length(S), Result));\nend;\n\nfunction StringToJsString(const S: UnicodeString): JsValueRef;\nconst\n  Null: UnicodeChar = #0;\n  PNull: PUnicodeChar = @Null;\nvar\n  P: PUnicodeChar;\nbegin\n  P := PUnicodeChar(S);\n  if not Assigned(P) then\n    P := PNull;\n  ChakraCoreCheck(JsCreateStringUtf16(P, Length(S), Result));\nend;\n\nfunction JsEscapeString(const S: UTF8String): UTF8String;\nbegin\n  Result := UTF8Encode(JsEscapeString(UTF8ToString(S)));\nend;\n\n// TODO see https://mathiasbynens.be/notes/javascript-escapes\nfunction JsEscapeString(const S: UnicodeString): UnicodeString;\nbegin\n  Result := S;\n  Result := WideStringReplace(Result, '\\', '\\\\', [rfReplaceAll]);\n  Result := WideStringReplace(Result, #8, '\\b', [rfReplaceAll]);\n  Result := WideStringReplace(Result, #9, '\\t', [rfReplaceAll]);\n  Result := WideStringReplace(Result, #10, '\\n', [rfReplaceAll]);\n  Result := WideStringReplace(Result, #11, '\\v', [rfReplaceAll]);\n  Result := WideStringReplace(Result, #12, '\\f', [rfReplaceAll]);\n  Result := WideStringReplace(Result, #13, '\\r', [rfReplaceAll]);\n  Result := WideStringReplace(Result, '\"', '\\\"', [rfReplaceAll]);\n  Result := WideStringReplace(Result, '''', '\\''', [rfReplaceAll]);\nend;\n\nfunction JsCreateArray(Length: Integer): JsValueRef;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsCreateArray(Length, Result));\nend;\n\nfunction JsArrayLength(Value: JsValueRef): Integer;\nbegin\n  Result := JsNumberToInt(JsGetProperty(Value, 'length'));\nend;\n\nfunction JsArrayGetElement(Value: JsValueRef; Index: Integer): JsValueRef;\nbegin\n  ChakraCoreCheck(JsGetIndexedProperty(Value, IntToJsNumber(Index), Result));\nend;\n\nprocedure JsArraySetElement(Value: JsValueRef; Index: Integer; ElementValue: JsValueRef);\nbegin\n  ChakraCoreCheck(JsSetIndexedProperty(Value, IntToJsNumber(Index), ElementValue));\nend;\n\nfunction StringsToJsArray(const Strings: array of UnicodeString): JsValueRef;\nvar\n  L, I: Integer;\nbegin\n  L := Length(Strings);\n  Result := JsCreateArray(L);\n  for I := 0 to L - 1 do\n    JsArraySetElement(Result, I, StringToJsString(Strings[I]));\nend;\n\nfunction StringsToJsArray(const Strings: array of UTF8String): JsValueRef;\nvar\n  L, I: Integer;\nbegin\n  L := Length(Strings);\n  Result := JsCreateArray(L);\n  for I := 0 to L - 1 do\n    JsArraySetElement(Result, I, StringToJsString(Strings[I]));\nend;\n\nfunction JsBooleanToBoolean(Value: JsValueRef): Boolean;\nvar\n  B: ByteBool;\nbegin\n  ChakraCoreCheck(JsBooleanToBool(Value, B));\n  Result := B;\nend;\n\nfunction JsNumberToDouble(Value: JsValueRef): Double;\nbegin\n  Result := -1;\n  ChakraCoreCheck(ChakraCommon.JsNumberToDouble(Value, Result));\nend;\n\nfunction JsNumberToInt(Value: JsValueRef): Integer;\nbegin\n  Result := -1;\n  ChakraCoreCheck(ChakraCommon.JsNumberToInt(Value, Result));\nend;\n\nfunction JsStringToUnicodeString(Value: JsValueRef): UnicodeString;\nvar\n  StringValue: JsValueRef;\n  StringLength: size_t;\nbegin\n  Result := '';\n  StringValue := JsValueAsJsString(Value);\n  StringLength := 0;\n  ChakraCoreCheck(JsCopyStringUtf16(StringValue, 0, -1, nil, @StringLength));\n  if StringLength > 0 then\n  begin\n    SetLength(Result, StringLength);\n    ChakraCoreCheck(JsCopyStringUtf16(StringValue, 0, StringLength, PUnicodeChar(Result), nil));\n  end;\nend;\n\nfunction JsStringToUTF8String(Value: JsValueRef): UTF8String;\nvar\n  StringValue: JsValueRef;\n  StringLength: size_t;\nbegin\n  Result := '';\n  StringValue := JsValueAsJsString(Value);\n  StringLength := 0;\n  ChakraCoreCheck(JsCopyString(StringValue, nil, 0, @StringLength));\n  if StringLength > 0 then\n  begin\n    SetLength(Result, StringLength);\n    ChakraCoreCheck(JsCopyString(StringValue, PAnsiChar(Result), StringLength, nil));\n  end;\nend;\n\nprocedure JsEnumArray(Value: JsValueRef; EnumFunc: TJsEnumArrayFunc; Data: Pointer);\nvar\n  I: Integer;\n  ElementValue: JsValueRef;\nbegin\n  if JsGetValueType(Value) <> JsArray then\n    Exit;\n\n  for I := 0 to JsArrayLength(Value) - 1 do\n  begin\n    ElementValue := JsArrayGetElement(Value, I);\n    if EnumFunc(Value, I, ElementValue, Data) then\n      Break;\n  end;\nend;\n\ntype\n  PListPropData = ^TListPropData;\n  TListPropData = record\n    Instance: JsValueRef;\n    EnumFunc: TJsEnumPropertyFunc;\n    Data: Pointer;\n  end;\n\nfunction _EnumPropertyFunc(Value: JsValueRef; Index: Integer; ElementValue: JsValueRef; Data: Pointer): Boolean;\nvar\n  ListPropData: PListPropData absolute Data;\n  PropName: UnicodeString;\nbegin\n  Result := False;\n  PropName := JsStringToUnicodeString(ElementValue);\n  ListPropData^.EnumFunc(ListPropData^.Instance, PropName, JsGetProperty(ListPropData^.Instance, PropName),\n    ListPropData^.Data);\nend;\n\nprocedure JsEnumProperties(Value: JsValueRef; EnumFunc: TJsEnumPropertyFunc; Data: Pointer);\nvar\n  PropNames: JsValueRef;\n  ListPropData: TListPropData;\nbegin\n  ChakraCoreCheck(JsGetOwnPropertyNames(Value, PropNames));\n  if JsGetValuetype(PropNames) = JsArray then\n  begin\n    ListPropData.Instance := Value;\n    ListPropData.EnumFunc := EnumFunc;\n    ListPropData.Data := Data;\n    JsEnumArray(PropNames, _EnumPropertyFunc, @ListPropData);\n  end;\nend;\n\nfunction JsInspect(Value: JsValueRef): UnicodeString;\nbegin\n  Result := '';\n  try\n    case JsGetValueType(Value) of\n      JsObject:\n        Result := '{' + JsInspectObject(Value) + '}';\n      JsArray:\n        Result := '[' + JsInspectArray(Value) + ']';\n      JsArrayBuffer:\n        Result := '{' + JsInspectObject(Value) + '}';\n      JsTypedArray:\n        Result := '{' + JsInspectObject(Value) + '}';\n      JsDataView:\n        Result := '{' + JsInspectObject(Value) + '}';\n      else\n        Result := '\"' + JsEscapeString(JsStringToUnicodeString(JsValueAsJsString(Value))) + '\"';\n    end;\n  except\n    on E: Exception do\n    begin\n      if not Assigned(JsInspectExceptionHandler) then\n        raise;\n      Result := Result + '\"' + JsEscapeString(JsInspectExceptionHandler(Value, E)) + '\"';\n    end;\n  end;\nend;\n\nfunction _JsInspectArrayElement(Value: JsValueRef; Index: Integer; ElementValue: JsValueRef; Data: Pointer): Boolean;\nvar\n  S: PUnicodeString absolute Data;\nbegin\n  Result := False;\n  if Index > 0 then\n    S^ := S^ + ',';\n  S^ := S^ + JsInspect(ElementValue);\nend;\n\nfunction JsInspectArray(Value: JsValueRef): UnicodeString;\nbegin\n  Result := '';\n  JsEnumArray(Value, _JsInspectArrayElement, @Result);\nend;\n\nfunction _JsInspectObjectProperty(Instance: JsValueRef; const PropName: UnicodeString; PropValue: JsValueRef; Data: Pointer): Boolean;\nvar\n  S: PUnicodeString absolute data;\nbegin\n  Result := False;\n  if S^ <> '' then\n    S^ := S^ + ',';\n  S^ := S^ + '\"' + PropName + '\":' + JsInspect(PropValue);\nend;\n\nfunction JsInspectObject(Value: JsValueRef): UnicodeString;\nbegin\n  Result := '';\n  JsEnumProperties(Value, _JsInspectObjectProperty, @Result);\nend;\n\nfunction JsContextOf(Instance: JsValueRef): JsContextRef;\nbegin\n  ChakraCoreCheck(JsGetContextOfObject(Instance, Result));\nend;\n\nfunction JsGlobal: JsValueRef;\nbegin\n  ChakraCoreCheck(JsGetGlobalObject(Result));\nend;\n\nfunction JsGetPrototype(Instance: JsValueRef): JsValueRef;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsGetPrototype(Instance, Result));\nend;\n\nfunction JsInstanceOf(Instance: JsValueRef; const ConstructorName: UnicodeString; ThisArg: JsValueRef): Boolean;\nbegin\n  if not Assigned(ThisArg) then\n    ThisArg := JsGlobal;\n  Result := JsInstanceOf(Instance, JsGetProperty(ThisArg, ConstructorName));\nend;\n\nfunction JsInstanceOf(Instance, AConstructor: JsValueRef): Boolean;\nvar\n  B: ByteBool;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsInstanceOf(Instance, AConstructor, B));\n  Result := B;\nend;\n\nfunction JsNew(const ConstructorName: UTF8String; const Args: array of JsValueRef; ThisArg: JsValueRef): JsValueRef;\nvar\n  AConstructor: JsValueRef;\nbegin\n  if not Assigned(ThisArg) then\n    ThisArg := JsGlobal;\n  AConstructor := JsGetProperty(ThisArg, ConstructorName);\n  Result := JsNew(AConstructor, AConstructor, Args);\nend;\n\nfunction JsNew(const ConstructorName: UnicodeString; const Args: array of JsValueRef; ThisArg: JsValueRef): JsValueRef;\nvar\n  AConstructor: JsValueRef;\nbegin\n  if not Assigned(ThisArg) then\n    ThisArg := JsGlobal;\n  AConstructor := JsGetProperty(ThisArg, ConstructorName);\n  Result := JsNew(AConstructor, AConstructor, Args);\nend;\n\nfunction JsNew(AConstructor, ACallee: JsValueRef; const Args: array of JsValueRef): JsValueRef;\nvar\n  NewArgs: JsValueRefArray;\n  L: Integer;\nbegin\n  // pass callee + args\n  L := Length(Args);\n  SetLength(NewArgs, L + 1);\n  NewArgs[0] := ACallee;\n  Move(Args[0], NewArgs[1], L * SizeOf(JsValueRef));\n  ChakraCoreCheck(ChakraCommon.JsConstructObject(AConstructor, @NewArgs[0], L + 1, Result));\nend;\n\nfunction JsAddRef(Value: JsValueRef): Integer;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsAddRef(Value, @Result));\nend;\n\nfunction JsRelease(Value: JsValueRef): Integer;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsRelease(Value, @Result));\nend;\n\nfunction JsValueAsJsBoolean(Value: JsValueRef): JsValueRef;\nbegin\n  ChakraCoreCheck(JsConvertValueToBoolean(Value, Result));\nend;\n\nfunction JsValueAsJsNumber(Value: JsValueRef): JsValueRef;\nbegin\n  ChakraCoreCheck(JsConvertValueToNumber(Value, Result));\nend;\n\nfunction JsValueAsJsObject(Value: JsValueRef): JsValueRef;\nbegin\n  ChakraCoreCheck(JsConvertValueToObject(Value, Result));\nend;\n\nfunction JsValueAsJsString(Value: JsValueRef): JsValueRef;\nbegin\n  ChakraCoreCheck(JsConvertValueToString(Value, Result));\nend;\n\nfunction JsEqual(Value1, Value2: JsValueRef; AStrict: Boolean): Boolean;\nvar\n  B: ByteBool;\nbegin\n  if AStrict then\n    ChakraCoreCheck(JsStrictEquals(Value1, Value2, B))\n  else\n    ChakraCoreCheck(JsEquals(Value1, Value2, B));\n  Result := B;\nend;\n\nfunction JsGetErrorMessage(ErrorCode: JsErrorCode): PResStringRec;\nbegin\n  case ErrorCode of\n    // JsNoError\n    // JsErrorCategoryUsage\n    JsErrorInvalidArgument:\n      Result := @SJsErrorInvalidArgument;\n    JsErrorNullArgument:\n      Result := @SJsErrorNullArgument;\n    JsErrorNoCurrentContext:\n      Result := @SJsErrorNoCurrentContext;\n    JsErrorInExceptionState:\n      Result := @SJsErrorInExceptionState;\n    JsErrorNotImplemented:\n      Result := @SJsErrorNotImplemented;\n    JsErrorWrongThread:\n      Result := @SJsErrorWrongThread;\n    JsErrorRuntimeInUse:\n      Result := @SJsErrorRuntimeInUse;\n    JsErrorBadSerializedScript:\n      Result := @SJsErrorBadSerializedScript;\n    JsErrorInDisabledState:\n      Result := @SJsErrorInDisabledState;\n    JsErrorCannotDisableExecution:\n      Result := @SJsErrorCannotDisableExecution;\n    JsErrorHeapEnumInProgress:\n      Result := @SJsErrorHeapEnumInProgress;\n    JsErrorArgumentNotObject:\n      Result := @SJsErrorArgumentNotObject;\n    JsErrorInProfileCallback:\n      Result := @SJsErrorInProfileCallback;\n    JsErrorInThreadServiceCallback:\n      Result := @SJsErrorInThreadServiceCallback;\n    JsErrorCannotSerializeDebugScript:\n      Result := @SJsErrorCannotSerializeDebugScript;\n    JsErrorAlreadyDebuggingContext:\n      Result := @SJsErrorAlreadyDebuggingContext;\n    JsErrorAlreadyProfilingContext:\n      Result := @SJsErrorAlreadyProfilingContext;\n    JsErrorIdleNotEnabled:\n      Result := @SJsErrorIdleNotEnabled;\n    JsCannotSetProjectionEnqueueCallback:\n      Result := @SJsCannotSetProjectionEnqueueCallback;\n    JsErrorCannotStartProjection:\n      Result := @SJsErrorCannotStartProjection;\n    JsErrorInObjectBeforeCollectCallback:\n      Result := @SJsErrorInObjectBeforeCollectCallback;\n    JsErrorObjectNotInspectable:\n      Result := @SJsErrorObjectNotInspectable;\n    JsErrorPropertyNotSymbol:\n      Result := @SJsErrorPropertyNotSymbol;\n    JsErrorPropertyNotString:\n      Result := @SJsErrorPropertyNotString;\n    JsErrorInvalidContext:\n      Result := @SJsErrorInvalidContext;\n    JsInvalidModuleHostInfoKind:\n      Result := @SJsInvalidModuleHostInfoKind;\n    JsErrorModuleParsed:\n      Result := @SJsErrorModuleParsed;\n    JsErrorModuleEvaluated:\n      Result := @SJsErrorModuleEvaluated;\n    JsNoWeakRefRequired:\n      Result := @SJsNoWeakRefRequired;\n    JsErrorPromisePending:\n      Result := @SJsErrorPromisePending;\n    JsErrorModuleNotEvaluated:\n      Result := @SJsErrorModuleNotEvaluated;\n    // JsErrorCategoryEngine\n    JsErrorOutOfMemory:\n      Result := @SJsErrorOutOfMemory;\n    JsErrorBadFPUState:\n      Result := @SJsErrorBadFPUState;\n    // JsErrorCategoryScript\n    JsErrorScriptException:\n      Result := @SJsErrorScriptException;\n    JsErrorScriptCompile:\n      Result := @SJsErrorScriptCompile;\n    JsErrorScriptTerminated:\n      Result := @SJsErrorScriptTerminated;\n    JsErrorScriptEvalDisabled:\n      Result := @SJsErrorScriptEvalDisabled;\n    // JsErrorCategoryFatal\n    JsErrorFatal:\n      Result := @SJsErrorFatal;\n    JsErrorWrongRuntime:\n      Result := @SJsErrorWrongRuntime;\n    // JsErrorCategoryDiagError\n    JsErrorDiagAlreadyInDebugMode:\n      Result := @SJsErrorDiagAlreadyInDebugMode;\n    JsErrorDiagNotInDebugMode:\n      Result := @SJsErrorDiagNotInDebugMode;\n    JsErrorDiagNotAtBreak:\n      Result := @SJsErrorDiagNotAtBreak;\n    JsErrorDiagInvalidHandle:\n      Result := @SJsErrorDiagInvalidHandle;\n    JsErrorDiagObjectNotFound:\n      Result := @SJsErrorDiagObjectNotFound;\n    JsErrorDiagUnableToPerformAction:\n      Result := @SJsErrorDiagUnableToPerformAction;\n    else\n      Result := nil;\n  end;\nend;\n\nfunction JsCreateObject(APrototype: JsValueRef): JsValueRef;\nbegin\n  if Assigned(APrototype) then // Object.create(prototype)\n    Result := JsCallFunction('create', [APrototype], JsGetProperty(JsGlobal, 'Object'))\n  else\n    ChakraCoreCheck(ChakraCommon.JsCreateObject(Result));\nend;\n\nfunction JsCreateSymbol(const Description: UnicodeString): JsValueRef;\nvar\n  Desc: JsValueRef;\nbegin\n  Desc := JsNullValue;\n  if Description <> '' then\n    Desc := StringToJsString(Description);\n  ChakraCoreCheck(ChakraCommon.JsCreateSymbol(Desc, Result));\nend;\n\nfunction JsCreateNativeTypedArray(AType: JsTypedArrayType; ALength: Integer): JsValueRef;\nconst\n  ElementSizes: array[JsTypedArrayType] of Integer = (8, 8, 8, 16, 16, 32, 32, 32, 64);\nvar\n  Base: TChakraCoreNativeArrayBuffer;\nbegin\n  Base := TChakraCoreNativeArrayBuffer.Create(ALength * ElementSizes[AType]);\n  try\n    ChakraCoreCheck(JsCreateTypedArray(AType, Base.Handle, 0, ALength, Result));\n  except\n    Base.Free;\n    raise;\n  end;\nend;\n\nfunction JsGetExternalData(Value: JsValueRef): Pointer;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsGetExternalData(Value, Result));\nend;\n\nprocedure JsSetExternalData(Value: JsValueRef; Data: Pointer);\nbegin\n  ChakraCoreCheck(ChakraCommon.JsSetExternalData(Value, Data));\nend;\n\nfunction JsGetValueType(Value: JsValueRef): JsValueType;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsGetValueType(Value, Result));\nend;\n\nfunction JsGetTypedArrayType(Value: JsValueRef): JsTypedArrayType;\nbegin\n  ChakraCoreCheck(JsGetTypedArrayInfo(Value, @Result, nil, nil, nil));\nend;\n\nfunction JsCallFunction(Func: JsValueRef; Args: PJsValueRef; ArgCount: Word): JsValueRef;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsCallFunction(Func, Args, ArgCount, @Result));\nend;\n\nfunction JsCallFunction(Func: JsValueRef; const Args: array of JsValueRef; ThisArg: JsValueRef): JsValueRef;\nvar\n  L: Integer;\n  NewArgs: array of JsValueRef;\nbegin\n  if not Assigned(ThisArg) then\n    ThisArg := JsGlobal;\n\n  L := Length(Args);\n  SetLength(NewArgs, L + 1);\n  NewArgs[0] := ThisArg;\n  if L > 0 then\n    Move(Args[0], NewArgs[1], L * SizeOf(JsValueRef));\n  Result := JsCallFunction(Func, @NewArgs[0], L + 1);\nend;\n\nfunction JsCallFunction(const FunctionName: UTF8String; const Args: array of JsValueRef;\n  ThisArg: JsValueRef): JsValueRef;\nvar\n  Func: JsValueRef;\nbegin\n  if not Assigned(ThisArg) then\n    ThisArg := JsGlobal;\n  Func := JsGetProperty(ThisArg, FunctionName);\n  Result := JsCallFunction(Func, Args, ThisArg);\nend;\n\nfunction JsCallFunction(const FunctionName: UnicodeString; const Args: array of JsValueRef;\n  ThisArg: JsValueRef): JsValueRef;\nbegin\n  Result := JsCallFunction(UTF8Encode(FunctionName), Args, ThisArg);\nend;\n\nfunction JsGetProperty(Value, Prop: JsValueRef): JsValueRef;\nbegin\n  ChakraCoreCheck(JsObjectGetProperty(Value, Prop, Result));\nend;\n\nfunction JsGetProperty(Value: JsValueRef; PropId: JsPropertyIdRef): JsValueRef;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsGetProperty(Value, PropId, Result));\nend;\n\nfunction JsGetProperty(Value: JsValueRef; const PropName: UTF8String): JsValueRef;\nbegin\n  ChakraCoreCheck(JsObjectGetProperty(Value, StringToJsString(PropName), Result));\nend;\n\nfunction JsGetProperty(Value: JsValueRef; const PropName: UnicodeString): JsValueRef;\nbegin\n  ChakraCoreCheck(JsObjectGetProperty(Value, StringToJsString(PropName), Result));\nend;\n\nfunction JsTryGetProperty(Value, Prop: JsValueRef; out PropValue: JsValueRef): Boolean;\nbegin\n  Result := JsObjectGetProperty(Value, Prop, PropValue) = JsNoError;\nend;\n\nfunction JsTryGetProperty(Value: JsValueRef; const PropName: UTF8String; out PropValue: JsValueRef): Boolean;\nbegin\n  Result := JsObjectGetProperty(Value, StringToJsString(PropName), PropValue) = JsNoError;\nend;\n\nfunction JsTryGetProperty(Value: JsValueRef; const PropName: UnicodeString; out PropValue: JsValueRef): Boolean;\nbegin\n  Result := JsObjectGetProperty(Value, StringToJsString(PropName), PropValue) = JsNoError;\nend;\n\nfunction JsHasException: Boolean;\nvar\n  B: ByteBool;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsHasException(B));\n  Result := B;\nend;\n\nfunction JsHasExternalData(Value: JsValueRef): Boolean;\nvar\n  B: ByteBool;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsHasExternalData(Value, B));\n  Result := B;\nend;\n\nfunction JsHasProperty(Value, Prop: JsValueRef): Boolean;\nvar\n  B: ByteBool;\nbegin\n  ChakraCoreCheck(JsObjectHasProperty(Value, Prop, B));\n  Result := B;\nend;\n\nfunction JsHasProperty(Value: JsValueRef; const PropId: JsPropertyIdRef): Boolean;\nvar\n  B: ByteBool;\nbegin\n  ChakraCoreCheck(ChakraCore.JsHasOwnProperty(Value, PropId, B));\n  Result := B;\nend;\n\nfunction JsHasProperty(Value: JsValueRef; const PropName: UTF8String): Boolean;\nvar\n  B: ByteBool;\nbegin\n  ChakraCoreCheck(JsObjectHasProperty(Value, StringToJsString(PropName), B));\n  Result := B;\nend;\n\nfunction JsHasProperty(Value: JsValueRef; const PropName: UnicodeString): Boolean;\nvar\n  B: ByteBool;\nbegin\n  ChakraCoreCheck(JsObjectHasProperty(Value, StringToJsString(PropName), B));\n  Result := B;\nend;\n\nfunction JsCreatePropertyDescriptor(Configurable, Enumerable: Boolean; GetAccessor, SetAccessor: JsValueRef;\n  UseStrictRules: Boolean): JsValueRef;\nbegin\n  Result := JsCreateObject;\n  JsSetProperty(Result, 'configurable', BooleanToJsBoolean(Configurable), True);\n  JsSetProperty(Result, 'enumerable', BooleanToJsBoolean(Enumerable), True);\n  if Assigned(GetAccessor) and (JsGetValueType(GetAccessor) = JsFunction) then\n    JsSetProperty(Result, 'get', GetAccessor, UseStrictRules);\n  if Assigned(SetAccessor) and (JsGetValueType(SetAccessor) = JsFunction) then\n    JsSetProperty(Result, 'set', SetAccessor, UseStrictRules);\nend;\n\nfunction JsDefineProperty(PropId: JsPropertyIdRef; Configurable, Enumerable: Boolean;\n  GetAccessor, SetAccessor: JsValueRef; Scope: JsValueRef; UseStrictRules: Boolean): Boolean;\nbegin\n  if not Assigned(Scope) then\n    Scope := JsGlobal;\n  ChakraCoreCheck(ChakraCommon.JsDefineProperty(Scope, PropId, JsCreatePropertyDescriptor(Configurable, Enumerable,\n    GetAccessor, SetAccessor, UseStrictRules), ByteBool(Result)));\nend;\n\nfunction JsDefineProperty(const PropName: UTF8String; Configurable, Enumerable: Boolean;\n  GetAccessor, SetAccessor: JsValueRef; Scope: JsValueRef; UseStrictRules: Boolean): Boolean;\nvar\n  PropId: JsPropertyIdRef;\nbegin\n  ChakraCoreCheck(JsCreatePropertyId(PAnsiChar(PropName), Length(PropName), PropId));\n  Result := JsDefineProperty(PropId, Configurable, Enumerable, GetAccessor, SetAccessor, Scope, UseStrictRules);\nend;\n\nfunction JsDefineProperty(const PropName: UnicodeString; Configurable, Enumerable: Boolean;\n  GetAccessor, SetAccessor: JsValueRef; Scope: JsValueRef; UseStrictRules: Boolean): Boolean;\nbegin\n  Result := JsDefineProperty(UTF8Encode(PropName), Configurable, Enumerable, GetAccessor, SetAccessor, Scope,\n    UseStrictRules);\nend;\n\nfunction JsDeleteProperty(Value, Prop: JsValueRef; UseStrictRules: Boolean): Boolean;\nvar\n  B: JsValueRef;\nbegin\n  ChakraCoreCheck(JsObjectDeleteProperty(Value, Prop, UseStrictRules, B));\n  Result := JsBooleanToBoolean(JsValueAsJsBoolean(B));\nend;\n\nfunction JsDeleteProperty(Value: JsValueRef; PropId: JsPropertyIdRef; UseStrictRules: Boolean): Boolean;\nvar\n  B: JsValueRef;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsDeleteProperty(Value, PropId, UseStrictRules, B));\n  Result := JsBooleanToBoolean(JsValueAsJsBoolean(B));\nend;\n\nfunction JsDeleteProperty(Value: JsValueRef; const PropName: UTF8String; UseStrictRules: Boolean): Boolean;\nvar\n  B: JsValueRef;\nbegin\n  ChakraCoreCheck(JsObjectDeleteProperty(Value, StringToJsString(PropName), UseStrictRules, B));\n  Result := JsBooleanToBoolean(JsValueAsJsBoolean(B));\nend;\n\nfunction JsDeleteProperty(Value: JsValueRef; const PropName: UnicodeString; UseStrictRules: Boolean): Boolean;\nvar\n  B: JsValueRef;\nbegin\n  ChakraCoreCheck(JsObjectDeleteProperty(Value, StringToJsString(PropName), UseStrictRules, B));\n  Result := JsBooleanToBoolean(JsValueAsJsBoolean(B));\nend;\n\nfunction JsParseScript(const Script, Name: UTF8String; SourceContext: NativeUInt; IsLibraryCode: Boolean): JsValueRef;\nconst\n  ParseScriptAttributes: array[Boolean] of JsParseScriptAttributes = ([], [JsParseScriptAttributeLibraryCode]);\nvar\n  ScriptName, ScriptSource: JsValueRef;\nbegin\n  ScriptName := StringToJsString(Name);\n  ChakraCoreCheck(JsCreateExternalArrayBuffer(Pointer(Script), Length(Script), nil, nil, ScriptSource));\n  ChakraCoreCheck(JsParse(ScriptSource, SourceContext, ScriptName, ParseScriptAttributes[IsLibraryCode], Result));\nend;\n\nfunction JsParseScript(const Script, Name: UnicodeString; SourceContext: NativeUInt; IsLibraryCode: Boolean): JsValueRef;\nconst\n  ParseScriptAttributes: array[Boolean] of JsParseScriptAttributes = ([JsParseScriptAttributeArrayBufferIsUtf16Encoded],\n    [JsParseScriptAttributeLibraryCode, JsParseScriptAttributeArrayBufferIsUtf16Encoded]);\nvar\n  ScriptName, ScriptSource: JsValueRef;\nbegin\n  ScriptName := StringToJsString(Name);\n  ChakraCoreCheck(JsCreateExternalArrayBuffer(Pointer(PUnicodeChar(Script)), Length(Script) * SizeOf(UnicodeChar),\n    nil, nil, ScriptSource));\n  ChakraCoreCheck(JsParse(ScriptSource, SourceContext, ScriptName, ParseScriptAttributes[IsLibraryCode], Result));\nend;\n\nfunction JsRunScript(const Script, Name: UTF8String; SourceContext: NativeUInt; IsLibraryCode: Boolean): JsValueRef;\nconst\n  ParseScriptAttributes: array[Boolean] of JsParseScriptAttributes = ([], [JsParseScriptAttributeLibraryCode]);\nvar\n  ScriptName, ScriptSource: JsValueRef;\nbegin\n  ScriptName := StringToJsString(Name);\n  ChakraCoreCheck(JsCreateExternalArrayBuffer(Pointer(Script), Length(Script), nil, nil, ScriptSource));\n  ChakraCoreCheck(JsRun(ScriptSource, SourceContext, ScriptName, ParseScriptAttributes[IsLibraryCode], Result));\nend;\n\nfunction JsRunScript(const Script, Name: UnicodeString; SourceContext: NativeUInt; IsLibraryCode: Boolean): JsValueRef;\nconst\n  ParseScriptAttributes: array[Boolean] of JsParseScriptAttributes = ([JsParseScriptAttributeArrayBufferIsUtf16Encoded],\n    [JsParseScriptAttributeLibraryCode, JsParseScriptAttributeArrayBufferIsUtf16Encoded]);\nvar\n  ScriptName, ScriptSource: JsValueRef;\nbegin\n  ScriptName := StringToJsString(Name);\n  ChakraCoreCheck(JsCreateExternalArrayBuffer(Pointer(PUnicodeChar(Script)), Length(Script) * SizeOf(UnicodeChar),\n    nil, nil, ScriptSource));\n  ChakraCoreCheck(JsRun(ScriptSource, SourceContext, ScriptName, ParseScriptAttributes[IsLibraryCode], Result));\nend;\n\nfunction JsCreateFunction(Callback: JsNativeFunction; CallbackState: Pointer; const Name: UTF8String): JsValueRef;\nbegin\n  if Name = '' then\n    ChakraCoreCheck(ChakraCommon.JsCreateFunction(Callback, CallbackState, Result))\n  else\n    ChakraCoreCheck(ChakraCommon.JsCreateNamedFunction(StringToJsString(Name), Callback, CallbackState, Result));\nend;\n\nfunction JsCreateFunction(Callback: JsNativeFunction; CallbackState: Pointer; const Name: UnicodeString): JsValueRef;\nbegin\n  if Name = '' then\n    ChakraCoreCheck(ChakraCommon.JsCreateFunction(Callback, CallbackState, Result))\n  else\n    ChakraCoreCheck(ChakraCommon.JsCreateNamedFunction(StringToJsString(Name), Callback, CallbackState, Result));\nend;\n\nprocedure JsCreatePromise(out Promise, ResolveFunc, RejectFunc: JsValueRef);\nbegin\n  ChakraCoreCheck(ChakraCore.JsCreatePromise(Promise, ResolveFunc, RejectFunc));\nend;\n\nfunction JsSetCallback(Instance: JsValueRef; const CallbackName: UTF8String; Callback: JsNativeFunction;\n  CallbackState: Pointer; UseStrictRules: Boolean): JsValueRef;\nbegin\n  Result := JsCreateFunction(Callback, CallbackState, CallbackName);\n  JsSetProperty(Instance, CallbackName, Result, UseStrictRules);\nend;\n\nfunction JsSetCallback(Instance: JsValueRef; const CallbackName: UnicodeString; Callback: JsNativeFunction;\n  CallbackState: Pointer; UseStrictRules: Boolean): JsValueRef;\nbegin\n  Result := JsSetCallback(Instance, UTF8Encode(CallbackName), Callback, CallbackState, UseStrictRules);\nend;\n\nprocedure JsSetProperty(Instance, Prop, Value: JsValueRef; UseStrictRules: Boolean);\nbegin\n  ChakraCoreCheck(JsObjectSetProperty(Instance, Prop, Value, UseStrictRules));\nend;\n\nprocedure JsSetProperty(Instance: JsValueRef; PropId: JsPropertyIdRef; Value: JsValueRef; UseStrictRules: Boolean);\nbegin\n  ChakraCoreCheck(ChakraCommon.JsSetProperty(Instance, PropId, Value, UseStrictRules));\nend;\n\nprocedure JsSetProperty(Instance: JsValueRef; const PropName: UTF8String; Value: JsValueRef; UseStrictRules: Boolean);\nbegin\n  ChakraCoreCheck(JsObjectSetProperty(Instance, StringToJsString(PropName), Value, UseStrictRules));\nend;\n\nprocedure JsSetProperty(Instance: JsValueRef; const PropName: UnicodeString; Value: JsValueRef;\n  UseStrictRules: Boolean);\nbegin\n  ChakraCoreCheck(JsObjectSetProperty(Instance, StringToJsString(PropName), Value, UseStrictRules));\nend;\n\nconst\n  ChakraCoreErrorConstructors: array[TErrorType] of JsErrorConstructor = (\n    ChakraCommon.JsCreateError,\n    JsCreateRangeError,\n    JsCreateReferenceError,\n    JsCreateSyntaxError,\n    JsCreateTypeError,\n    JsCreateUriError\n  );\n\nfunction JsCreateError(const AMessage: UTF8String; ErrorType: TErrorType = etGenericError): JsValueRef;\nbegin\n  ChakraCoreCheck(ChakraCoreErrorConstructors[ErrorType](StringToJsString(AMessage), Result));\nend;\n\nfunction JsCreateError(const AMessage: UnicodeString; ErrorType: TErrorType = etGenericError): JsValueRef;\nbegin\n  ChakraCoreCheck(ChakraCoreErrorConstructors[ErrorType](StringToJsString(AMessage), Result));\nend;\n\nprocedure JsThrowError(const AMessage: UTF8String; ErrorType: TErrorType = etGenericError);\nbegin\n  JsThrowError(JsCreateError(AMessage, ErrorType));\nend;\n\nprocedure JsThrowError(const AMessage: UnicodeString; ErrorType: TErrorType);\nbegin\n  JsThrowError(JsCreateError(AMessage, ErrorType));\nend;\n\nprocedure JsThrowError(Error: JsValueRef);\nbegin\n  ChakraCoreCheck(JsSetException(Error));\nend;\n\nfunction JsGetCurrentContext: JsContextRef;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsGetCurrentContext(Result));\nend;\n\nfunction JsGetCurrentRuntime: JsRuntimeHandle;\nbegin\n  ChakraCoreCheck(ChakraCommon.JsGetRuntime(JsGetCurrentContext, Result));\nend;\n\nfunction JsIsDebugging: Boolean;\nvar\n  DiagAttributes: JsDiagBreakOnExceptionAttributes;\nbegin\n  Result := JsDiagGetBreakOnException(JsGetCurrentRuntime, DiagAttributes) <> JsErrorDiagNotInDebugMode;\nend;\n\nend.\n"
  },
  {
    "path": "src/ChakraCoreVersion.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\n//-------------------------------------------------------------------------------------------------------\n// Copyright (C) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n//-------------------------------------------------------------------------------------------------------\n\n// NOTE: When changing this file, you may need to update the GUID in ByteCodeCacheReleaseFileVersion.h\n// Please update the GUID when:\n// * CHAKRA_CORE_VERSION_RELEASE is changed to 1\n// * CHAKRA_CORE_VERSION_RELEASE is currently set to 1 and the bytecode changes\n// See notes below about ReleaseVersioningScheme.\n\nunit ChakraCoreVersion;\n\ninterface\n\n// --------------\n// VERSION NUMBER\n// --------------\n\n// ChakraCore version number definitions (used in ChakraCore binary metadata)\nconst\n  CHAKRA_CORE_MAJOR_VERSION = 1;\n  CHAKRA_CORE_MINOR_VERSION = 11;\n  CHAKRA_CORE_PATCH_VERSION = 24;\n  CHAKRA_CORE_VERSION_RELEASE_QFE = 0; // Redundant with PATCH_VERSION. Keep this value set to 0.\n\n// -------------\n// RELEASE FLAGS\n// -------------\n\n// NOTE: CHAKRA_CORE_VERSION_PRERELEASE can only be set to 1 when\n// CHAKRA_CORE_VERSION_RELEASE is set to 1, or there is no effect.\n// Here are the meanings of the various combinations:\n//\n//                  RELEASE**   PRERELEASE\n// DEVELOPMENT      0           0\n// <INVALID>        0           1           # INVALID but identical to DEVELOPMENT\n// RELEASE**        1           0           #\n// PRERELEASE       1           1\n//                  ** Release flags are not related to build type (e.g. x64_release)\n//\n// Unless otherwise noted, the code affected by these flags lies mostly in bin/CoreCommon.ver\n//\n// DEVELOPMENT:\n// * Uses EngineeringVersioningScheme (see lib/Runtime/ByteCode/ByteCodeSerializer.cpp)\n// * Sets file flag VS_FF_PRIVATEBUILD\n// * Adds \"Private\" to the file description\n//\n// RELEASE** and PRERELEASE (i.e. controlled by CHAKRA_CORE_VERSION_RELEASE flag):\n// * Uses ReleaseVersioningScheme (see lib/Runtime/ByteCode/ByteCodeSerializer.cpp)\n//\n// PRERELEASE (preparing for release but not yet ready to release):\n// * Sets file flag VS_FF_PRERELEASE\n// * Adds \"Pre-release\" to the file description\n//\n// RELEASE** (code is ready to release)\n// * Sets neither of the file flags noted above\n// * Does not add anything to the file description\n\n// ChakraCore RELEASE and PRERELEASE flags\n  CHAKRA_CORE_VERSION_RELEASE = 1;\n  CHAKRA_CORE_VERSION_PRERELEASE = 0;\n\n// Chakra RELEASE flag\n// Mostly redundant with CHAKRA_CORE_VERSION_RELEASE,\n// but semantically refers to Chakra rather than ChakraCore.\n  CHAKRA_VERSION_RELEASE = 0;\n\nimplementation\n\nend.\n"
  },
  {
    "path": "src/ChakraDebug.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\n//-------------------------------------------------------------------------------------------------------\n// Copyright (C) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n//-------------------------------------------------------------------------------------------------------\n/// \\mainpage Chakra Hosting Debugging API Reference\n///\n/// Chakra is Microsoft's JavaScript engine. It is an integral part of Internet Explorer but can\n/// also be hosted independently by other applications. This reference describes the APIs available\n/// to applications to debug JavaScript.\n\n/// \\file\n/// \\brief The Chakra hosting debugging API.\n///\n/// This file contains a flat C API layer. This is the API exported by ChakraCore.dll.\n\nunit ChakraDebug;\n\n{$include common.inc}\n\n{$minenumsize 4}\n\ninterface\n\nuses\n  ChakraCommon;\n\ntype\n  /// <summary>\n  ///     Debug events reported from ChakraCore engine.\n  /// </summary>\n  JsDiagDebugEvent = (\n    /// <summary>\n    ///     Indicates a new script being compiled, this includes script, eval, new function.\n    /// </summary>\n    JsDiagDebugEventSourceCompile = 0,\n    /// <summary>\n    ///     Indicates compile error for a script.\n    /// </summary>\n    JsDiagDebugEventCompileError = 1,\n    /// <summary>\n    ///     Indicates a break due to a breakpoint.\n    /// </summary>\n    JsDiagDebugEventBreakpoint = 2,\n    /// <summary>\n    ///     Indicates a break after completion of step action.\n    /// </summary>\n    JsDiagDebugEventStepComplete = 3,\n    /// <summary>\n    ///     Indicates a break due to debugger statement.\n    /// </summary>\n    JsDiagDebugEventDebuggerStatement = 4,\n    /// <summary>\n    ///     Indicates a break due to async break.\n    /// </summary>\n    JsDiagDebugEventAsyncBreak = 5,\n    /// <summary>\n    ///     Indicates a break due to a runtime script exception.\n    /// </summary>\n    JsDiagDebugEventRuntimeException = 6\n  );\n\n  /// <summary>\n  ///     Break on Exception attributes.\n  /// </summary>\n  JsDiagBreakOnExceptionAttributes = (\n    /// <summary>\n    ///     Don't break on any exception.\n    /// </summary>\n    JsDiagBreakOnExceptionAttributeNone = $0,\n    /// <summary>\n    ///     Break on uncaught exception.\n    /// </summary>\n    JsDiagBreakOnExceptionAttributeUncaught = $1,\n    /// <summary>\n    ///     Break on first chance exception.\n    /// </summary>\n    JsDiagBreakOnExceptionAttributeFirstChance = $2\n  );\n\n  /// <summary>\n  ///     Stepping types.\n  /// </summary>\n  JsDiagStepType = (\n    /// <summary>\n    ///     Perform a step operation to next statement.\n    /// </summary>\n    JsDiagStepTypeStepIn = 0,\n    /// <summary>\n    ///     Perform a step out from the current function.\n    /// </summary>\n    JsDiagStepTypeStepOut = 1,\n    /// <summary>\n    ///     Perform a single step over after a debug break if the next statement is a function call, else behaves as a stepin.\n    /// </summary>\n    JsDiagStepTypeStepOver = 2,\n    /// <summary>\n    ///     Perform a single step back to the previous statement (only applicable in TTD mode).\n    /// </summary>\n    JsDiagStepTypeStepBack = 3,\n    /// <summary>\n    ///     Perform a reverse continue operation (only applicable in TTD mode).\n    /// </summary>\n    JsDiagStepTypeReverseContinue = 4,\n    /// <summary>\n    ///     Perform a forward continue operation. Clears any existing step value.\n    /// </summary>\n    JsDiagStepTypeContinue = 5\n  );\n\n  /// <summary>\n  ///     User implemented callback routine for debug events.\n  /// </summary>\n  /// <remarks>\n  ///     Use <c>JsDiagStartDebugging</c> to register the callback.\n  /// </remarks>\n  /// <param name=\"debugEvent\">The type of JsDiagDebugEvent event.</param>\n  /// <param name=\"eventData\">Additional data related to the debug event.</param>\n  /// <param name=\"callbackState\">The state passed to <c>JsDiagStartDebugging</c>.</param>\n  JsDiagDebugEventCallback = function(debugEvent: JsDiagDebugEvent; eventData: JsValueRef; callbackState: Pointer): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Starts debugging in the given runtime.\n  /// </summary>\n  /// <param name=\"runtimeHandle\">Runtime to put into debug mode.</param>\n  /// <param name=\"debugEventCallback\">Registers a callback to be called on every JsDiagDebugEvent.</param>\n  /// <param name=\"callbackState\">User provided state that will be passed back to the callback.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The runtime should be active on the current thread and should not be in debug state.\n  /// </remarks>\n  function JsDiagStartDebugging(runtimeHandle: JsRuntimeHandle; debugEventCallback: JsDiagDebugEventCallback;\n    callbackState: Pointer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Stops debugging in the given runtime.\n  /// </summary>\n  /// <param name=\"runtimeHandle\">Runtime to stop debugging.</param>\n  /// <param name=\"callbackState\">User provided state that was passed in JsDiagStartDebugging.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The runtime should be active on the current thread and in debug state.\n  /// </remarks>\n  function JsDiagStopDebugging(runtimeHandle: JsRuntimeHandle; callbackState: PPointer): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Request the runtime to break on next JavaScript statement.\n  /// </summary>\n  /// <param name=\"runtimeHandle\">Runtime to request break.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The runtime should be in debug state. This API can be called from another runtime.\n  /// </remarks>\n  function JsDiagRequestAsyncBreak(runtimeHandle: JsRuntimeHandle): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     List all breakpoints in the current runtime.\n  /// </summary>\n  /// <param name=\"breakpoints\">Array of breakpoints.</param>\n  /// <remarks>\n  ///     <para>\n  ///     [{\n  ///         \"breakpointId\" : 1,\n  ///         \"scriptId\" : 1,\n  ///         \"line\" : 0,\n  ///         \"column\" : 62\n  ///     }]\n  ///     </para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The current runtime should be in debug state. This API can be called when runtime is at a break or running.\n  /// </remarks>\n  function JsDiagGetBreakpoints(out breakpoints: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets breakpoint in the specified script at give location.\n  /// </summary>\n  /// <param name=\"scriptId\">Id of script from JsDiagGetScripts or JsDiagGetSource to put breakpoint.</param>\n  /// <param name=\"lineNumber\">0 based line number to put breakpoint.</param>\n  /// <param name=\"columnNumber\">0 based column number to put breakpoint.</param>\n  /// <param name=\"breakpoint\">Breakpoint object with id, line and column if success.</param>\n  /// <remarks>\n  ///     <para>\n  ///     {\n  ///         \"breakpointId\" : 1,\n  ///         \"line\" : 2,\n  ///         \"column\" : 4\n  ///     }\n  ///     </para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The current runtime should be in debug state. This API can be called when runtime is at a break or running.\n  /// </remarks>\n  function JsDiagSetBreakpoint(scriptId, lineNumber, columnNumber: Cardinal; out breakpoint: JsValueRef): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Remove a breakpoint.\n  /// </summary>\n  /// <param name=\"breakpointId\">Breakpoint id returned from JsDiagSetBreakpoint.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The current runtime should be in debug state. This API can be called when runtime is at a break or running.\n  /// </remarks>\n  function JsDiagRemoveBreakpoint(breakpointId: Cardinal): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets break on exception handling.\n  /// </summary>\n  /// <param name=\"runtimeHandle\">Runtime to set break on exception attributes.</param>\n  /// <param name=\"exceptionAttributes\">Mask of JsDiagBreakOnExceptionAttributes to set.</param>\n  /// <remarks>\n  ///     <para>\n  ///         If this API is not called the default value is set to JsDiagBreakOnExceptionAttributeUncaught in the runtime.\n  ///     </para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The runtime should be in debug state. This API can be called from another runtime.\n  /// </remarks>\n  function JsDiagSetBreakOnException(runtimeHandle: JsRuntimeHandle;\n    exceptionAttributes: JsDiagBreakOnExceptionAttributes): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets break on exception setting.\n  /// </summary>\n  /// <param name=\"runtimeHandle\">Runtime from which to get break on exception attributes, should be in debug mode.</param>\n  /// <param name=\"exceptionAttributes\">Mask of JsDiagBreakOnExceptionAttributes.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The runtime should be in debug state. This API can be called from another runtime.\n  /// </remarks>\n  function JsDiagGetBreakOnException(runtimeHandle: JsRuntimeHandle;\n    out exceptionAttributes: JsDiagBreakOnExceptionAttributes): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Sets the step type in the runtime after a debug break.\n  /// </summary>\n  /// <remarks>\n  ///     Requires to be at a debug break.\n  /// </remarks>\n  /// <param name=\"resumeType\">Type of JsDiagStepType.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The current runtime should be in debug state. This API can only be called when runtime is at a break.\n  /// </remarks>\n  function JsDiagSetStepType(stepType: JsDiagStepType): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets list of scripts.\n  /// </summary>\n  /// <param name=\"scriptsArray\">Array of script objects.</param>\n  /// <remarks>\n  ///     <para>\n  ///     [{\n  ///         \"scriptId\" : 2,\n  ///         \"fileName\" : \"c:\\\\Test\\\\Test.js\",\n  ///         \"lineCount\" : 4,\n  ///         \"sourceLength\" : 111\n  ///       }, {\n  ///         \"scriptId\" : 3,\n  ///         \"parentScriptId\" : 2,\n  ///         \"scriptType\" : \"eval code\",\n  ///         \"lineCount\" : 1,\n  ///         \"sourceLength\" : 12\n  ///     }]\n  ///     </para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The current runtime should be in debug state. This API can be called when runtime is at a break or running.\n  /// </remarks>\n  function JsDiagGetScripts(out scriptsArray: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets source for a specific script identified by scriptId from JsDiagGetScripts.\n  /// </summary>\n  /// <param name=\"scriptId\">Id of the script.</param>\n  /// <param name=\"source\">Source object.</param>\n  /// <remarks>\n  ///     <para>\n  ///     {\n  ///         \"scriptId\" : 1,\n  ///         \"fileName\" : \"c:\\\\Test\\\\Test.js\",\n  ///         \"lineCount\" : 12,\n  ///         \"sourceLength\" : 15154,\n  ///         \"source\" : \"var x = 1;\"\n  ///     }\n  ///     </para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The current runtime should be in debug state. This API can be called when runtime is at a break or running.\n  /// </remarks>\n  function JsDiagGetSource(scriptId: Cardinal; out source: JsValueRef): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the source information for a function object.\n  /// </summary>\n  /// <param name=\"function\">JavaScript function.</param>\n  /// <param name=\"functionPosition\">Function position - scriptId, start line, start column, line number of first statement, column number of first statement.</param>\n  /// <remarks>\n  ///     <para>\n  ///     {\n  ///         \"scriptId\" : 1,\n  ///         \"fileName\" : \"c:\\\\Test\\\\Test.js\",\n  ///         \"line\" : 1,\n  ///         \"column\" : 2,\n  ///         \"firstStatementLine\" : 6,\n  ///         \"firstStatementColumn\" : 0\n  ///     }\n  ///     </para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     This API can be called when runtime is at a break or running.\n  /// </remarks>\n  function JsDiagGetFunctionPosition(_function: JsValueRef; out functionPosition: JsValueRef): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the stack trace information.\n  /// </summary>\n  /// <param name=\"stackTrace\">Stack trace information.</param>\n  /// <remarks>\n  ///     <para>\n  ///     [{\n  ///         \"index\" : 0,\n  ///         \"scriptId\" : 2,\n  ///         \"line\" : 3,\n  ///         \"column\" : 0,\n  ///         \"sourceLength\" : 9,\n  ///         \"sourceText\" : \"var x = 1\",\n  ///         \"functionHandle\" : 1\n  ///     }]\n  ///    </para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The current runtime should be in debug state. This API can only be called when runtime is at a break.\n  /// </remarks>\n  function JsDiagGetStackTrace(out stackTrace: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the list of properties corresponding to the frame.\n  /// </summary>\n  /// <param name=\"stackFrameIndex\">Index of stack frame from JsDiagGetStackTrace.</param>\n  /// <param name=\"properties\">Object of properties array (properties, scopes and globals).</param>\n  /// <remarks>\n  ///     <para>\n  ///     propertyAttributes is a bit mask of\n  ///         NONE = 0x1,\n  ///         HAVE_CHILDRENS = 0x2,\n  ///         READ_ONLY_VALUE = 0x4,\n  ///         IN_TDZ = 0x8,\n  ///     </para>\n  ///     <para>\n  ///     {\n  ///         \"thisObject\": {\n  ///             \"name\": \"this\",\n  ///             \"type\" : \"object\",\n  ///             \"className\" : \"Object\",\n  ///             \"display\" : \"{...}\",\n  ///             \"propertyAttributes\" : 1,\n  ///             \"handle\" : 306\n  ///         },\n  ///         \"exception\" : {\n  ///             \"name\" : \"{exception}\",\n  ///             \"type\" : \"object\",\n  ///             \"display\" : \"'a' is undefined\",\n  ///             \"className\" : \"Error\",\n  ///             \"propertyAttributes\" : 1,\n  ///             \"handle\" : 307\n  ///         }\n  ///         \"arguments\" : {\n  ///             \"name\" : \"arguments\",\n  ///             \"type\" : \"object\",\n  ///             \"display\" : \"{...}\",\n  ///             \"className\" : \"Object\",\n  ///             \"propertyAttributes\" : 1,\n  ///             \"handle\" : 190\n  ///         },\n  ///         \"returnValue\" : {\n  ///             \"name\" : \"[Return value]\",\n  ///             \"type\" : \"undefined\",\n  ///             \"propertyAttributes\" : 0,\n  ///             \"handle\" : 192\n  ///         },\n  ///         \"functionCallsReturn\" : [{\n  ///                 \"name\" : \"[foo1 returned]\",\n  ///                 \"type\" : \"number\",\n  ///                 \"value\" : 1,\n  ///                 \"propertyAttributes\" : 2,\n  ///                 \"handle\" : 191\n  ///             }\n  ///         ],\n  ///         \"locals\" : [],\n  ///         \"scopes\" : [{\n  ///                 \"index\" : 0,\n  ///                 \"handle\" : 193\n  ///             }\n  ///         ],\n  ///         \"globals\" : {\n  ///             \"handle\" : 194\n  ///         }\n  ///     }\n  ///     </para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The current runtime should be in debug state. This API can only be called when runtime is at a break.\n  /// </remarks>\n  function JsDiagGetStackProperties(stackFrameIndex: Cardinal; out properties: JsValueRef): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the list of children of a handle.\n  /// </summary>\n  /// <param name=\"objectHandle\">Handle of object.</param>\n  /// <param name=\"fromCount\">0-based from count of properties, usually 0.</param>\n  /// <param name=\"totalCount\">Number of properties to return.</param>\n  /// <param name=\"propertiesObject\">Array of properties.</param>\n  /// <remarks>Handle should be from objects returned from call to JsDiagGetStackProperties.</remarks>\n  /// <remarks>For scenarios where object have large number of properties totalCount can be used to control how many properties are given.</remarks>\n  /// <remarks>\n  ///     <para>\n  ///     {\n  ///         \"totalPropertiesOfObject\": 10,\n  ///         \"properties\" : [{\n  ///                 \"name\" : \"__proto__\",\n  ///                 \"type\" : \"object\",\n  ///                 \"display\" : \"{...}\",\n  ///                 \"className\" : \"Object\",\n  ///                 \"propertyAttributes\" : 1,\n  ///                 \"handle\" : 156\n  ///             }\n  ///         ],\n  ///         \"debuggerOnlyProperties\" : [{\n  ///                 \"name\" : \"[Map]\",\n  ///                 \"type\" : \"string\",\n  ///                 \"value\" : \"size = 0\",\n  ///                 \"propertyAttributes\" : 2,\n  ///                 \"handle\" : 157\n  ///             }\n  ///         ]\n  ///     }\n  ///     </para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The current runtime should be in debug state. This API can only be called when runtime is at a break.\n  /// </remarks>\n  function JsDiagGetProperties(objectHandle, fromCount, totalCount: Cardinal;\n    out propertiesObject: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Gets the object corresponding to handle.\n  /// </summary>\n  /// <param name=\"objectHandle\">Handle of object.</param>\n  /// <param name=\"handleObject\">Object corresponding to the handle.</param>\n  /// <remarks>\n  ///     <para>\n  ///     {\n  ///         \"scriptId\" : 24,\n  ///          \"line\" : 1,\n  ///          \"column\" : 63,\n  ///          \"name\" : \"foo\",\n  ///          \"type\" : \"function\",\n  ///          \"handle\" : 2\n  ///     }\n  ///    </para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  /// <remarks>\n  ///     The current runtime should be in debug state. This API can only be called when runtime is at a break.\n  /// </remarks>\n  function JsDiagGetObjectFromHandle(objectHandle: Cardinal; out handleObject: JsValueRef): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     Evaluates an expression on given frame.\n  /// </summary>\n  /// <param name=\"expression\">\n  ///     Javascript String or ArrayBuffer (incl. ExternalArrayBuffer).\n  /// </param>\n  /// <param name=\"stackFrameIndex\">Index of stack frame on which to evaluate the expression.</param>\n  /// <param name=\"parseAttributes\">\n  ///     Defines how `expression` (JsValueRef) should be parsed.\n  ///     - `JsParseScriptAttributeNone` when `expression` is a Utf8 encoded ArrayBuffer and/or a Javascript String (encoding independent)\n  ///     - `JsParseScriptAttributeArrayBufferIsUtf16Encoded` when `expression` is Utf16 Encoded ArrayBuffer\n  ///     - `JsParseScriptAttributeLibraryCode` has no use for this function and has similar effect with `JsParseScriptAttributeNone`\n  /// </param>\n  /// <param name=\"forceSetValueProp\">Forces the result to contain the raw value of the expression result.</param>\n  /// <param name=\"evalResult\">Result of evaluation.</param>\n  /// <remarks>\n  ///     <para>\n  ///     evalResult when evaluating 'this' and return is JsNoError\n  ///     {\n  ///         \"name\" : \"this\",\n  ///         \"type\" : \"object\",\n  ///         \"className\" : \"Object\",\n  ///         \"display\" : \"{...}\",\n  ///         \"propertyAttributes\" : 1,\n  ///         \"handle\" : 18\n  ///     }\n  ///\n  ///     evalResult when evaluating a script which throws JavaScript error and return is JsErrorScriptException\n  ///     {\n  ///         \"name\" : \"a.b.c\",\n  ///         \"type\" : \"object\",\n  ///         \"className\" : \"Error\",\n  ///         \"display\" : \"'a' is undefined\",\n  ///         \"propertyAttributes\" : 1,\n  ///         \"handle\" : 18\n  ///     }\n  ///     </para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, evalResult will contain the result\n  ///     The code <c>JsErrorScriptException</c> if evaluate generated a JavaScript exception, evalResult will contain the error details\n  ///     Other error code for invalid parameters or API was not called at break\n  /// </returns>\n  /// <remarks>\n  ///     The current runtime should be in debug state. This API can only be called when runtime is at a break.\n  /// </remarks>\n  function JsDiagEvaluate(expression: JsValueRef; stackFrameIndex: Cardinal; parseAttributes: JsParseScriptAttributes;\n    forceSetValueProp: bool; out evalResult: JsValueRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\ntype\n  /////////////////////\n  /// <summary>\n  ///     TimeTravel move options as bit flag enum.\n  /// </summary>\n  JsTTDMoveModes = (\n      /// <summary>\n      ///     Indicates no special actions needed for move.\n      /// </summary>\n      JsTTDMoveNone = $0,\n\n      /// <summary>\n      ///     Indicates that we want to move to the first event.\n      /// </summary>\n      JsTTDMoveFirstEvent = $1,\n\n      /// <summary>\n      ///     Indicates that we want to move to the last event.\n      /// </summary>\n      JsTTDMoveLastEvent = $2,\n\n      /// <summary>\n      ///     Indicates that we want to move to the kth event -- top 32 bits are event count.\n      /// </summary>\n      JsTTDMoveKthEvent = $4,\n\n      /// <summary>\n      ///     Indicates if we are doing the scan for a continue operation\n      /// </summary>\n      JsTTDMoveScanIntervalForContinue = $10,\n\n      /// <summary>\n      ///     Indicates if we are doing the scan for a continue operation and are in the time-segment where the active breakpoint was\n      /// </summary>\n      JsTTDMoveScanIntervalForContinueInActiveBreakpointSegment = $20,\n\n      /// <summary>\n      ///     Indicates if we want to set break on entry or just run and let something else trigger breakpoints.\n      /// </summary>\n      JsTTDMoveBreakOnEntry = $100\n  );\n  JsTTDMoveMode = Cardinal;\n\n  /// <summary>\n  ///     A handle for URI's that TTD information is written to/read from.\n  /// </summary>\n  JsTTDStreamHandle = Pointer;\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Construct a JsTTDStreamHandle that will be used to read/write the event log portion of the TTD data based on the uri\n  ///     provided by JsTTDInitializeUriCallback.\n  /// </summary>\n  /// <remarks>\n  ///     <para>Exactly one of read or write will be set to true.</para>\n  /// </remarks>\n  /// <param name=\"uriLength\">The length of the uri array that the host passed in for storing log info.</param>\n  /// <param name=\"uri\">The URI that the host passed in for storing log info.</param>\n  /// <param name=\"asciiNameLength\">The length of the ascii name array that the host passed in for storing log info.</param>\n  /// <param name=\"asciiResourceName\">An optional ascii string giving a unique name to the resource that the JsTTDStreamHandle will be created for.</param>\n  /// <param name=\"read\">If the handle should be opened for reading.</param>\n  /// <param name=\"write\">If the handle should be opened for writing.</param>\n  /// <returns>A JsTTDStreamHandle opened in read/write mode as specified.</returns>\n  TTDOpenResourceStreamCallback = function(uriLength: size_t; uri: PAnsiChar; asciiNameLength: size_t;\n    asciiResourceName: PAnsiChar; read, write: bool): JsTTDStreamHandle; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     A callback for reading data from a handle.\n  /// </summary>\n  /// <param name=\"handle\">The JsTTDStreamHandle to read the data from.</param>\n  /// <param name=\"buff\">The buffer to place the data into.</param>\n  /// <param name=\"size\">The max number of bytes that should be read.</param>\n  /// <param name=\"readCount\">The actual number of bytes read and placed in the buffer.</param>\n  /// <returns>true if the read was successful false otherwise.</returns>\n  JsTTDReadBytesFromStreamCallback = function(handle: JsTTDStreamHandle; buff: PByte; size: size_t;\n    out readCount: size_t): bool; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     A callback for writing data to a handle.\n  /// </summary>\n  /// <param name=\"handle\">The JsTTDStreamHandle to write the data to.</param>\n  /// <param name=\"buff\">The buffer to copy the data from.</param>\n  /// <param name=\"size\">The max number of bytes that should be written.</param>\n  /// <param name=\"readCount\">The actual number of bytes written to the HANDLE.</param>\n  /// <returns>true if the write was successful false otherwise.</returns>\n  JsTTDWriteBytesToStreamCallback = function (handle: JsTTDStreamHandle; buff: PByte; size: size_t;\n    out writtenCount: size_t): bool; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Flush and close the stream represented by the HANDLE as needed.\n  /// </summary>\n  /// <remarks>\n  ///     <para>Exactly one of read or write will be set to true.</para>\n  /// </remarks>\n  /// <param name=\"handle\">The JsTTDStreamHandle to close.</param>\n  /// <param name=\"read\">If the handle was opened for reading.</param>\n  /// <param name=\"write\">If the handle was opened for writing.</param>\n  JsTTDFlushAndCloseStreamCallback = procedure(handle: JsTTDStreamHandle; read, write: bool);\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Creates a new runtime in Record Mode.\n  /// </summary>\n  /// <param name=\"attributes\">The attributes of the runtime to be created.</param>\n  /// <param name=\"enableDebugging\">A flag to enable debugging during record.</param>\n  /// <param name=\"snapInterval\">The interval to wait between snapshots (measured in millis).</param>\n  /// <param name=\"snapHistoryLength\">The amount of history to maintain before discarding -- measured in number of snapshots and controls how far back in time a trace can be reversed.</param>\n  /// <param name=\"openResourceStream\">The <c>TTDOpenResourceStreamCallback</c> function for generating a JsTTDStreamHandle to read/write serialized data.</param>\n  /// <param name=\"writeBytesToStream\">The <c>JsTTDWriteBytesToStreamCallback</c> function for writing bytes to a JsTTDStreamHandle.</param>\n  /// <param name=\"flushAndCloseStream\">The <c>JsTTDFlushAndCloseStreamCallback</c> function for flushing and closing a JsTTDStreamHandle as needed.</param>\n  /// <param name=\"threadService\">The thread service for the runtime. Can be null.</param>\n  /// <param name=\"runtime\">The runtime created.</param>\n  /// <remarks>\n  ///     <para>See <c>JsCreateRuntime</c> for additional information.</para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsTTDCreateRecordRuntime(attributes: JsRuntimeAttributes; enableDebugging: bool; snapInterval, snapHistoryLength: size_t;\n    openResourceStream: TTDOpenResourceStreamCallback; writeBytesToStream: JsTTDWriteBytesToStreamCallback;\n    flushAndCloseStream: JsTTDFlushAndCloseStreamCallback; threadService: JsThreadServiceCallback;\n    out runtime: JsRuntimeHandle): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Creates a new runtime in Debug Mode.\n  /// </summary>\n  /// <param name=\"attributes\">The attributes of the runtime to be created.</param>\n  /// <param name=\"infoUri\">The uri where the recorded Time-Travel data should be loaded from.</param>\n  /// <param name=\"enableDebugging\">A flag to enable additional debugging operation support during replay.</param>\n  /// <param name=\"openResourceStream\">The <c>TTDOpenResourceStreamCallback</c> function for generating a JsTTDStreamHandle to read/write serialized data.</param>\n  /// <param name=\"readBytesFromStream\">The <c>JsTTDReadBytesFromStreamCallback</c> function for reading bytes from a JsTTDStreamHandle.</param>\n  /// <param name=\"flushAndCloseStream\">The <c>JsTTDFlushAndCloseStreamCallback</c> function for flushing and closing a JsTTDStreamHandle as needed.</param>\n  /// <param name=\"threadService\">The thread service for the runtime. Can be null.</param>\n  /// <param name=\"runtime\">The runtime created.</param>\n  /// <remarks>\n  ///     <para>See <c>JsCreateRuntime</c> for additional information.</para>\n  /// </remarks>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsTTDCreateReplayRuntime(attributes: JsRuntimeAttributes; infoUri: PAnsiChar; infoUriCount: size_t;\n    enableDebugging: bool; openResourceStream: TTDOpenResourceStreamCallback;\n    readBytesFromStream: JsTTDReadBytesFromStreamCallback; flushAndCloseStream: JsTTDFlushAndCloseStreamCallback;\n    threadService: JsThreadServiceCallback; out runtime: JsRuntimeHandle): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Creates a script context that takes the TTD mode from the log or explicitly is not in TTD mode (regular takes mode from currently active script).\n  /// </summary>\n  /// <param name=\"runtime\">The runtime the script context is being created in.</param>\n  /// <param name=\"useRuntimeTTDMode\">Set to true to use runtime TTD mode false to explicitly be non-TTD context.</param>\n  /// <param name=\"newContext\">The created script context.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsTTDCreateContext(runtimeHandle: JsRuntimeHandle; useRuntimeTTDMode: bool;\n    out newContext: JsContextRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Notify the time-travel system that a context has been identified as dead by the gc (and is being de-allocated).\n  /// </summary>\n  /// <param name=\"context\">The script context that is now dead.</param>\n  /// <returns>\n  ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.\n  /// </returns>\n  function JsTTDNotifyContextDestroy(context: JsContextRef): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Start Time-Travel record or replay at next turn of event loop.\n  /// </summary>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDStart: JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Stop Time-Travel record or replay.\n  /// </summary>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDStop: JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Pause Time-Travel recording before executing code on behalf of debugger or other diagnostic/telemetry.\n  /// </summary>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDPauseTimeTravelBeforeRuntimeOperation: JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     ReStart Time-Travel recording after executing code on behalf of debugger or other diagnostic/telemetry.\n  /// </summary>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDReStartTimeTravelAfterRuntimeOperation: JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Notify the Js runtime we are at a safe yield point in the event loop (i.e. no locals on the stack and we can process as desired).\n  /// </summary>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDNotifyYield: JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Notify the TTD runtime that we are doing a weak add on a reference (we may use this in external API calls and the release will happen in a GC callback).\n  /// </summary>\n  /// <param name=\"value\">The value we are adding the ref to.</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDNotifyLongLivedReferenceAdd(value: JsValueRef): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Notify the Js runtime the host is aborting the process and what the status code is.\n  /// </summary>\n  /// <param name=\"statusCode\">The exit status code.</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDHostExit(statusCode: Integer): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Notify the event log that the contents of one buffer have been copied to a second buffer.\n  /// </summary>\n  /// <param name=\"dst\">The buffer that was written into.</param>\n  /// <param name=\"dstIndex\">The first index modified.</param>\n  /// <param name=\"src\">The buffer that was copied from.</param>\n  /// <param name=\"srcIndex\">The first index copied.</param>\n  /// <param name=\"count\">The number of bytes copied.</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDRawBufferCopySyncIndirect(dst: JsValueRef; dstIndex: size_t; src: JsValueRef;\n    srcIndex, count: size_t): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Notify the event log that the contents of a naked byte* buffer passed to the host have been modified synchronously.\n  /// </summary>\n  /// <param name=\"buffer\">The buffer that was modified.</param>\n  /// <param name=\"index\">The first index modified.</param>\n  /// <param name=\"count\">The number of bytes written.</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDRawBufferModifySyncIndirect(buffer: JsValueRef; index, count: size_t): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Get info for notifying the TTD system that a raw buffer it shares with the host has been modified.\n  /// </summary>\n  /// <param name=\"instance\">The array buffer we want to monitor for contents modification.</param>\n  /// <param name=\"initialModPos\">The first position in the buffer that may be modified.</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDRawBufferAsyncModificationRegister(instance: JsValueRef; initialModPos: PByte): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Notify the event log that the contents of a naked byte* buffer passed to the host have been modified asynchronously.\n  /// </summary>\n  /// <param name=\"finalModPos\">One past the last modified position in the buffer.</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDRawBufferAsyncModifyComplete(finalModPos: PByte): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     A check for unimplemented TTD actions in the host.\n  ///     This API is a TEMPORARY API while we complete the implementation of TTD support in the Node host and will be deleted once that is complete.\n  /// </summary>\n  /// <param name=\"msg\">The message to print if we should be catching this as a TTD operation.</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDCheckAndAssertIfTTDRunning(msg: PAnsiChar): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Before calling JsTTDMoveToTopLevelEvent (which inflates a snapshot and replays) check to see if we want to reset the script context.\n  ///     We reset the script context if the move will require inflating from a different snapshot that the last one.\n  /// </summary>\n  /// <param name=\"runtimeHandle\">The runtime handle that the script is executing in.</param>\n  /// <param name=\"moveMode\">Flags controlling the way the move it performed and how other parameters are interpreted.</param>\n  /// <param name=\"kthEvent\">When <c>moveMode == JsTTDMoveKthEvent</c> indicates which event, otherwise this parameter is ignored.</param>\n  /// <param name=\"targetEventTime\">The event time we want to move to or -1 if not relevant.</param>\n  /// <param name=\"targetStartSnapTime\">Out parameter with the event time of the snapshot that we should inflate from.</param>\n  /// <param name=\"targetEndSnapTime\">Optional Out parameter with the snapshot time following the event.</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDGetSnapTimeTopLevelEventMove(runtimeHandle: JsRuntimeHandle; moveMode: JsTTDMoveMode; kthEvent: Cardinal;\n    targetEventTime: Int64; out targetStartSnapTime: Int64; targetEndSnapTime: PInt64): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Get the snapshot interval that bounds the target event time.\n  /// </summary>\n  /// <param name=\"runtimeHandle\">The runtime handle that the script is executing in.</param>\n  /// <param name=\"targetEventTime\">The event time we want to get the interval for.</param>\n  /// <param name=\"startSnapTime\">The snapshot time that comes before the desired event.</param>\n  /// <param name=\"endSnapTime\">The snapshot time that comes after the desired event (-1 if the leg ends before a snapshot appears).</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDGetSnapShotBoundInterval(runtimeHandle: JsRuntimeHandle; targetEventTime: Int64;\n    out startSnapTime, endSnapTime: Int64): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Get the snapshot interval that precedes the one given by currentSnapStartTime (or -1 if there is no such interval).\n  /// </summary>\n  /// <param name=\"runtimeHandle\">The runtime handle that the script is executing in.</param>\n  /// <param name=\"currentSnapStartTime\">The current snapshot interval start time.</param>\n  /// <param name=\"previousSnapTime\">The resulting previous snapshot interval start time or -1 if no such time.</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDGetPreviousSnapshotInterval(runtimeHandle: JsRuntimeHandle; currentSnapStartTime: Int64;\n    out previousSnapTime: Int64): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     During debug operations some additional information is populated during replay. This runs the code between the given\n  ///     snapshots to populate this information which may be needed by the debugger to determine time-travel jump targets.\n  /// </summary>\n  /// <param name=\"runtimeHandle\">The runtime handle that the script is executing in.</param>\n  ///<param name = \"startSnapTime\">The snapshot time that we will start executing from.< / param>\n  ///<param name = \"endSnapTime\">The snapshot time that we will stop at (or -1 if we want to run to the end).< / param>\n  /// <param name=\"moveMode\">Additional flags for controling how the move is done.</param>\n  /// <param name=\"newTargetEventTime\">The updated target event time set according to the moveMode (-1 if not found).</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDPreExecuteSnapShotInterval(runtimeHandle: JsRuntimeHandle; startSnapTime, endSnapTime: Int64;\n    moveMode: JsTTDMoveMode; out newTargetEventTime: Int64): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Move to the given top-level call event time (assuming JsTTDPrepContextsForTopLevelEventMove) was called previously to reset any script contexts.\n  ///     This also computes the ready-to-run snapshot if needed.\n  /// </summary>\n  /// <param name=\"runtimeHandle\">The runtime handle that the script is executing in.</param>\n  /// <param name=\"moveMode\">Additional flags for controling how the move is done.</param>\n  /// <param name=\"snapshotTime\">The event time that we will start executing from to move to the given target time.</param>\n  /// <param name=\"eventTime\">The event that we want to move to.</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDMoveToTopLevelEvent(runtimeHandle: JsRuntimeHandle; moveMode: JsTTDMoveMode;\n    snapshotTime, eventTime: Int64): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Execute from the current point in the log to the end returning the error code.\n  /// </summary>\n  /// <param name=\"moveMode\">Additional flags for controling how the move is done.</param>\n  /// <param name=\"rootEventTime\">The event time that we should move to next or notification (-1) that replay has ended.</param>\n  /// <returns>\n  ///     If the debugger requested an abort the code is JsNoError -- rootEventTime is the target event time we need to move to and re - execute from.\n  ///     If we aborted at the end of the replay log the code is JsNoError -- rootEventTime is -1.\n  ///     If there was an unhandled script exception the code is JsErrorCategoryScript.\n  /// </returns>\n  function JsTTDReplayExecution(moveMode: JsTTDMoveMode; out rootEventTime: Int64): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     Enable or disable autotrace ability from JsRT.\n  /// </summary>\n  /// <param name=\"status\">True to enable autotracing false to disable it.</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDDiagSetAutoTraceStatus(status: bool): JsErrorCode; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\n  /// <summary>\n  ///     TTD API -- may change in future versions:\n  ///     A way for the debugger to programatically write a trace when it is at a breakpoint.\n  /// </summary>\n  /// <param name=\"uri\">The URI that the log should be written into.</param>\n  /// <param name=\"uriLength\">The length of the uri array that the host passed in for storing log info.</param>\n  /// <returns>The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.</returns>\n  function JsTTDDiagWriteLog(uri: PAnsiChar; uriLength: size_t): JsErrorCode;\n    {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\n\nimplementation\n\n{$ifdef MSWINDOWS}\nconst\n  _chakracore = 'chakracore.dll';\n{$endif}\n\n{$ifdef DARWIN}\nconst\n  _chakracore = 'libChakraCore.dylib';\n{$endif}\n\n{$ifdef LINUX}\nconst\n  _chakracore = 'libChakraCore.so';\n{$endif}\n\n  function JsDiagStartDebugging; external _chakracore;\n  function JsDiagStopDebugging; external _chakracore;\n  function JsDiagRequestAsyncBreak; external _chakracore;\n  function JsDiagGetBreakpoints; external _chakracore;\n  function JsDiagSetBreakpoint; external _chakracore;\n  function JsDiagRemoveBreakpoint; external _chakracore;\n  function JsDiagSetBreakOnException; external _chakracore;\n  function JsDiagGetBreakOnException; external _chakracore;\n  function JsDiagSetStepType; external _chakracore;\n  function JsDiagGetScripts; external _chakracore;\n  function JsDiagGetSource; external _chakracore;\n  function JsDiagGetFunctionPosition; external _chakracore;\n  function JsDiagGetStackTrace; external _chakracore;\n  function JsDiagGetStackProperties; external _chakracore;\n  function JsDiagGetProperties; external _chakracore;\n  function JsDiagGetObjectFromHandle; external _chakracore;\n  function JsDiagEvaluate; external _chakracore;\n  function JsTTDCreateRecordRuntime; external _chakracore;\n  function JsTTDCreateReplayRuntime; external _chakracore;\n  function JsTTDCreateContext; external _chakracore;\n  function JsTTDNotifyContextDestroy; external _chakracore;\n  function JsTTDStart; external _chakracore;\n  function JsTTDStop; external _chakracore;\n  function JsTTDPauseTimeTravelBeforeRuntimeOperation; external _chakracore;\n  function JsTTDReStartTimeTravelAfterRuntimeOperation; external _chakracore;\n  function JsTTDNotifyYield; external _chakracore;\n  function JsTTDNotifyLongLivedReferenceAdd; external _chakracore;\n  function JsTTDHostExit; external _chakracore;\n  function JsTTDRawBufferCopySyncIndirect; external _chakracore;\n  function JsTTDRawBufferModifySyncIndirect; external _chakracore;\n  function JsTTDRawBufferAsyncModificationRegister; external _chakracore;\n  function JsTTDRawBufferAsyncModifyComplete; external _chakracore;\n  function JsTTDCheckAndAssertIfTTDRunning; external _chakracore;\n  function JsTTDGetSnapTimeTopLevelEventMove; external _chakracore;\n  function JsTTDGetSnapShotBoundInterval; external _chakracore;\n  function JsTTDGetPreviousSnapshotInterval; external _chakracore;\n  function JsTTDPreExecuteSnapShotInterval; external _chakracore;\n  function JsTTDMoveToTopLevelEvent; external _chakracore;\n  function JsTTDReplayExecution; external _chakracore;\n  function JsTTDDiagSetAutoTraceStatus; external _chakracore;\n  function JsTTDDiagWriteLog; external _chakracore;\n\nend.\n"
  },
  {
    "path": "src/Compat.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nunit Compat;\n\ninterface\n\n{$include common.inc}\n\n{$ifdef FPC}\n  {$macro ON}\n  {$warn SYMBOL_PLATFORM OFF}\n{$endif}\n\nuses\n{$ifdef DELPHI}\n  Windows,\n{$endif}\n  SysUtils;\n\n{$ifndef HAS_NATIVEUINT}\ntype\n  PNativeUInt = ^NativeUInt;\n  NativeUInt = Cardinal;\n{$endif}\n\n{$ifndef HAS_RAWBYTESTRING}\ntype\n  RawByteString = AnsiString;\n{$endif}\n\n{$ifndef HAS_UINTPTR}\ntype\n  PUIntPtr = ^UIntPtr;\n  UIntPtr = NativeUInt;\n{$endif}\n\n{$ifndef HAS_WSTRPOS}\nfunction WStrPos(const Str1, Str2: PWideChar): PWideChar;\n{$endif}\n\ntype\n  PUnicodeChar = ^UnicodeChar;\n  UnicodeChar = WideChar;\n\n{$ifndef SUPPORTS_UNICODE_STRING}\ntype\n  PUnicodeString = ^UnicodeString;\n  UnicodeString = WideString;\n{$endif}\n\n{$ifdef DELPHI}\nfunction UnicodeFormat(const Format: UnicodeString; const Args: array of const): UnicodeString;\nfunction UnicodeSameText(const S1, S2: UnicodeString): Boolean;\nfunction UnicodeStringReplace(const S, OldPattern, NewPattern: UnicodeString; Flags: TReplaceFlags): UnicodeString;\n{$endif DELPHI}\n\nfunction GetBuildInfoString: string;\nfunction GetExeFileVersionString: string;\n\n{$ifdef FPC}\nvar\n  UTF8ToString: function(const S: RawByteString): UnicodeString = @UTF8Decode;\n{$endif}\n\n{$ifdef DELPHI}\n// initialize to US format settings (use point as decimal separator for float values)\nvar\n  DefaultFormatSettings: TFormatSettings;\n\nprocedure InitCriticalSection(var Lock: TRTLCriticalSection);\nprocedure DoneCriticalSection(var Lock: TRTLCriticalSection);\n\n{$ifndef HAS_WIDESTRUTILS}\nfunction WideStringReplace(const S, OldPattern, NewPattern: Widestring; Flags: TReplaceFlags): Widestring;\n{$endif}\n\n{$ifndef UNICODE}\nvar\n  UTF8ToString: function(const S: UTF8String): WideString;\n{$endif}\n{$endif DELPHI}\n\nimplementation\n\n{$ifdef FPC}\nuses\n  {$ifdef WINDOWS}\n  winpeimagereader,\n  {$endif}\n  {$ifdef LINUX}\n  elfreader,\n  {$endif}\n  {$ifdef DARWIN}\n  machoreader,\n  {$endif}\n  fileinfo;\n{$endif}\n\n{$ifdef FPC}\nfunction GetBuildInfoString: string;\nbegin\n  Result := Format('FPC %d.%d.%d for %s-%s', [FPC_VERSION, FPC_RELEASE, FPC_PATCH, lowercase({$i %FPCTARGETOS%}), lowercase({$i %FPCTARGETCPU%})])\nend;\n\nfunction GetExeFileVersionString: string;\nvar\n  FileVersionInfo: TFileVersionInfo;\nbegin\n  FileVersionInfo := TFileVersionInfo.Create(nil);\n  try\n    FileVersionInfo.ReadFileInfo;\n    Result := FileVersionInfo.VersionStrings.Values['FileVersion'];\n  finally\n    FileVersionInfo.Free;\n  end;\nend;\n\n{$ifndef HAS_WSTRPOS}\nfunction WStrPos(const Str1, Str2: PWideChar): PWideChar;\nbegin\n  Result := strpos(Str1, Str2);\nend;\n{$endif}\n{$endif}\n\n{$ifdef DELPHI}\n\nprocedure InitCriticalSection(var Lock: TRTLCriticalSection);\nbegin\n  InitializeCriticalSection(Lock);\nend;\n\nprocedure DoneCriticalSection(var Lock: TRTLCriticalSection);\nbegin\n  Windows.DeleteCriticalSection(Lock);\nend;\n\n{$ifndef HAS_WIDESTRUTILS}\nfunction WideStringReplace(const S, OldPattern, NewPattern: Widestring; Flags: TReplaceFlags): Widestring;\nvar\n  SearchStr, Patt, NewStr: Widestring;\n  Offset: Integer;\nbegin\n  if rfIgnoreCase in Flags then\n  begin\n    SearchStr := WideUpperCase(S);\n    Patt := WideUpperCase(OldPattern);\n  end else\n  begin\n    SearchStr := S;\n    Patt := OldPattern;\n  end;\n  NewStr := S;\n  Result := '';\n  while SearchStr <> '' do\n  begin\n    Offset := Pos(Patt, SearchStr);\n    if Offset = 0 then\n    begin\n      Result := Result + NewStr;\n      Break;\n    end;\n    Result := Result + Copy(NewStr, 1, Offset - 1) + NewPattern;\n    NewStr := Copy(NewStr, Offset + Length(OldPattern), MaxInt);\n    if not (rfReplaceAll in Flags) then\n    begin\n      Result := Result + NewStr;\n      Break;\n    end;\n    SearchStr := Copy(SearchStr, Offset + Length(Patt), MaxInt);\n  end;\nend;\n{$endif}\n\n{$ifdef DELPHI}\nfunction UnicodeFormat(const Format: UnicodeString; const Args: array of const): UnicodeString;\nbegin\n{$ifdef UNICODE}\n  Result := SysUtils.Format(Format, Args);\n{$else}\n  Result := WideFormat(Format, Args);\n{$endif}\nend;\n\nfunction UnicodeSameText(const S1, S2: UnicodeString): Boolean;\nbegin\n{$ifdef UNICODE}\n  Result := SameText(S1, S2);\n{$else}\n  Result := WideSameText(S1, S2);\n{$endif}\nend;\n\nfunction UnicodeStringReplace(const S, OldPattern, NewPattern: UnicodeString; Flags: TReplaceFlags): UnicodeString;\nbegin\n{$ifdef UNICODE}\n  Result := StringReplace(S, OldPattern, NewPattern, Flags);\n{$ELSE}\n  Result := WideStringReplace(S, OldPattern, NewPattern, Flags);\n{$ENDIF}\nend;\n{$endif DELPHI}\n\n{$ifdef DELPHIXE2_UP}\nconst\n  ArchitectureStrings: array[TOSVersion.TArchitecture] of string = ('x86', 'x64', 'arm32'{$ifdef DELPHIX_BERLIN_UP}, 'arm64'{$endif});\n  PlatformStrings: array[TOSVersion.TPlatform] of string = ('Windows', 'MacOS', 'iOS', 'Android', 'WinRT', 'Linux');\n{$endif}\n\nfunction GetBuildInfoString: string;\nbegin\n  {$ifdef DELPHIXE2_UP}\n  Result := Format('Delphi %.1f for %s-%s', [System.CompilerVersion, PlatformStrings[TOSVersion.Platform],\n    ArchitectureStrings[TOSVersion.Architecture]], DefaultFormatSettings);\n  {$else}\n  Result := Format('Delphi %.1f for Windows-x86', [CompilerVersion], DefaultFormatSettings);\n  {$endif}\nend;\n\nfunction GetExeFileVersionString: string;\nvar\n  Ver: LongRec;\nbegin\n  Ver := LongRec(GetFileVersion(Paramstr(0)));\n  Result := Format('%u.%u', [Ver.Hi, Ver.Lo]);\nend;\n\n{$ifndef HAS_WSTRPOS}\nfunction WStrPos(const Str1, Str2: PWideChar): PWideChar;\nvar\n  Str, SubStr: PWideChar;\n  Ch: WideChar;\nbegin\n  Result := nil;\n  if (Str1 = nil) or (Str1^ = #0) or (Str2 = nil) or (Str2^ = #0) then Exit;\n  Result := Str1;\n  Ch := Str2^;\n  repeat\n    if Result^ = Ch then\n    begin\n      Str := Result;\n      SubStr := Str2;\n      repeat\n        Inc(Str);\n        Inc(SubStr);\n        if SubStr^ = #0 then exit;\n        if Str^ = #0 then\n        begin\n          Result := nil;\n          exit;\n        end;\n        if Str^ <> SubStr^ then break;\n      until (FALSE);\n    end;\n    Inc(Result);\n  until (Result^ = #0);\n  Result := nil;\nend;\n{$endif}\n{$endif}\n\ninitialization\n{$ifdef DELPHI}\n{$ifndef UNICODE}\n  UTF8ToString := @UTF8Decode;\n{$endif}\n{$ifdef DELPHIXE_UP}\n  DefaultFormatSettings := TFormatSettings.Create('en-US');\n{$else}\n  GetLocaleFormatSettings(1033, DefaultFormatSettings);\n{$endif}\n{$endif}\n{$ifdef FPC}\n  {$ifdef WINDOWS}\n  GetLocaleFormatSettings(1033, DefaultFormatSettings);\n  {$endif}\n{$endif}\n\nfinalization\n\nend.\n"
  },
  {
    "path": "src/common.inc",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\n{$include ..\\ext\\jedi\\jedi.inc}\n\n{$ifdef MSWINDOWS}\n  {$define WINDOWS}\n{$endif}\n\n{$ifdef FPC}\n  {$ifdef UNIX}\n    {$define UseCThreads}\n  {$endif}\n  {$define HAS_NATIVEUINT}\n  {$define HAS_RAWBYTESTRING}\n  {$define HAS_UINTPTR}\n  {$define SUPPORTS_CLASS_FIELDS}\n  {$define SUPPORTS_UNICODE_STRING}\n{$endif}\n\n{$ifdef DELPHI}\n  {$ifdef DELPHIXE_UP}\n    {$define HAS_NATIVEUINT}\n  {$endif}\n  {$ifdef DELPHI2009_UP}\n    {$define HAS_RAWBYTESTRING}\n  {$endif}\n  {$ifdef DELPHIXE2_UP}\n    {$define HAS_UINTPTR}\n  {$endif}\n  {$ifdef DELPHI2007_UP}\n    {$define HAS_WIDESTRUTILS}\n  {$endif}\n{$endif}\n"
  },
  {
    "path": "tests/ChakraCoreTests.XE.dproj",
    "content": "﻿\t<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\t\t<PropertyGroup>\n\t\t\t<ProjectGuid>{31F06C91-6ED6-4632-93E5-4C71AFB559F7}</ProjectGuid>\n\t\t\t<MainSource>ChakraCoreTests.dpr</MainSource>\n\t\t\t<Config Condition=\"'$(Config)'==''\">Debug</Config>\n\t\t\t<DCC_DCCCompiler>DCC32</DCC_DCCCompiler>\n\t\t\t<ProjectVersion>12.3</ProjectVersion>\n\t\t\t<Base>True</Base>\n\t\t\t<Platform>Win32</Platform>\n\t\t\t<AppType>Console</AppType>\n\t\t\t<FrameworkType>None</FrameworkType>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Base' or '$(Base)'!=''\">\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Release' or '$(Cfg_1)'!=''\">\n\t\t\t<Cfg_1>true</Cfg_1>\n\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Debug' or '$(Cfg_2)'!=''\">\n\t\t\t<Cfg_2>true</Cfg_2>\n\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Base)'!=''\">\n\t\t\t<DCC_DependencyCheckOutputName>..\\bin\\$(Platform)\\$(Config)\\ChakraCoreTests.exe</DCC_DependencyCheckOutputName>\n\t\t\t<DCC_ExeOutput>..\\bin\\$(Platform)\\$(Config)</DCC_ExeOutput>\n\t\t\t<DCC_DcuOutput>..\\lib\\$(Platform)\\$(Config)</DCC_DcuOutput>\n\t\t\t<DCC_ImageBase>00400000</DCC_ImageBase>\n\t\t\t<DCC_UsePackage>vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP;JclDeveloperTools;Jcl;JclVcl;JclContainers</DCC_UsePackage>\n\t\t\t<DCC_UnitAlias>WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;$(DCC_UnitAlias)</DCC_UnitAlias>\n\t\t\t<DCC_Platform>x86</DCC_Platform>\n\t\t\t<DCC_UnitSearchPath>..\\src;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>\n\t\t\t<DCC_K>false</DCC_K>\n\t\t\t<DCC_N>true</DCC_N>\n\t\t\t<DCC_S>false</DCC_S>\n\t\t\t<DCC_SymbolReferenceInfo>1</DCC_SymbolReferenceInfo>\n\t\t\t<DCC_E>false</DCC_E>\n\t\t\t<DCC_F>false</DCC_F>\n\t\t\t<DCC_ConsoleTarget>true</DCC_ConsoleTarget>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Cfg_1)'!=''\">\n\t\t\t<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>\n\t\t\t<DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>\n\t\t\t<DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>\n\t\t\t<DCC_DebugInformation>false</DCC_DebugInformation>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Cfg_2)'!=''\">\n\t\t\t<DCC_Define>DEBUG;$(DCC_Define)</DCC_Define>\n\t\t</PropertyGroup>\n\t\t<ItemGroup>\n\t\t\t<DelphiCompile Include=\"ChakraCoreTests.dpr\">\n\t\t\t\t<MainSource>MainSource</MainSource>\n\t\t\t</DelphiCompile>\n\t\t\t<BuildConfiguration Include=\"Debug\">\n\t\t\t\t<Key>Cfg_2</Key>\n\t\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t</BuildConfiguration>\n\t\t\t<BuildConfiguration Include=\"Base\">\n\t\t\t\t<Key>Base</Key>\n\t\t\t</BuildConfiguration>\n\t\t\t<BuildConfiguration Include=\"Release\">\n\t\t\t\t<Key>Cfg_1</Key>\n\t\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t</BuildConfiguration>\n\t\t</ItemGroup>\n\t\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Delphi.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Delphi.Targets\"/>\n\t\t<Import Condition=\"Exists('$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj')\" Project=\"$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj\"/>\n\t\t<ProjectExtensions>\n\t\t\t<Borland.Personality>Delphi.Personality.12</Borland.Personality>\n\t\t\t<Borland.ProjectType>VCLApplication</Borland.ProjectType>\n\t\t\t<BorlandProject>\n\t\t\t\t<Delphi.Personality>\n\t\t\t\t\t<Source>\n\t\t\t\t\t\t<Source Name=\"MainSource\">ChakraCoreTests.dpr</Source>\n\t\t\t\t\t</Source>\n\t\t\t\t\t<Parameters/>\n\t\t\t\t\t<VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"IncludeVerInfo\">True</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"AutoIncBuild\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"MajorVer\">1</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"MinorVer\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Release\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Build\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Debug\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"PreRelease\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Special\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Private\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"DLL\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Locale\">1033</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"CodePage\">1252</VersionInfo>\n\t\t\t\t\t</VersionInfo>\n\t\t\t\t\t<VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"CompanyName\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"FileDescription\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"FileVersion\">1.0.0.0</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"InternalName\">ChakraCoreTests</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"LegalCopyright\">© 2021 Ondrej Kelle</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"LegalTrademarks\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"OriginalFilename\">ChakraCoreTests</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"ProductName\">chakracore-delphi</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"ProductVersion\">1.0.0.0</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"Comments\"/>\n\t\t\t\t\t</VersionInfoKeys>\n\t\t\t\t</Delphi.Personality>\n\t\t\t\t<Platforms>\n\t\t\t\t\t<Platform value=\"Win32\">True</Platform>\n\t\t\t\t</Platforms>\n\t\t\t</BorlandProject>\n\t\t\t<ProjectFileVersion>12</ProjectFileVersion>\n\t\t</ProjectExtensions>\n\t</Project>\n"
  },
  {
    "path": "tests/ChakraCoreTests.dof",
    "content": "[FileVersion]\nVersion=7.0\n[Compiler]\nA=8\nB=0\nC=1\nD=1\nE=0\nF=0\nG=1\nH=1\nI=1\nJ=0\nK=0\nL=1\nM=0\nN=1\nO=1\nP=1\nQ=0\nR=0\nS=0\nT=0\nU=0\nV=1\nW=0\nX=1\nY=1\nZ=1\nShowHints=1\nShowWarnings=1\nUnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;\nNamespacePrefix=\nSymbolDeprecated=1\nSymbolLibrary=1\nSymbolPlatform=1\nUnitLibrary=1\nUnitPlatform=1\nUnitDeprecated=1\nHResultCompat=1\nHidingMember=1\nHiddenVirtual=1\nGarbage=1\nBoundsError=1\nZeroNilCompat=1\nStringConstTruncated=1\nForLoopVarVarPar=1\nTypedConstVarPar=1\nAsgToTypedConst=1\nCaseLabelRange=1\nForVariable=1\nConstructingAbstract=1\nComparisonFalse=1\nComparisonTrue=1\nComparingSignedUnsigned=1\nCombiningSignedUnsigned=1\nUnsupportedConstruct=1\nFileOpen=1\nFileOpenUnitSrc=1\nBadGlobalSymbol=1\nDuplicateConstructorDestructor=1\nInvalidDirective=1\nPackageNoLink=1\nPackageThreadVar=1\nImplicitImport=1\nHPPEMITIgnored=1\nNoRetVal=1\nUseBeforeDef=1\nForLoopVarUndef=1\nUnitNameMismatch=1\nNoCFGFileFound=1\nMessageDirective=1\nImplicitVariants=1\nUnicodeToLocale=1\nLocaleToUnicode=1\nImagebaseMultiple=1\nSuspiciousTypecast=1\nPrivatePropAccessor=1\nUnsafeType=0\nUnsafeCode=0\nUnsafeCast=0\n[Linker]\nMapFile=0\nOutputObjs=0\nConsoleApp=0\nDebugInfo=0\nRemoteSymbols=0\nMinStackSize=16384\nMaxStackSize=1048576\nImageBase=4194304\nExeDescription=\n[Directories]\nOutputDir=..\\bin\\Win32\\Debug\nUnitOutputDir=..\\lib\\Win32\\Debug\nPackageDLLOutputDir=\nPackageDCPOutputDir=\nSearchPath=..\\src\nPackages=vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP;JclDeveloperTools;Jcl;JclVcl;JclContainers\nConditionals=\nDebugSourceDirs=\nUsePackages=0\n[Parameters]\nRunParams=\nHostApplication=\nLauncher=\nUseLauncher=0\nDebugCWD=\n[Language]\nActiveLang=\nProjectLang=\nRootDir=\n[Version Info]\nIncludeVerInfo=1\nAutoIncBuild=0\nMajorVer=1\nMinorVer=0\nRelease=0\nBuild=0\nDebug=0\nPreRelease=0\nSpecial=0\nPrivate=0\nDLL=0\nLocale=1033\nCodePage=1252\n[Version Info Keys]\nCompanyName=\nFileDescription=\nFileVersion=1.0.0.0\nInternalName=ChakraCoreTests\nLegalCopyright=� 2021 Ondrej Kelle\nLegalTrademarks=\nOriginalFilename=ChakraCoreTests\nProductName=chakracore-delphi\nProductVersion=1.0.0.0\nComments=\n[HistoryLists\\hlUnitAliases]\nCount=1\nItem0=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;\n[HistoryLists\\hlSearchPath]\nCount=1\nItem0=..\\..\\src\n[HistoryLists\\hlUnitOutputDirectory]\nCount=1\nItem0=..\\..\\lib\\Win32\\Debug\n[HistoryLists\\hlOutputDirectorry]\nCount=1\nItem0=..\\..\\bin\\Win32\\Debug\n"
  },
  {
    "path": "tests/ChakraCoreTests.dpr",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nprogram ChakraCoreTests;\n\n{$include ..\\src\\common.inc}\n\n{$ifdef FPC}\n  {$macro ON}\n{$endif}\n\n{$ifdef CONSOLE_TESTRUNNER}\n  {$apptype CONSOLE}\n{$endif}\n\nuses\n  SysUtils, Classes,\n{$ifdef FPC}\n  consoletestrunner, fpcunitreport, plaintestreport,\n{$endif}\n{$ifdef DELPHI}\n  TextTestRunner,\n{$endif}\n  Compat, ChakraCoreVersion, Test_ChakraCore, Test_Classes;\n\n{$R *.res}\n\n{$ifdef FPC}\nvar\n  Application: TTestRunner;\n{$endif}\n\nbegin\n  Writeln(Format('%s %s', [ExtractFileName(ParamStr(0)), GetExeFileVersionString]));\n  Writeln(Format('Built with %s', [GetBuildInfoString]));\n  Writeln(Format('Chakra Core version: %d.%d.%d', [CHAKRA_CORE_MAJOR_VERSION, CHAKRA_CORE_MINOR_VERSION, CHAKRA_CORE_PATCH_VERSION]));\n  Writeln;\n\n{$ifdef FPC}\n  Application := TTestRunner.Create(nil);\n  try\n    Application.Initialize;\n    Application.Run;\n  finally\n    Application.Free;\n  end;\n{$endif}\n\n{$ifdef DELPHI}\n  RunRegisteredTests;\n{$endif}\nend.\n"
  },
  {
    "path": "tests/ChakraCoreTests.lpi",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CONFIG>\n  <ProjectOptions>\n    <Version Value=\"10\"/>\n    <General>\n      <SessionStorage Value=\"InProjectDir\"/>\n      <MainUnit Value=\"0\"/>\n      <Title Value=\"ChakraCoreTests\"/>\n      <UseAppBundle Value=\"False\"/>\n      <ResourceType Value=\"res\"/>\n    </General>\n    <VersionInfo>\n      <UseVersionInfo Value=\"True\"/>\n      <MajorVersionNr Value=\"1\"/>\n      <StringTable InternalName=\"ChakraCoreTests\" LegalCopyright=\"© 2021 Ondrej Kelle\" OriginalFilename=\"ChakraCoreTests\" ProductName=\"chakracore-delphi\"/>\n    </VersionInfo>\n    <BuildModes Count=\"2\">\n      <Item1 Name=\"Debug\" Default=\"True\"/>\n      <Item2 Name=\"Release\">\n        <CompilerOptions>\n          <Version Value=\"11\"/>\n          <Target>\n            <Filename Value=\"bin/$(TargetCPU)-$(TargetOS)/ChakraCoreTests\"/>\n          </Target>\n          <SearchPaths>\n            <IncludeFiles Value=\"$(ProjOutDir)\"/>\n            <OtherUnitFiles Value=\"../src\"/>\n            <UnitOutputDirectory Value=\"lib/$(TargetCPU)-$(TargetOS)\"/>\n          </SearchPaths>\n          <Parsing>\n            <SyntaxOptions>\n              <SyntaxMode Value=\"DelphiUnicode\"/>\n              <UseAnsiStrings Value=\"False\"/>\n            </SyntaxOptions>\n          </Parsing>\n          <CodeGeneration>\n            <SmartLinkUnit Value=\"True\"/>\n            <Optimizations>\n              <OptimizationLevel Value=\"3\"/>\n            </Optimizations>\n          </CodeGeneration>\n          <Linking>\n            <Debugging>\n              <GenerateDebugInfo Value=\"False\"/>\n            </Debugging>\n            <LinkSmart Value=\"True\"/>\n          </Linking>\n        </CompilerOptions>\n      </Item2>\n    </BuildModes>\n    <PublishOptions>\n      <Version Value=\"2\"/>\n    </PublishOptions>\n    <RunParams>\n      <local>\n        <FormatVersion Value=\"1\"/>\n        <CommandLineParams Value=\"-a -p --format=plain\"/>\n      </local>\n      <environment>\n        <UserOverrides Count=\"1\">\n          <Variable0 Name=\"LD_LIBRARY_PATH\" Value=\"$Path($TargetFile)\"/>\n        </UserOverrides>\n      </environment>\n    </RunParams>\n    <RequiredPackages Count=\"1\">\n      <Item1>\n        <PackageName Value=\"FCL\"/>\n      </Item1>\n    </RequiredPackages>\n    <Units Count=\"3\">\n      <Unit0>\n        <Filename Value=\"ChakraCoreTests.dpr\"/>\n        <IsPartOfProject Value=\"True\"/>\n      </Unit0>\n      <Unit1>\n        <Filename Value=\"Test_ChakraCore.pas\"/>\n        <IsPartOfProject Value=\"True\"/>\n      </Unit1>\n      <Unit2>\n        <Filename Value=\"Test_Classes.pas\"/>\n        <IsPartOfProject Value=\"True\"/>\n      </Unit2>\n    </Units>\n  </ProjectOptions>\n  <CompilerOptions>\n    <Version Value=\"11\"/>\n    <Target>\n      <Filename Value=\"../bin/$(TargetCPU)-$(TargetOS)/$(BuildMode)/ChakraCoreTests\"/>\n    </Target>\n    <SearchPaths>\n      <IncludeFiles Value=\"$(ProjOutDir)\"/>\n      <OtherUnitFiles Value=\"../src\"/>\n      <UnitOutputDirectory Value=\"../lib/$(TargetCPU)-$(TargetOS)/$(BuildMode)\"/>\n    </SearchPaths>\n    <Parsing>\n      <SyntaxOptions>\n        <SyntaxMode Value=\"Delphi\"/>\n        <IncludeAssertionCode Value=\"True\"/>\n        <UseAnsiStrings Value=\"False\"/>\n      </SyntaxOptions>\n    </Parsing>\n    <CodeGeneration>\n      <Checks>\n        <IOChecks Value=\"True\"/>\n        <RangeChecks Value=\"True\"/>\n        <OverflowChecks Value=\"True\"/>\n        <StackChecks Value=\"True\"/>\n      </Checks>\n      <VerifyObjMethodCallValidity Value=\"True\"/>\n    </CodeGeneration>\n    <Linking>\n      <Debugging>\n        <DebugInfoType Value=\"dsDwarf2Set\"/>\n        <UseHeaptrc Value=\"True\"/>\n        <TrashVariables Value=\"True\"/>\n        <UseExternalDbgSyms Value=\"True\"/>\n      </Debugging>\n    </Linking>\n  </CompilerOptions>\n  <Debugging>\n    <Exceptions Count=\"5\">\n      <Item1>\n        <Name Value=\"EAbort\"/>\n      </Item1>\n      <Item2>\n        <Name Value=\"ECodetoolError\"/>\n      </Item2>\n      <Item3>\n        <Name Value=\"EFOpenError\"/>\n      </Item3>\n      <Item4>\n        <Name Value=\"EChakraCore\"/>\n      </Item4>\n      <Item5>\n        <Name Value=\"EChakraCoreScript\"/>\n      </Item5>\n    </Exceptions>\n  </Debugging>\n</CONFIG>\n"
  },
  {
    "path": "tests/ChakraCoreTestsUI.XE.dproj",
    "content": "﻿\t<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\t\t<PropertyGroup>\n\t\t\t<ProjectGuid>{0BA6D13A-3E85-4F64-897A-C3478268B7F8}</ProjectGuid>\n\t\t\t<MainSource>ChakraCoreTestsUI.dpr</MainSource>\n\t\t\t<Config Condition=\"'$(Config)'==''\">Debug</Config>\n\t\t\t<DCC_DCCCompiler>DCC32</DCC_DCCCompiler>\n\t\t\t<ProjectVersion>12.3</ProjectVersion>\n\t\t\t<Base>True</Base>\n\t\t\t<Platform>Win32</Platform>\n\t\t\t<AppType>Console</AppType>\n\t\t\t<FrameworkType>None</FrameworkType>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Base' or '$(Base)'!=''\">\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Release' or '$(Cfg_1)'!=''\">\n\t\t\t<Cfg_1>true</Cfg_1>\n\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Config)'=='Debug' or '$(Cfg_2)'!=''\">\n\t\t\t<Cfg_2>true</Cfg_2>\n\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t<Base>true</Base>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Base)'!=''\">\n\t\t\t<DCC_DependencyCheckOutputName>..\\bin\\$(Platform)\\$(Config)\\ChakraCoreTestsUI.exe</DCC_DependencyCheckOutputName>\n\t\t\t<DCC_ExeOutput>..\\bin\\$(Platform)\\$(Config)</DCC_ExeOutput>\n\t\t\t<DCC_DcuOutput>..\\lib\\$(Platform)\\$(Config)</DCC_DcuOutput>\n\t\t\t<DCC_ImageBase>00400000</DCC_ImageBase>\n\t\t\t<DCC_UsePackage>vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP;JclDeveloperTools;Jcl;JclVcl;JclContainers</DCC_UsePackage>\n\t\t\t<DCC_UnitAlias>WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;$(DCC_UnitAlias)</DCC_UnitAlias>\n\t\t\t<DCC_Platform>x86</DCC_Platform>\n\t\t\t<DCC_UnitSearchPath>..\\src;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>\n\t\t\t<DCC_K>false</DCC_K>\n\t\t\t<DCC_N>true</DCC_N>\n\t\t\t<DCC_S>false</DCC_S>\n\t\t\t<DCC_SymbolReferenceInfo>1</DCC_SymbolReferenceInfo>\n\t\t\t<DCC_E>false</DCC_E>\n\t\t\t<DCC_F>false</DCC_F>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Cfg_1)'!=''\">\n\t\t\t<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>\n\t\t\t<DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>\n\t\t\t<DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>\n\t\t\t<DCC_DebugInformation>false</DCC_DebugInformation>\n\t\t</PropertyGroup>\n\t\t<PropertyGroup Condition=\"'$(Cfg_2)'!=''\">\n\t\t\t<DCC_Define>DEBUG;$(DCC_Define)</DCC_Define>\n\t\t</PropertyGroup>\n\t\t<ItemGroup>\n\t\t\t<DelphiCompile Include=\"ChakraCoreTestsUI.dpr\">\n\t\t\t\t<MainSource>MainSource</MainSource>\n\t\t\t</DelphiCompile>\n\t\t\t<BuildConfiguration Include=\"Debug\">\n\t\t\t\t<Key>Cfg_2</Key>\n\t\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t</BuildConfiguration>\n\t\t\t<BuildConfiguration Include=\"Base\">\n\t\t\t\t<Key>Base</Key>\n\t\t\t</BuildConfiguration>\n\t\t\t<BuildConfiguration Include=\"Release\">\n\t\t\t\t<Key>Cfg_1</Key>\n\t\t\t\t<CfgParent>Base</CfgParent>\n\t\t\t</BuildConfiguration>\n\t\t</ItemGroup>\n\t\t<Import Condition=\"Exists('$(BDS)\\Bin\\CodeGear.Delphi.Targets')\" Project=\"$(BDS)\\Bin\\CodeGear.Delphi.Targets\"/>\n\t\t<Import Condition=\"Exists('$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj')\" Project=\"$(APPDATA)\\Embarcadero\\$(BDSAPPDATABASEDIR)\\$(PRODUCTVERSION)\\UserTools.proj\"/>\n\t\t<ProjectExtensions>\n\t\t\t<Borland.Personality>Delphi.Personality.12</Borland.Personality>\n\t\t\t<Borland.ProjectType>VCLApplication</Borland.ProjectType>\n\t\t\t<BorlandProject>\n\t\t\t\t<Delphi.Personality>\n\t\t\t\t\t<Source>\n\t\t\t\t\t\t<Source Name=\"MainSource\">ChakraCoreTestsUI.dpr</Source>\n\t\t\t\t\t</Source>\n\t\t\t\t\t<Parameters/>\n\t\t\t\t\t<VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"IncludeVerInfo\">True</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"AutoIncBuild\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"MajorVer\">1</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"MinorVer\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Release\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Build\">0</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Debug\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"PreRelease\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Special\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Private\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"DLL\">False</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"Locale\">1033</VersionInfo>\n\t\t\t\t\t\t<VersionInfo Name=\"CodePage\">1252</VersionInfo>\n\t\t\t\t\t</VersionInfo>\n\t\t\t\t\t<VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"CompanyName\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"FileDescription\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"FileVersion\">1.0.0.0</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"InternalName\">ChakraCoreTestsUI</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"LegalCopyright\">© 2021 Ondrej Kelle</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"LegalTrademarks\"/>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"OriginalFilename\">ChakraCoreTestsUI</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"ProductName\">chakracore-delphi</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"ProductVersion\">1.0.0.0</VersionInfoKeys>\n\t\t\t\t\t\t<VersionInfoKeys Name=\"Comments\"/>\n\t\t\t\t\t</VersionInfoKeys>\n\t\t\t\t</Delphi.Personality>\n\t\t\t\t<Platforms>\n\t\t\t\t\t<Platform value=\"Win32\">True</Platform>\n\t\t\t\t</Platforms>\n\t\t\t</BorlandProject>\n\t\t\t<ProjectFileVersion>12</ProjectFileVersion>\n\t\t</ProjectExtensions>\n\t</Project>\n"
  },
  {
    "path": "tests/ChakraCoreTestsUI.dof",
    "content": "[FileVersion]\nVersion=7.0\n[Compiler]\nA=8\nB=0\nC=1\nD=1\nE=0\nF=0\nG=1\nH=1\nI=1\nJ=0\nK=0\nL=1\nM=0\nN=1\nO=1\nP=1\nQ=0\nR=0\nS=0\nT=0\nU=0\nV=1\nW=0\nX=1\nY=1\nZ=1\nShowHints=1\nShowWarnings=1\nUnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;\nNamespacePrefix=\nSymbolDeprecated=1\nSymbolLibrary=1\nSymbolPlatform=1\nUnitLibrary=1\nUnitPlatform=1\nUnitDeprecated=1\nHResultCompat=1\nHidingMember=1\nHiddenVirtual=1\nGarbage=1\nBoundsError=1\nZeroNilCompat=1\nStringConstTruncated=1\nForLoopVarVarPar=1\nTypedConstVarPar=1\nAsgToTypedConst=1\nCaseLabelRange=1\nForVariable=1\nConstructingAbstract=1\nComparisonFalse=1\nComparisonTrue=1\nComparingSignedUnsigned=1\nCombiningSignedUnsigned=1\nUnsupportedConstruct=1\nFileOpen=1\nFileOpenUnitSrc=1\nBadGlobalSymbol=1\nDuplicateConstructorDestructor=1\nInvalidDirective=1\nPackageNoLink=1\nPackageThreadVar=1\nImplicitImport=1\nHPPEMITIgnored=1\nNoRetVal=1\nUseBeforeDef=1\nForLoopVarUndef=1\nUnitNameMismatch=1\nNoCFGFileFound=1\nMessageDirective=1\nImplicitVariants=1\nUnicodeToLocale=1\nLocaleToUnicode=1\nImagebaseMultiple=1\nSuspiciousTypecast=1\nPrivatePropAccessor=1\nUnsafeType=0\nUnsafeCode=0\nUnsafeCast=0\n[Linker]\nMapFile=0\nOutputObjs=0\nConsoleApp=1\nDebugInfo=0\nRemoteSymbols=0\nMinStackSize=16384\nMaxStackSize=1048576\nImageBase=4194304\nExeDescription=\n[Directories]\nOutputDir=..\\bin\\Win32\\Debug\nUnitOutputDir=..\\lib\\Win32\\Debug\nPackageDLLOutputDir=\nPackageDCPOutputDir=\nSearchPath=..\\src\nPackages=vcl;rtl;vclx;indy;inet;xmlrtl;vclie;inetdbbde;inetdbxpress;dbrtl;dsnap;dsnapcon;vcldb;soaprtl;VclSmp;dbexpress;dbxcds;inetdb;bdertl;vcldbx;webdsnap;websnap;adortl;ibxpress;teeui;teedb;tee;dss;visualclx;visualdbclx;vclactnband;vclshlctrls;IntrawebDB_50_70;Intraweb_50_70;Rave50CLX;Rave50VCL;dclOfficeXP;JclDeveloperTools;Jcl;JclVcl;JclContainers\nConditionals=\nDebugSourceDirs=\nUsePackages=0\n[Parameters]\nRunParams=\nHostApplication=\nLauncher=\nUseLauncher=0\nDebugCWD=\n[Language]\nActiveLang=\nProjectLang=\nRootDir=\n[Version Info]\nIncludeVerInfo=1\nAutoIncBuild=0\nMajorVer=1\nMinorVer=0\nRelease=0\nBuild=0\nDebug=0\nPreRelease=0\nSpecial=0\nPrivate=0\nDLL=0\nLocale=1033\nCodePage=1252\n[Version Info Keys]\nCompanyName=\nFileDescription=\nFileVersion=1.0.0.0\nInternalName=ChakraCoreTestsUI\nLegalCopyright=� 2021 Ondrej Kelle\nLegalTrademarks=\nOriginalFilename=ChakraCoreTestsUI.exe\nProductName=chakracore-delphi\nProductVersion=1.0.0.0\n[HistoryLists\\hlUnitAliases]\nCount=1\nItem0=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;\n[HistoryLists\\hlSearchPath]\nCount=1\nItem0=..\\..\\src\n[HistoryLists\\hlUnitOutputDirectory]\nCount=1\nItem0=..\\..\\lib\\Win32\\Debug\n[HistoryLists\\hlOutputDirectorry]\nCount=1\nItem0=..\\..\\bin\\Win32\\Debug\n"
  },
  {
    "path": "tests/ChakraCoreTestsUI.dpr",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nprogram ChakraCoreTestsUI;\n\n{$include ..\\src\\common.inc}\n\n{$ifdef FPC}\n  {$apptype GUI}\n{$endif}\n\nuses\n  SysUtils, Classes,\n{$ifdef FPC}\n  Interfaces, Forms, Graphics, GuiTestRunner,     \n{$endif}\n{$ifdef DELPHI}\n  TestFramework, GUITestRunner,\n{$endif}\n  Compat, Test_ChakraCore, Test_Classes, ChakraCoreVersion;\n\n{$R *.res}\n\nbegin\n{$ifdef FPC}\n  Application.Initialize;\n  Application.CreateForm(TGuiTestRunner, TestRunner);\n{$ifdef WINDOWS}\n  TestRunner.XMLSynEdit.Font.Name := 'Consolas';\n{$endif}\n{$ifdef LINUX}\n  TestRunner.XMLSynEdit.Font.Name := 'Liberation Mono';\n{$endif}\n{$ifdef DARWIN}\n  TestRunner.XMLSynEdit.Font.Name := 'Menlo';\n{$endif}\n  TestRunner.XMLSynEdit.Font.Quality := fqCleartype;\n\n  TestRunner.MemoLog.Append(Format('%s %s', [ExtractFileName(ParamStr(0)), GetExeFileVersionString]));\n  TestRunner.MemoLog.Append(Format('Built with %s', [GetBuildInfoString]));\n  TestRunner.MemoLog.Append(Format('Chakra Core version: %d.%d.%d', [CHAKRA_CORE_MAJOR_VERSION, CHAKRA_CORE_MINOR_VERSION, CHAKRA_CORE_PATCH_VERSION]));\n  Application.Run;\n{$endif}\n\n{$ifdef DELPHI}\n  with TGUITestRunner.Create(nil) do\n  begin\n    try\n      ErrorMessageRTF.Lines.Add(Format('%s %s', [ExtractFileName(ParamStr(0)), GetExeFileVersionString]));\n      ErrorMessageRTF.Lines.Add(Format('Built with %s', [GetBuildInfoString]));\n      ErrorMessageRTF.Lines.Add(Format('Chakra Core version: %d.%d.%d', [CHAKRA_CORE_MAJOR_VERSION, CHAKRA_CORE_MINOR_VERSION, CHAKRA_CORE_PATCH_VERSION]));\n      Suite := registeredTests;\n      ShowModal;\n    finally\n      Free;\n    end;\n  end;\n{$endif}\nend.\n"
  },
  {
    "path": "tests/ChakraCoreTestsUI.lpi",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CONFIG>\n  <ProjectOptions>\n    <Version Value=\"11\"/>\n    <General>\n      <SessionStorage Value=\"InProjectDir\"/>\n      <MainUnit Value=\"0\"/>\n      <Title Value=\"ChakraCoreTestsUI\"/>\n      <ResourceType Value=\"res\"/>\n      <UseXPManifest Value=\"True\"/>\n    </General>\n    <VersionInfo>\n      <UseVersionInfo Value=\"True\"/>\n      <MajorVersionNr Value=\"1\"/>\n      <StringTable InternalName=\"ChakraCoreTestsUI\" LegalCopyright=\"© 2021 Ondrej Kelle\" OriginalFilename=\"ChakraCoreTestsUI\" ProductName=\"chakracore-delphi\"/>\n    </VersionInfo>\n    <BuildModes Count=\"2\">\n      <Item1 Name=\"Debug\" Default=\"True\"/>\n      <Item2 Name=\"Release\">\n        <CompilerOptions>\n          <Version Value=\"11\"/>\n          <Target>\n            <Filename Value=\"../bin/$(TargetCPU)-$(TargetOS)/$(BuildMode)/ChakraCoreTestsUI\"/>\n          </Target>\n          <SearchPaths>\n            <IncludeFiles Value=\"$(ProjOutDir)\"/>\n            <Libraries Value=\"../bin/$(TargetCPU)-$(TargetOS)/$(BuildMode)\"/>\n            <OtherUnitFiles Value=\"../src;$(LazarusDir)/components/fpcunit/lib/$(TargetCPU)-$(TargetOS)/$(LCLWidgetType);$(LazarusDir)/components/fpcunit\"/>\n            <UnitOutputDirectory Value=\"../lib/$(TargetCPU)-$(TargetOS)/$(BuildMode)\"/>\n          </SearchPaths>\n          <CodeGeneration>\n            <SmartLinkUnit Value=\"True\"/>\n            <Optimizations>\n              <OptimizationLevel Value=\"3\"/>\n            </Optimizations>\n          </CodeGeneration>\n          <Linking>\n            <Debugging>\n              <GenerateDebugInfo Value=\"False\"/>\n            </Debugging>\n            <LinkSmart Value=\"True\"/>\n            <Options>\n              <Win32>\n                <GraphicApplication Value=\"True\"/>\n              </Win32>\n            </Options>\n          </Linking>\n        </CompilerOptions>\n      </Item2>\n    </BuildModes>\n    <PublishOptions>\n      <Version Value=\"2\"/>\n    </PublishOptions>\n    <RunParams>\n      <FormatVersion Value=\"2\"/>\n      <Modes Count=\"1\">\n        <Mode0 Name=\"default\"/>\n      </Modes>\n    </RunParams>\n    <RequiredPackages Count=\"3\">\n      <Item1>\n        <PackageName Value=\"fpcunittestrunner\"/>\n      </Item1>\n      <Item2>\n        <PackageName Value=\"LCL\"/>\n      </Item2>\n      <Item3>\n        <PackageName Value=\"FCL\"/>\n      </Item3>\n    </RequiredPackages>\n    <Units Count=\"3\">\n      <Unit0>\n        <Filename Value=\"ChakraCoreTestsUI.dpr\"/>\n        <IsPartOfProject Value=\"True\"/>\n      </Unit0>\n      <Unit1>\n        <Filename Value=\"Test_ChakraCore.pas\"/>\n        <IsPartOfProject Value=\"True\"/>\n      </Unit1>\n      <Unit2>\n        <Filename Value=\"Test_Classes.pas\"/>\n        <IsPartOfProject Value=\"True\"/>\n      </Unit2>\n    </Units>\n  </ProjectOptions>\n  <CompilerOptions>\n    <Version Value=\"11\"/>\n    <Target>\n      <Filename Value=\"../bin/$(TargetCPU)-$(TargetOS)/$(BuildMode)/ChakraCoreTestsUI\"/>\n    </Target>\n    <SearchPaths>\n      <IncludeFiles Value=\"$(ProjOutDir)\"/>\n      <Libraries Value=\"../bin/$(TargetCPU)-$(TargetOS)/$(BuildMode)\"/>\n      <OtherUnitFiles Value=\"../src;$(LazarusDir)/components/fpcunit/lib/$(TargetCPU)-$(TargetOS)/$(LCLWidgetType);$(LazarusDir)/components/fpcunit\"/>\n      <UnitOutputDirectory Value=\"../lib/$(TargetCPU)-$(TargetOS)/$(BuildMode)\"/>\n    </SearchPaths>\n    <Parsing>\n      <SyntaxOptions>\n        <SyntaxMode Value=\"Delphi\"/>\n        <IncludeAssertionCode Value=\"True\"/>\n      </SyntaxOptions>\n    </Parsing>\n    <CodeGeneration>\n      <Checks>\n        <IOChecks Value=\"True\"/>\n        <OverflowChecks Value=\"True\"/>\n        <StackChecks Value=\"True\"/>\n      </Checks>\n    </CodeGeneration>\n    <Linking>\n      <Options>\n        <Win32>\n          <GraphicApplication Value=\"True\"/>\n        </Win32>\n      </Options>\n    </Linking>\n  </CompilerOptions>\n  <Debugging>\n    <Exceptions Count=\"5\">\n      <Item1>\n        <Name Value=\"EAbort\"/>\n      </Item1>\n      <Item2>\n        <Name Value=\"ECodetoolError\"/>\n      </Item2>\n      <Item3>\n        <Name Value=\"EFOpenError\"/>\n      </Item3>\n      <Item4>\n        <Name Value=\"EChakraCore\"/>\n      </Item4>\n      <Item5>\n        <Name Value=\"EChakraCoreScript\"/>\n      </Item5>\n    </Exceptions>\n  </Debugging>\n</CONFIG>\n"
  },
  {
    "path": "tests/Test_ChakraCore.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nunit Test_ChakraCore;\n\ninterface\n\n{$include ..\\src\\common.inc}\n\nuses\n  Classes, SysUtils,\n{$ifdef FPC}\n{$ifndef WINDOWS}\n  cwstring,\n{$endif}\n  fpcunit, testregistry,\n{$else}\n  TestFramework,\n{$endif}\n  Compat, ChakraCoreVersion, ChakraCommon, ChakraCore, ChakraDebug, ChakraCoreUtils;\n\ntype\n\n  { TBaseTestCase }\n\n  TBaseTestCase = class(TTestCase)\n  public\n{$ifdef DELPHI}\n    // work around Delphi 2007 and earlier compiler error \"Ambiguous overloaded call to 'CheckEquals'\"\n    procedure CheckEquals(expected, actual: Integer; msg: string = ''); override;\n    // DUnit needs a delta when comparing float values\n    procedure CheckEquals(expected, actual: extended; msg: string = ''); reintroduce; overload;\n{$endif}\n    procedure CheckEquals(expected, actual: JsValueType; const msg: string = ''); overload;\n    procedure CheckEquals(expected, actual: JsTypedArrayType; const msg: string = ''); overload;\n    procedure CheckValueType(expected: JsValueType; value: JsValueRef; const msg: string = '');\n  end;\n\n  TChakraCoreTestCase = class(TBaseTestCase)\n  private\n    FContext: JsContextRef;\n    FRuntime: JsRuntimeHandle;\n  protected\n    procedure SetUp; override;\n    procedure TearDown; override;\n  end;\n\n  TChakraCoreUtilsScripting = class(TChakraCoreTestCase)\n  published\n    procedure TestVersion;\n    procedure TestUndefined;\n    procedure TestNull;\n    procedure TestInt;\n    procedure TestDouble;\n    procedure TestInfinity;\n    procedure TestNaN;\n    procedure TestString;\n    procedure TestStringUnicode;\n    procedure TestBoolean;\n    procedure TestObject;\n    procedure TestFunction;\n    procedure TestError;\n    procedure TestArray;\n    procedure TestSymbol;\n    procedure TestArrayBuffer;\n    procedure TestTypedArray;\n    procedure TestDataView;\n    procedure TestThrowBoolean;\n    procedure TestThrowInt;\n    procedure TestThrowString;\n    procedure TestThrowObject;\n    procedure TestThrowError;\n    procedure TestThrowHostError;\n    procedure TestCallFunction01;\n    procedure TestCallFunction02;\n    procedure TestCallFunction03;\n    procedure TestCallFunctions;\n    procedure TestCallNew;\n    procedure TestFPExceptions;\n    procedure TestDebugging;\n  end;\n\n  { TChakraCorePrototypes }\n\n  TChakraCorePrototypes = class(TChakraCoreTestCase)\n  published\n    procedure TestInheritance;\n  end;\n\nimplementation\n\nuses\n{$ifdef HAS_WIDESTRUTILS}\n  WideStrUtils,\n{$endif}\n  Math;\n\n{$ifdef DELPHI}\nprocedure TBaseTestCase.CheckEquals(expected, actual: Integer; msg: string);\nbegin\n  inherited CheckEquals(expected, actual, msg);\nend;\n\nprocedure TBaseTestCase.CheckEquals(expected, actual: extended; msg: string);\nconst\n  DefaultDelta = 0.0000001;\nbegin\n  inherited CheckEquals(expected, actual, DefaultDelta, msg);\nend;\n{$endif}\n\nprocedure TBaseTestCase.CheckEquals(expected, actual: JsValueType; const msg: string);\nbegin\n  inherited CheckEquals(Ord(expected), Ord(actual), msg);\nend;\n\nprocedure TBaseTestCase.CheckEquals(expected, actual: JsTypedArrayType; const msg: string);\nbegin\n  inherited CheckEquals(Ord(expected), Ord(actual), msg);\nend;\n\nprocedure TBaseTestCase.CheckValueType(expected: JsValueType; value: JsValueRef; const msg: string);\nbegin\n  CheckEquals(expected, JsGetValueType(Value), msg);\nend;\n\nprocedure TChakraCoreTestCase.SetUp;\nbegin\n  FRuntime := nil;\n  FContext := nil;\n\n  ChakraCoreCheck(JsCreateRuntime(JsRuntimeAttributeNone, nil, FRuntime));\n  ChakraCoreCheck(JsCreateContext(FRuntime, FContext));\n  ChakraCoreCheck(JsSetCurrentContext(FContext));\nend;\n\nprocedure TChakraCoreTestCase.TearDown;\nbegin\n  ChakraCoreCheck(JsSetCurrentContext(JS_INVALID_REFERENCE));\n  if Assigned(FRuntime) then\n    ChakraCoreCheck(JsDisposeRuntime(FRuntime));\nend;\n\nprocedure TChakraCoreUtilsScripting.TestVersion;\nbegin\n  CheckEquals(Integer(1), CHAKRA_CORE_MAJOR_VERSION, 'major version number');\n  CheckEquals(Integer(11), CHAKRA_CORE_MINOR_VERSION, 'minor version number');\n  CheckEquals(Integer(24), CHAKRA_CORE_PATCH_VERSION, 'patch version number');\nend;\n\nprocedure TChakraCoreUtilsScripting.TestUndefined;\nconst\n  SScript = 'this.result = undefined';\n  SName = 'TestUndefined.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    CheckValueType(JsUndefined, Result, 'result type');\n    Check(JsEqual(JsUndefinedValue, Result, True), 'result type');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestNull;\nconst\n  SScript = 'this.result = null';\n  SName = 'TestNull.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    CheckValueType(JsNull, Result, 'result type');\n    Check(JsEqual(JsNullValue, Result, True), 'result type');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestInt;\nconst\n  IntValue = 42;\n  SScript = 'this.result = %d';\n  SName = 'TestInt.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(Format(SScript, [IntValue])), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(Format(SScript, [IntValue])), UTF8String(SName));\n\n    CheckValueType(JsNumber, Result, 'result type');\n    CheckEquals(IntValue, JsNumberToInt(Result), 'result value');\n    Check(JsEqual(IntToJsNumber(IntValue), Result, True), 'result value');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestDouble;\nconst\n  DoubleValue: Double = 3.14;\n  SScript = 'this.result = %f';\n  SName = 'TestDouble.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False To True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(Format(SScript, [DoubleValue], DefaultFormatSettings)), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(Format(SScript, [DoubleValue], DefaultFormatSettings)), UTF8String(SName));\n\n    CheckValueType(JsNumber, Result, 'result type');\n    CheckEquals(DoubleValue, JsNumberToDouble(Result), 'result value');\n    Check(JsEqual(DoubleToJsNumber(DoubleValue), Result, True), 'result value');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestInfinity;\nconst\n  SScript = 'this.result = Infinity';\n  SName = 'TestInfinity.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    CheckValueType(JsNumber, Result, 'result type');\n    Check(IsInfinite(JsNumberToDouble(Result)), 'INF');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestNaN;\nconst\n  SScript = 'this.result = NaN';\n  SName = 'TestNaN.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    CheckValueType(JsNumber, Result, 'result type');\n    Check(IsNan(JsNumberToDouble(Result)), 'NaN');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestString;\nconst\n  StringValues: array[0..1] of UnicodeString = ('', 'Hello, world!');\n  SScript = 'this.result = \"%s\"';\n  SName = 'TestString.js';\nvar\n  Unicode: Boolean;\n  I: Integer;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n    for I := Low(StringValues) to High(StringValues) do\n    begin\n      if Unicode then\n        Result := JsRunScript(UnicodeString(Format(SScript, [StringValues[I]])), UnicodeString(SName))\n      else\n        Result := JsRunScript(UTF8String(Format(SScript, [StringValues[I]])), UTF8String(SName));\n\n      CheckValueType(JsString, Result, 'result type');\n      CheckEquals(StringValues[I], JsStringToUnicodeString(Result), 'result value');\n      Check(JsEqual(StringToJsString(StringValues[I]), Result, True), 'result value');\n    end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestStringUnicode;\nconst\n  StringValues: array [0..1] of UTF8String = ('', #$E4#$BD#$A0#$E5#$A5#$BD);\n  SScript = 'this.result = \"%s\"';\n  SName = 'TestString.js';\nvar\n  Unicode: Boolean;\n  I: Integer;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n    for I := Low(StringValues) to High(StringValues) do\n    begin\n      if Unicode then\n        Result := JsRunScript(WideFormat(SScript, [UTF8ToString(StringValues[I])]), UnicodeString(SName))\n      else\n        Result := JsRunScript(Format(SScript, [UTF8String(StringValues[I])]), UTF8String(SName));\n\n      CheckValueType(JsString, Result, 'result type');\n{$ifdef SUPPORTS_UNICODE}\n      CheckEquals(UTF8ToString(StringValues[I]), JsStringToUnicodeString(Result), 'result value');\n{$else}\n      CheckEquals(UTF8String(StringValues[I]), JsStringToUTF8String(Result), 'result value');\n{$endif}\n      Check(JsEqual(StringToJsString(StringValues[I]), Result, True), 'result value');\n    end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestBoolean;\nconst\n  SScripts: array[Boolean] of string = (\n    'this.result = false',\n    'this.result = true'\n  );\n  SName = 'TestBoolean.js';\nvar\n  Unicode, BooleanValue: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    for BooleanValue := False to True do\n    begin\n      if Unicode then\n        Result := JsRunScript(UnicodeString(SScripts[BooleanValue]), UnicodeString(SName))\n      else\n        Result := JsRunScript(UTF8String(SScripts[BooleanValue]), UTF8String(SName));\n\n      CheckValueType(JsBoolean, Result, 'result type');\n      CheckEquals(BooleanValue, JsBooleanToBoolean(Result), 'result value');\n      Check(JsEqual(BooleanToJsBoolean(BooleanValue), Result, True), 'result value');\n    end;\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestObject;\nconst\n  SScript = 'this.result = this';\n  SName = 'TestObject.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    CheckValueType(JsObject, Result, 'result type');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestFunction;\nconst\n  SScript = 'this.result = function() { return 42; }';\n  SName = 'TestFunction.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    CheckValueType(JsFunction, Result, 'result type');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestError;\nconst\n  SScript = 'this.result = new Error(\"Test Error\")';\n  SName = 'TestError.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    CheckValueType(JsError, Result, 'result type');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestArray;\nconst\n  IntElementValue = 42;\n  DoubleElementValue = 3.14;\n  StringElementValue: UnicodeString = 'Hello, world!';\n  SScript = 'this.result = [undefined, null, %d, %f, \"%s\", true, false, this, function() { return 42; }, new Error(\"Test Error\")]';\n  SName = 'TestArray.js';\nvar\n  Unicode: Boolean;\n  Result, Element: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(Format(SScript, [IntElementValue, DoubleElementValue, StringElementValue],\n        DefaultFormatSettings)), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(Format(SScript, [IntElementValue, DoubleElementValue, StringElementValue],\n        DefaultFormatSettings)), UTF8String(SName));\n\n    CheckValueType(JsArray, Result, 'result type');\n\n    ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(0), Element));\n    CheckValueType(JsUndefined, Element, 'element 0 type');\n\n    ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(1), Element));\n    CheckValueType(JsNull, Element, 'element 1 type');\n\n    ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(2), Element));\n    CheckValueType(JsNumber, Element, 'element 2 type');\n    CheckEquals(IntElementValue, JsNumberToInt(Element), 'element 2 value');\n    Check(JsEqual(IntToJsNumber(IntElementValue), Element, True), 'element 2 value');\n\n    ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(3), Element));\n    CheckValueType(JsNumber, Element, 'element 3 type');\n    CheckEquals(DoubleElementValue, JsNumberToDouble(Element), 'element 3 value');\n    Check(JsEqual(DoubleToJsNumber(DoubleElementValue), Element, True), 'element 3 value');\n\n    ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(4), Element));\n    CheckValueType(JsString, Element, 'element 4 type');\n    CheckEquals(StringElementValue, JsStringToUnicodeString(Element), 'element 4 value');\n    Check(JsEqual(StringToJsString(StringElementValue), Element, True), 'element 4 value');\n\n    ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(5), Element));\n    CheckValueType(JsBoolean, Element, 'element 5 type');\n    CheckEquals(True, JsBooleanToBoolean(Element), 'element 5 value');\n    Check(JsEqual(BooleanToJsBoolean(True), Element, True), 'element 5 value');\n\n    ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(6), Element));\n    CheckValueType(JsBoolean, Element, 'element 6 type');\n    CheckEquals(False, JsBooleanToBoolean(Element), 'element 6 value');\n    Check(JsEqual(BooleanToJsBoolean(False), Element, True), 'element 6 value');\n\n    ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(7), Element));\n    CheckValueType(JsObject, Element, 'element 7 type');\n\n    ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(8), Element));\n    CheckValueType(JsFunction, Element, 'element 8 type');\n\n    ChakraCoreCheck(JsGetIndexedProperty(Result, IntToJsNumber(9), Element));\n    CheckValueType(JsError, Element, 'element 9 type');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestSymbol;\nconst\n  SScript = 'this.result = Symbol(''foo'')';\n  SName = 'TestSymbol.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    CheckValueType(JsSymbol, Result, 'result type');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestArrayBuffer;\nconst\n  SScript = 'this.result = new ArrayBuffer(1024)';\n  SName = 'TestArrayBuffer.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    CheckValueType(JsArrayBuffer, Result, 'result type');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestTypedArray;\nconst\n  SScripts: array[JsTypedArrayType] of string = (\n    'this.result = new Int8Array(16)',\n    'this.result = new Uint8Array(16)',\n    'this.result = new Uint8ClampedArray(16)',\n    'this.result = new Int16Array(16)',\n    'this.result = new Uint16Array(16)',\n    'this.result = new Int32Array(16)',\n    'this.result = new Uint32Array(16)',\n    'this.result = new Float32Array(16)',\n    'this.result = new Float64Array(16)'\n  );\n  SName = 'TesTypedtArray.js';\nvar\n  Unicode: Boolean;\n  I: JsTypedArrayType;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    for I := Low(JsTypedArraytype) to High(JsTypedArraytype) do\n    begin\n      if Unicode then\n        Result := JsRunScript(UnicodeString(SScripts[I]), UnicodeString(SName))\n      else\n        Result := JsRunScript(UTF8String(SScripts[I]), UTF8String(SName));\n\n      CheckValueType(JsTypedArray, Result, 'result type');\n      CheckEquals(I, JsGetTypedArrayType(Result), 'element type');\n    end;\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestDataView;\nconst\n  SScript = 'this.result = new DataView(new ArrayBuffer(1024), 0, 1024)';\n  SName = 'TestArrayBuffer.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    CheckValueType(JsDataView, Result, 'result type');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestThrowBoolean;\nconst\n  SScript = 'throw true;';\n  SName = 'TestThrowBoolean.js';\nvar\n  Unicode: Boolean;\nbegin\n  for Unicode := False to True do\n  begin\n    try\n      if Unicode then\n        JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n      else\n        JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n      Check(False, 'Expected error');\n    except\n      on E: EChakraCore do\n      begin\n        CheckValueType(JsBoolean, E.Error, 'error type');\n        CheckEquals(True, JsBooleanToBoolean(E.Error), 'error value');\n      end;\n    end;\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestThrowInt;\nconst\n  IntValue = 42;\n  SScript = 'throw %d;';\n  SName = 'TestThrowInt.js';\nvar\n  Unicode: Boolean;\nbegin\n  for Unicode := False to True do\n  begin\n    try\n      if Unicode then\n        JsRunScript(UnicodeString(Format(SScript, [IntValue])), UnicodeString(SName))\n      else\n        JsRunScript(UTF8String(Format(SScript, [IntValue])), UTF8String(SName));\n\n      Check(False, 'Expected error');\n    except\n      on E: EChakraCore do\n      begin\n        CheckValuetype(JsNumber, E.Error, 'error type');\n        CheckEquals(IntValue, JsNumberToInt(E.Error), 'error value');\n      end;\n    end;\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestThrowString;\nconst\n  StringValue: UnicodeString = 'Error';\n  SScript = 'throw \"%s\";';\n  SName = 'TestThrowString.js';\nvar\n  Unicode: Boolean;\nbegin\n  for Unicode := False to True do\n  begin\n    try\n      if Unicode then\n        JsRunScript(UnicodeString(Format(SScript, [StringValue])), UnicodeString(SName))\n      else\n        JsRunScript(UTF8String(Format(SScript, [StringValue])), UTF8String(SName));\n\n      Check(False, 'Expected error');\n    except\n      on E: EChakraCore do\n      begin\n        CheckValueType(JsString, E.Error, 'error type');\n        CheckEquals(StringValue, JsStringToUnicodeString(E.Error));\n      end;\n    end;\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestThrowObject;\nconst\n  SScript = 'throw this;';\n  SName = 'TestThrowObject.js';\nvar\n  Unicode: Boolean;\nbegin\n  for Unicode := False to True do\n  begin\n    try\n      if Unicode then\n        JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n      else\n        JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n      Check(False, 'Expected error');\n    except\n      on E: EChakraCore do\n      begin\n        CheckValueType(JsObject, E.Error, 'error type');\n      end;\n    end;\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestThrowError;\nconst\n  SScript = 'syntax error?';\n  SName = 'TestThrowError.js';\nvar\n  Unicode: Boolean;\n  Name, Message: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    try\n      if Unicode then\n        JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n      else\n        JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n      Check(False, 'Expected error');\n    except\n      on E: EChakraCore do\n      begin\n        CheckValueType(JsError, E.Error, 'error type');\n\n        Name := JsGetProperty(E.Error, 'name');\n        Message := JsGetProperty(E.Error, 'message');\n\n        CheckEquals(UnicodeString('SyntaxError'), JsStringToUnicodeString(Name));\n        CheckEquals(UnicodeString('Expected '';'''), JsStringToUnicodeString(Message));\n      end;\n    end;\n  end;\nend;\n\nconst\n  ErrorTypeNames: array[TErrorType] of UnicodeString = ('Error', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError');\n\ntype\n  PErrorType = ^TErrorType;\n\nfunction TestErrorCallback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRef; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nvar\n  ErrorType: PErrorType absolute CallbackState;\nbegin\n  ChakraCoreCheck(JsGetUndefinedValue(Result));\n  JsThrowError(Format('Test %s error', [ErrorTypeNames[ErrorType^]]), ErrorType^);\nend;\n\nprocedure TChakraCoreUtilsScripting.TestThrowHostError;\nconst\n  SScript = 'this.testerror();';\n  SName = 'TestThrowHostError.js';\nvar\n  Global: JsValueRef;\n  Unicode: Boolean;\n  EType: TErrorType;\n  Name, Message: JsValueRef;\nbegin\n  ChakraCoreCheck(JsGetGlobalObject(Global));\n  JsSetCallback(Global, 'testerror', @TestErrorCallback, @EType);\n  for Unicode := False to True do\n  begin\n    for EType := Low(TErrorType) to High(TErrorType) do\n    begin\n      try\n        if Unicode then\n          JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n        else\n          JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n        Check(False, 'Expected error');\n      except\n        on E: EChakraCore do\n        begin\n          CheckValueType(JsError, E.Error, 'error type');\n\n          Name := JsGetProperty(E.Error, 'name');\n          Message := JsGetProperty(E.Error, 'message');\n\n          CheckEquals(ErrorTypeNames[EType], JsStringToUnicodeString(Name));\n          CheckEquals(WideFormat('Test %s error', [ErrorTypeNames[EType]]), JsStringToUnicodeString(Message));\n        end;\n      end;\n    end;\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestCallFunction01;\nconst\n  SScript = 'function square(number) { return number * number; }';\n  SName = 'TestCallFunction01.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\n  Global, SquareFunc: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    ChakraCoreCheck(JsGetGlobalObject(Global));\n    SquareFunc := JsGetProperty(Global, 'square');\n    Result := JsCallFunction(SquareFunc, [IntToJsNumber(3)]);\n\n    CheckValueType(JsNumber, Result, 'result type');\n    CheckEquals(9, JsNumberToInt(Result), 'result value');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestCallFunction02;\nconst\n  SScript = 'function square(number) { return number * number; }';\n  SName = 'TestCallFunction02.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    Result := JsCallFunction('square', [IntToJsNumber(3)]);\n\n    CheckValueType(JsNumber, Result, 'result type');\n    CheckEquals(9, JsNumberToInt(Result), 'result value');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestCallFunction03;\nconst\n  SScript = 'var obj = {}; obj.square = function square(number) { return number * number; }';\n  SName = 'TestCallFunction02.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    Result := JsCallFunction('square', [IntToJsNumber(3)], JsGetProperty(JsGlobal, UnicodeString('obj')));\n\n    CheckValueType(JsNumber, Result, 'result type');\n    CheckEquals(9, JsNumberToInt(Result), 'result value');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestCallFunctions;\nconst\n  SScript1 = 'function square(number) { return number * number; }';\n  SScript2 = 'function fact(number) { if (number == 0) { return 1; } else { return number * fact(number - 1); } }';\n  SName = 'TestCallFunctions.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n    begin\n      Result := JsRunScript(UnicodeString(SScript1), UnicodeString(SName));\n      CheckValueType(JsUndefined, Result, 'result type');\n      Result := JsRunScript(UnicodeString(SScript2), UnicodeString(SName));\n      CheckValueType(JsUndefined, Result, 'result type');\n    end\n    else\n    begin\n      Result := JsRunScript(UTF8String(SScript1), UTF8String(SName));\n      CheckValueType(JsUndefined, Result, 'result type');\n      Result := JsRunScript(UTF8String(SScript2), UTF8String(SName));\n      CheckValueType(JsUndefined, Result, 'result type');\n    end;\n\n    Result := JsCallFunction('square', [IntToJsNumber(3)]);\n\n    CheckValuetype(JsNumber, Result, 'result type');\n    CheckEquals(9, JsNumberToInt(Result), 'result value');\n\n    Result := JsCallFunction('fact', [IntToJsNumber(5)]);\n\n    CheckValueType(JsNumber, Result, 'result type');\n    CheckEquals(120, JsNumberToInt(Result), 'result value');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestCallNew;\nconst\n  SScript = 'this.result = new Object()';\n  SName = 'TestCallNew.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    CheckValueType(JsObject, Result, 'result type');\n    Check(JsInstanceOf(Result, 'Object'), 'instanceof Object');\n  end;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestFPExceptions;\nconst\n  SScript = 'var d = new Date(); this.Result = d.getTime();';\n  SName = 'TestFPExceptions.js';\nvar\n  Unicode: Boolean;\n  Result: JsValueRef;\nbegin\n  for Unicode := False to True do\n  begin\n    if Unicode then\n      Result := JsRunScript(UnicodeString(SScript), UnicodeString(SName))\n    else\n      Result := JsRunScript(UTF8String(SScript), UTF8String(SName));\n\n    CheckValueType(JsNumber, Result, 'result type');\n  end;\nend;\n\nfunction DebugCallback(debugEvent: JsDiagDebugEvent; eventData: JsValueRef; callbackState: Pointer): JsErrorCode;\n  {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := JsNoError;\nend;\n\nprocedure TChakraCoreUtilsScripting.TestDebugging;\nvar\n  Dummy: Pointer;\nbegin\n  Check(not JsIsDebugging, 'is debugging');\n  ChakraCoreCheck(JsDiagStartDebugging(FRuntime, DebugCallback, nil));\n  try\n    Check(JsIsDebugging, 'is debugging');\n  finally\n    ChakraCoreCheck(JsDiagStopDebugging(FRuntime, @Dummy));\n  end;\n  Check(not JsIsDebugging, 'is debugging');\nend;\n\n{ TChakraCorePrototypes }\n\nvar\n  RectangleConstructor: JsValueRef = nil;\n  RectanglePrototype: JsValueref = nil;\n\nfunction Rectangle_ConstructorCallback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRef; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nvar\n  TestCase: TChakraCorePrototypes absolute CallbackState;\n  ArgsArray: PJsValueRefArray absolute Args;\n  ShapeCtr: JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n\n  try\n    TestCase.CheckValueType(JsFunction, Callee, 'Rectangle constructor value type');\n    TestCase.CheckEquals(5, Integer(ArgCount), 'Rectangle constructor argument count');\n    ShapeCtr := JsGetProperty(JsGlobal, 'Shape');\n\n    if IsConstructCall then\n      ChakraCoreCheck(JsCreateExternalObjectWithPrototype(CallbackState, nil, RectanglePrototype, Result))\n    else\n      Result := ArgsArray^[0];\n\n    // Shape.call(x, y);\n    JsCallFunction(ShapeCtr, [ArgsArray^[1], ArgsArray^[2]], Result);\n\n    // this.w = w;\n    JsSetProperty(Result, UnicodeString('w'), ArgsArray^[3]);\n    // this.h = h;\n    JsSetProperty(Result, UnicodeString('h'), ArgsArray^[4]);\n  except on E: Exception do\n    JsThrowError(Format('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nfunction Global_GetRectangleCallback(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRef; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nvar\n  ShapeCtr, ShapePrototype: JsValueRef;\nbegin\n  Result := JsUndefinedValue;\n  try\n    if not Assigned(RectangleConstructor) then\n    begin\n      ChakraCoreCheck(JsCreateNamedFunction(StringToJsString('Rectangle'), Rectangle_ConstructorCallback, CallbackState,\n        RectangleConstructor));\n    end;\n\n    if not Assigned(RectanglePrototype) then\n    begin\n      ShapeCtr := JsGetProperty(JsGlobal, 'Shape');\n      ShapePrototype := JsGetProperty(ShapeCtr, 'prototype');\n      // Rectangle.prototype = Object.create(Shape.prototype);\n      RectanglePrototype := JsCreateObject(ShapePrototype);\n      JsSetProperty(RectangleConstructor, 'prototype', RectanglePrototype);\n\n      // Rectangle.prototype.constructor = Rectangle;\n      JsSetProperty(RectanglePrototype, 'constructor', RectangleConstructor);\n    end;\n\n    Result := RectangleConstructor;\n  except\n    on E: Exception do\n      JsThrowError(Format('[%s] %s', [E.ClassName, E.Message]));\n  end;\nend;\n\nprocedure TChakraCorePrototypes.TestInheritance;\n// - Shape (x, y) => Object\n//   - Circle (x, y, r) => Shape (x, y)\n//   - Rectangle (x, y, w, h) => Shape (x, y)\n//     - Square (x, y, w) => Rectangle (x, y, w, w)\nconst\n  SScript =\n    // Shape: (Javascript) superclass\n    'function Shape(x, y) {'                                     + sLineBreak +\n    '  this.x = x;'                                              + sLineBreak +\n    '  this.y = y;'                                              + sLineBreak +\n    '}'                                                          + sLineBreak +\n                                                                   sLineBreak +\n    'Shape.prototype.move = function(x, y) {'                    + sLineBreak +\n    '  this.x += x;'                                             + sLineBreak +\n    '  this.y += y;'                                             + sLineBreak +\n    '};'                                                         + sLineBreak +\n                                                                   sLineBreak +\n    // Circle: (Javascript) subclass of (Javascript) Shape\n    'function Circle(x, y, r) {'                                 + sLineBreak +\n    '  Shape.call(this, x, y);'                                  + sLineBreak +\n    '  this.r = r;'                                              + sLineBreak +\n    '}'                                                          + sLineBreak +\n                                                                   sLineBreak +\n    'Circle.prototype = Object.create(Shape.prototype);'         + sLineBreak +\n    'Circle.prototype.constructor = Circle;'                     + sLineBreak +\n                                                                   sLineBreak +\n    // Square: (Javascript) subclass of (native) Rectangle\n    'function Square(x, y, w) {'                                 + sLineBreak +\n    '  Rectangle.call(this, x, y, w, w);'                        + sLineBreak +\n    '}'                                                          + sLineBreak +\n                                                                   sLineBreak +\n    'Square.prototype = Object.create(Rectangle.prototype);'     + sLineBreak +\n    'Square.prototype.constructor = Square;';\n  SName = 'TestInheritance.js';\nvar\n  ShapeObj, CircleObj, RectangleObj, SquareObj: JsValueRef;\nbegin\n  RectangleConstructor := nil;\n  RectanglePrototype := nil;\n  try\n    JsDefineProperty('Rectangle', True, True, JsCreateFunction(Global_GetRectangleCallback, Self, UnicodeString('')),\n      nil, JsGlobal);\n\n    JsRunScript(SScript, SName);\n\n    // var shapeObj = new Shape(10, 10);\n    ShapeObj := JsNew('Shape', [IntToJsNumber(10), IntToJsNumber(10)]);\n    CheckValueType(JsObject, ShapeObj, 'shapeObj value type');\n    CheckTrue(JsInstanceOf(ShapeObj, 'Shape'), 'shapeObj instanceof Shape');\n    CheckFalse(JsInstanceOf(ShapeObj, 'Circle'), 'shapeObj instanceof Circle');\n    CheckFalse(JsInstanceOf(ShapeObj, 'Rectangle'), 'shapeObj instanceof Rectangle');\n    CheckFalse(JsInstanceOf(ShapeObj, 'Square'), 'shapeObj instanceof Square');\n\n    CheckEquals(10, JsNumberToInt(JsGetProperty(ShapeObj, 'x')), 'shapeObj.x before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(ShapeObj, 'y')), 'shapeObj.y before move');\n    JsCallFunction('move', [IntToJsNumber(10), IntToJsNumber(10)], ShapeObj);\n    CheckEquals(20, JsNumberToInt(JsGetProperty(ShapeObj, 'x')), 'shapeObj.x after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(ShapeObj, 'y')), 'shapeObj.y after move');\n\n    // var circleObj = new Circle(10, 10, 10);\n    CircleObj := JsNew('Circle', [IntToJsNumber(10), IntToJsNumber(10), IntToJsNumber(10)]);\n    CheckValueType(JsObject, CircleObj, 'circleObj value type');\n    CheckTrue(JsInstanceOf(CircleObj, 'Shape'), 'circleObj instanceof Shape');\n    CheckTrue(JsInstanceOf(CircleObj, 'Circle'), 'circleObj instanceof Circle');\n    CheckFalse(JsInstanceOf(CircleObj, 'Rectangle'), 'circleObj instanceof Rectangle');\n    CheckFalse(JsInstanceOf(CircleObj, 'Square'), 'circleObj instanceof Square');\n\n    CheckEquals(10, JsNumberToInt(JsGetProperty(CircleObj, 'x')), 'circleObj.x before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(CircleObj, 'y')), 'circleObj.y before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(CircleObj, 'r')), 'circleObj.r before move');\n    JsCallFunction('move', [IntToJsNumber(10), IntToJsNumber(10)], CircleObj);\n    CheckEquals(20, JsNumberToInt(JsGetProperty(CircleObj, 'x')), 'circleObj.x after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(CircleObj, 'y')), 'circleObj.y after move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(CircleObj, 'r')), 'circleObj.r after move');\n\n    // var rectangleObj = new Rectangle(10, 10, 60, 40);\n    RectangleObj := JsNew('Rectangle', [IntToJsNumber(10), IntToJsNumber(10), IntToJsNumber(60), IntToJsNumber(40)]);\n    CheckValueType(JsObject, RectangleObj, 'rectangleObj value type');\n    CheckTrue(JsInstanceOf(RectangleObj, 'Shape'), 'rectangleObj instanceof Shape');\n    CheckFalse(JsInstanceOf(RectangleObj, 'Circle'), 'rectangleObj instanceof Circle');\n    CheckTrue(JsInstanceOf(RectangleObj, 'Rectangle'), 'rectangleObj instanceof Rectangle');\n    CheckFalse(JsInstanceOf(RectangleObj, 'Square'), 'rectangleObj instanceof Square');\n\n    CheckEquals(10, JsNumberToInt(JsGetProperty(RectangleObj, 'x')), 'rectangleObj.x before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(RectangleObj, 'y')), 'rectangleObj.y before move');\n    CheckEquals(60, JsNumberToInt(JsGetProperty(RectangleObj, 'w')), 'rectangleObj.w before move');\n    CheckEquals(40, JsNumberToInt(JsGetProperty(RectangleObj, 'h')), 'rectangleObj.h before move');\n    JsCallFunction('move', [IntToJsNumber(10), IntToJsNumber(10)], RectangleObj);\n    CheckEquals(20, JsNumberToInt(JsGetProperty(RectangleObj, 'x')), 'rectangleObj.x after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(RectangleObj, 'y')), 'rectangleObj.y after move');\n    CheckEquals(60, JsNumberToInt(JsGetProperty(RectangleObj, 'w')), 'rectangleObj.w after move');\n    CheckEquals(40, JsNumberToInt(JsGetProperty(RectangleObj, 'h')), 'rectangleObj.h after move');\n\n    // var squareObj = new Square(10, 10, 20);\n    SquareObj := JsNew('Square', [IntToJsNumber(10), IntToJsNumber(10), IntToJsNumber(20)]);\n    CheckValueType(JsObject, SquareObj, 'squareObj value type');\n    CheckTrue(JsInstanceOf(SquareObj, 'Shape'), 'squareObj instanceof Shape');\n    CheckFalse(JsInstanceOf(SquareObj, 'Circle'), 'squareObj instanceof Circle');\n    CheckTrue(JsInstanceOf(SquareObj, 'Rectangle'), 'squareObj instanceof Rectangle');\n    CheckTrue(JsInstanceOf(SquareObj, 'Square'), 'squareObj instanceof Square');\n\n    CheckEquals(10, JsNumberToInt(JsGetProperty(SquareObj, 'x')), 'squareObj.x before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(SquareObj, 'y')), 'sqaureObj.y before move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'w')), 'squareObj.w before move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'h')), 'squareObj.h before move');\n    JsCallFunction('move', [IntToJsNumber(10), IntToJsNumber(10)], SquareObj);\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'x')), 'squareObj.x after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'y')), 'squareObj.y after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'w')), 'squareObj.w after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'h')), 'squareObj.h after move');\n  finally\n    RectanglePrototype := nil;\n    RectangleConstructor := nil;\n  end;\nend;\n\ninitialization\n{$ifdef FPC}\n  RegisterTests([TChakraCoreUtilsScripting, TChakraCorePrototypes]);\n{$else}\n  RegisterTests([TChakraCoreUtilsScripting.Suite, TChakraCorePrototypes.Suite]);\n{$endif}\n\nend.\n"
  },
  {
    "path": "tests/Test_Classes.pas",
    "content": "(*\n\nMIT License\n\nCopyright (c) 2021 Ondrej Kelle\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*)\n\nunit Test_Classes;\n\ninterface\n\n{$include ..\\src\\common.inc}\n\nuses\n  Classes, SysUtils,\n{$ifdef FPC}\n{$ifndef WINDOWS}\n  cwstring,\n{$endif}\n  fpcunit, testregistry,\n{$else}\n  TestFramework,\n{$endif}\n  Compat, ChakraCommon, ChakraCore, ChakraCoreUtils, ChakraCoreClasses,\n  Test_ChakraCore;\n\ntype\n\n  { TChakraCoreContextTestCase }\n\n  TChakraCoreContextTestCase = class(TBaseTestCase)\n  published\n    procedure TestScriptReferenceError;\n    procedure TestScriptSyntaxError;\n    procedure TestEvalReferenceError;\n    procedure TestEvalSyntaxError;\n  end;\n\n  { TNativeClassTestCase }\n\n  TNativeClassTestCase = class(TBaseTestCase)\n  published\n    procedure TestMethod1AsScript;\n    procedure TestMethod1AsFunction;\n    procedure TestNamedProperty;\n    procedure TestProjectedClass;\n    procedure TestClassProjectedTwice;\n    procedure TestClassProjectedInMultipleContexts;\n    procedure TestInheritance;\n    procedure TestInheritance2;\n    procedure TestFinalizer;\n    procedure TestFinalizer2;\n    procedure TestFinalizer3;\n    procedure TestFinalizer4;\n  end;\n\nimplementation\n\n{ TChakraCoreContextTestCase }\n\nprocedure TChakraCoreContextTestCase.TestScriptReferenceError;\nconst\n  SScript = 'badref.bla();';\n  SName = 'TestScriptReferenceError.js';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\nbegin\n  Runtime := nil;\n  Context := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    try\n      Context.RunScript(SScript, SName);\n    except\n      on E: EChakraCoreScript do\n      begin\n        CheckEquals(0, E.Line, 'EChakraCoreScript.Line');\n        CheckEquals(0, E.Column, 'EChakraCoreScript.Column');\n        CheckEquals(UnicodeString(SScript), E.Source, 'EChakraCoreScript.Source');\n        CheckEquals(UnicodeString(SName), E.ScriptURL, 'EChakraCoreScript.ScriptURL');\n        CheckEquals(LoadResString(JsGetErrorMessage(JsErrorScriptException)) + sLineBreak +\n          'ReferenceError: ''badref'' is not defined', E.Message, 'EChakraCoreScript.Message');\n      end;\n    end;\n  finally\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\nprocedure TChakraCoreContextTestCase.TestScriptSyntaxError;\nconst\n  SScript: array[0..1] of UnicodeString = (\n    '// first line comment',\n    '   @ bad syntax'\n  );\n  SName = 'TestScriptSyntaxError.js';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\nbegin\n  Runtime := nil;\n  Context := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    try\n      Context.RunScript(SScript[0] + UnicodeString(sLineBreak) + SScript[1], UnicodeString(SName));\n    except\n      on E: EChakraCoreScript do\n      begin\n        CheckEquals(1, E.Line, 'EChakraCoreScript.Line');\n        CheckEquals(3, E.Column, 'EChakraCoreScript.Column');\n        CheckEquals(SScript[1], E.Source, 'EChakraCoreScript.Source');\n        CheckEquals(UnicodeString(SName), E.ScriptURL, 'EChakraCoreScript.ScriptURL');\n        CheckEquals(LoadResString(JsGetErrorMessage(JsErrorScriptCompile)) + sLineBreak +\n          'SyntaxError: Invalid character', E.Message, 'EChakraCoreScript.Message');\n      end;\n    end;\n  finally\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\nprocedure TChakraCoreContextTestCase.TestEvalReferenceError;\nconst\n  SScript = 'badref.bla();';\n  SName = 'TestEvalReferenceError.js';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\nbegin\n  Runtime := nil;\n  Context := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    try\n      Context.RunScript('eval(''' + SScript + ''');', SName);\n    except\n      on E: EChakraCoreScript do\n      begin\n        CheckEquals(0, E.Line, 'EChakraCoreScript.Line');\n        CheckEquals(0, E.Column, 'EChakraCoreScript.Column');\n        CheckEquals(UnicodeString(SScript), E.Source, 'EChakraCoreScript.Source');\n        CheckEquals(UnicodeString('eval code'), E.ScriptURL, 'EChakraCoreScript.ScriptURL');\n        CheckEquals(LoadResString(JsGetErrorMessage(JsErrorScriptException)) + sLineBreak +\n          'ReferenceError: ''badref'' is not defined', E.Message, 'EChakraCoreScript.Message');\n      end;\n    end;\n  finally\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\nprocedure TChakraCoreContextTestCase.TestEvalSyntaxError;\nconst\n  SScript = 'eval(''@ bad syntax'');';\n  SName = 'TestEvalSyntaxError.js';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\nbegin\n  Runtime := nil;\n  Context := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    try\n      Context.RunScript(SScript, SName);\n    except\n      on E: EChakraCoreScript do\n      begin\n        CheckEquals(0, E.Line, 'EChakraCoreScript.Line');\n        CheckEquals(0, E.Column, 'EChakraCoreScript.Column');\n        CheckEquals(UnicodeString(SScript), E.Source, 'EChakraCoreScript.Source');\n        CheckEquals(UnicodeString(SName), E.ScriptURL, 'EChakraCoreScript.ScriptURL');\n        CheckEquals(LoadResString(JsGetErrorMessage(JsErrorScriptException)) + sLineBreak +\n          'SyntaxError: Invalid character', E.Message, 'EChakraCoreScript.Message');\n      end;\n    end;\n  finally\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\n{ TTestObject1 }\n\ntype\n  TTestObject1 = class(TNativeObject)\n  private\n    FMethod1Called: Boolean;\n    FProp1: UnicodeString;\n\n    function GetProp1: JsValueRef;\n    procedure SetProp1(Value: JsValueRef);\n    function Method1(Args: PJsValueRef; ArgCount: Word): JsValueRef;\n  protected\n    class procedure RegisterProperties(AInstance: JsHandle); override;\n    class procedure RegisterMethods(AInstance: JsHandle); override;\n  end;\n\nfunction TTestObject1.GetProp1: JsValueRef;\nbegin\n  Result := StringToJsString(FProp1);\nend;\n\nprocedure TTestObject1.SetProp1(Value: JsValueRef);\nvar\n  SValue: UnicodeString;\nbegin\n  SValue := JsStringToUnicodeString(Value);\n  if SValue <> FProp1 then\n  begin\n    // Prop1 changed\n    FProp1 := SValue;\n  end;\nend;\n\nfunction TTestObject1.Method1(Args: PJsValueRef; ArgCount: Word): JsValueRef;\nbegin\n  Result := StringToJsString('Hello');\n  FMethod1Called := True;\nend;\n\nclass procedure TTestObject1.RegisterMethods(AInstance: JsHandle);\nbegin\n  RegisterMethod(AInstance, 'method1', @TTestObject1.Method1);\nend;\n\nclass procedure TTestObject1.RegisterProperties(AInstance: JsHandle);\nbegin\n  RegisterNamedProperty(AInstance, 'prop1', False, False, @TTestObject1.GetProp1, @TTestObject1.SetProp1);\nend;\n\n{ TNativeClassTestCase }\n\nprocedure TNativeClassTestCase.TestMethod1AsScript;\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\n  TestObject: TTestObject1;\n  Result: JsValueRef;\nbegin\n  Runtime := nil;\n  Context := nil;\n  TestObject := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    TestObject := TTestObject1.Create;\n    JsSetProperty(Context.Global, 'obj', TestObject.Instance);\n    Result := Context.RunScript('obj.method1(null, null);', 'TestMethod1.js');\n    Check(TestObject.FMethod1Called, 'method1 called');\n    CheckValueType(JsString, Result, 'method1 result type');\n    CheckEquals(UnicodeString('Hello'), JsStringToUnicodeString(Result), 'method1 result');\n  finally\n    TestObject.Free;\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\nprocedure TNativeClassTestCase.TestMethod1AsFunction;\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\n  TestObject: TTestObject1;\n  Result: JsValueRef;\nbegin\n  Runtime := nil;\n  Context := nil;\n  TestObject := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    TestObject := TTestObject1.Create;\n    JsSetProperty(Context.Global, 'obj', TestObject.Instance);\n    Result := Context.CallFunction('method1', [], TestObject.Instance);\n    Check(TestObject.FMethod1Called, 'method1 called');\n    CheckValueType(JsString, Result, 'method1 result type');\n    CheckEquals(UnicodeString('Hello'), JsStringToUnicodeString(Result), 'method1 result');\n  finally\n    TestObject.Free;\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\nprocedure TNativeClassTestCase.TestNamedProperty;\nconst\n  SValue: UnicodeString = 'Hello';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\n  TestObject: TTestObject1;\nbegin\n  Runtime := nil;\n  Context := nil;\n  TestObject := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    TestObject := TTestObject1.Create;\n    JsSetProperty(Context.Global, 'obj', TestObject.Instance);\n    Context.RunScript(WideFormat('obj.prop1 = ''%s'';', [SValue]), UnicodeString('TestNamedProperty.js'));\n    CheckEquals(SValue, TestObject.FProp1, 'prop1 value');\n    CheckEquals(SValue, JsStringToUnicodeString(JsGetProperty(TestObject.Instance, 'prop1')), 'prop1 value');\n  finally\n    TestObject.Free;\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\nprocedure TNativeClassTestCase.TestProjectedClass;\nconst\n  SScript: UnicodeString = 'var obj = new TestObject(); var s1 = obj.method1(); obj.prop1 = s1; var s2 = obj.prop1;';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\nbegin\n  Runtime := nil;\n  Context := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    TTestObject1.Project('TestObject');\n    Context.RunScript(SScript, UnicodeString('TestProjectedClass.js'));\n    CheckEquals(UnicodeString('Hello'), JsStringToUnicodeString(JsGetProperty(Context.Global, 's1')), 's1');\n    CheckEquals(UnicodeString('Hello'), JsStringToUnicodeString(JsGetProperty(Context.Global, 's2')), 's2');\n  finally\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\nprocedure TNativeClassTestCase.TestClassProjectedTwice;\nbegin\n  TestProjectedClass;\n  TestProjectedClass;\nend;\n\nprocedure TNativeClassTestCase.TestClassProjectedInMultipleContexts;\nconst\n  SScript: UnicodeString = 'var obj = new TestObject(); var s1 = obj.method1(); obj.prop1 = s1; var s2 = obj.prop1;';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context1, Context2: TChakraCoreContext;\nbegin\n  Runtime := nil;\n  Context1 := nil;\n  Context2 := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context1 := TChakraCoreContext.Create(Runtime);\n    Context2 := TChakraCoreContext.Create(Runtime);\n\n    Context1.Activate;\n    TTestObject1.Project('TestObject');\n    Context1.RunScript(SScript, UnicodeString('TestProjectedClass1.js'));\n    CheckEquals(UnicodeString('Hello'), JsStringToUnicodeString(JsGetProperty(Context1.Global, 's1')), 's1');\n    CheckEquals(UnicodeString('Hello'), JsStringToUnicodeString(JsGetProperty(Context1.Global, 's2')), 's2');\n\n    Context2.Activate;\n    TTestObject1.Project('TestObject');\n    Context2.RunScript(SScript, UnicodeString('TestProjectedClass2.js'));\n    CheckEquals(UnicodeString('Hello'), JsStringToUnicodeString(JsGetProperty(Context2.Global, 's1')), 's1');\n    CheckEquals(UnicodeString('Hello'), JsStringToUnicodeString(JsGetProperty(Context2.Global, 's2')), 's2');\n  finally\n    Context2.Free;\n    Context1.Free;\n    Runtime.Free;\n  end;\nend;\n\n{ TRectangle }\n\ntype\n  TRectangle = class(TNativeObject)\n    class procedure InitializeInstance(AInstance: JsValueRef; Args: PJsValueRef; ArgCount: Word); override;\n    class function InitializePrototype(AConstructor: JsValueRef): JsValueRef; override;\n  end;\n\nclass procedure TRectangle.InitializeInstance(AInstance: JsValueRef; Args: PJsValueRef; ArgCount: Word);\nvar\n  ArgsArray: PJsValueRefArray absolute Args;\n  ShapeCtr: JsValueRef;\nbegin\n  if Self = TRectangle then\n  begin\n    // Shape.call(x, y);\n    ShapeCtr := JsGetProperty(JsGlobal, 'Shape');\n    JsCallFunction(ShapeCtr, [ArgsArray^[0], ArgsArray^[1]], AInstance);\n\n    // this.w = w;\n    JsSetProperty(AInstance, UnicodeString('w'), ArgsArray^[2]);\n    // this.h = h;\n    JsSetProperty(AInstance, UnicodeString('h'), ArgsArray^[3]);\n  end\n  else\n    inherited InitializeInstance(AInstance, Args, ArgCount);\nend;\n\nclass function TRectangle.InitializePrototype(AConstructor: JsValueRef): JsValueRef;\nvar\n  ShapeCtr, ShapePrototype: JsValueRef;\nbegin\n  if Self = TRectangle then\n  begin\n    ShapeCtr := JsGetProperty(JsGlobal, 'Shape');\n    ShapePrototype := JsGetProperty(ShapeCtr, 'prototype');\n    // Rectangle.prototype = Object.create(Shape.prototype);\n    Result := JsCreateObject(ShapePrototype);\n  end\n  else\n    Result := inherited InitializePrototype(AConstructor);\nend;\n\nprocedure TNativeClassTestCase.TestInheritance;\n// same tests as in TChakraCorePrototypes.TestInheritance, against ChakraCoreClasses.TNativeObject implementation\n// - Shape (x, y) => Object\n//   - Circle (x, y, r) => Shape (x, y)\n//   - Rectangle (x, y, w, h) => Shape (x, y)\n//     - Square (x, y, w) => Rectangle (x, y, w, w)\nconst\n  SScript =\n    // Shape: (Javascript) superclass\n    'function Shape(x, y) {'                                     + sLineBreak +\n    '  this.x = x;'                                              + sLineBreak +\n    '  this.y = y;'                                              + sLineBreak +\n    '}'                                                          + sLineBreak +\n                                                                   sLineBreak +\n    'Shape.prototype.move = function(x, y) {'                    + sLineBreak +\n    '  this.x += x;'                                             + sLineBreak +\n    '  this.y += y;'                                             + sLineBreak +\n    '};'                                                         + sLineBreak +\n                                                                   sLineBreak +\n    // Circle: (Javascript) subclass of (Javascript) Shape\n    'function Circle(x, y, r) {'                                 + sLineBreak +\n    '  Shape.call(this, x, y);'                                  + sLineBreak +\n    '  this.r = r;'                                              + sLineBreak +\n    '}'                                                          + sLineBreak +\n                                                                   sLineBreak +\n    'Circle.prototype = Object.create(Shape.prototype);'         + sLineBreak +\n    'Circle.prototype.constructor = Circle;'                     + sLineBreak +\n                                                                   sLineBreak +\n    // Square: (Javascript) subclass of (native) Rectangle\n    'function Square(x, y, w) {'                                 + sLineBreak +\n    '  Rectangle.call(this, x, y, w, w);'                        + sLineBreak +\n    '}'                                                          + sLineBreak +\n                                                                   sLineBreak +\n    'Square.prototype = Object.create(Rectangle.prototype);'     + sLineBreak +\n    'Square.prototype.constructor = Square;';\n  SName = 'TestInheritance.js';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\n  ShapeObj, CircleObj, RectangleObj, SquareObj: JsValueRef;\nbegin\n  Runtime := nil;\n  Context := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    TRectangle.Project('Rectangle');\n\n    JsRunScript(SScript, SName);\n\n    // var shapeObj = new Shape(10, 10);\n    ShapeObj := JsNew('Shape', [IntToJsNumber(10), IntToJsNumber(10)]);\n    CheckValueType(JsObject, ShapeObj, 'shapeObj value type');\n    CheckTrue(JsInstanceOf(ShapeObj, 'Shape'), 'shapeObj instanceof Shape');\n    CheckFalse(JsInstanceOf(ShapeObj, 'Circle'), 'shapeObj instanceof Circle');\n    CheckFalse(JsInstanceOf(ShapeObj, 'Rectangle'), 'shapeObj instanceof Rectangle');\n    CheckFalse(JsInstanceOf(ShapeObj, 'Square'), 'shapeObj instanceof Square');\n\n    CheckEquals(10, JsNumberToInt(JsGetProperty(ShapeObj, 'x')), 'shapeObj.x before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(ShapeObj, 'y')), 'shapeObj.y before move');\n    JsCallFunction('move', [IntToJsNumber(10), IntToJsNumber(10)], ShapeObj);\n    CheckEquals(20, JsNumberToInt(JsGetProperty(ShapeObj, 'x')), 'shapeObj.x after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(ShapeObj, 'y')), 'shapeObj.y after move');\n\n    // var circleObj = new Circle(10, 10, 10);\n    CircleObj := JsNew('Circle', [IntToJsNumber(10), IntToJsNumber(10), IntToJsNumber(10)]);\n    CheckValueType(JsObject, CircleObj, 'circleObj value type');\n    CheckTrue(JsInstanceOf(CircleObj, 'Shape'), 'circleObj instanceof Shape');\n    CheckTrue(JsInstanceOf(CircleObj, 'Circle'), 'circleObj instanceof Circle');\n    CheckFalse(JsInstanceOf(CircleObj, 'Rectangle'), 'circleObj instanceof Rectangle');\n    CheckFalse(JsInstanceOf(CircleObj, 'Square'), 'circleObj instanceof Square');\n\n    CheckEquals(10, JsNumberToInt(JsGetProperty(CircleObj, 'x')), 'circleObj.x before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(CircleObj, 'y')), 'circleObj.y before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(CircleObj, 'r')), 'circleObj.r before move');\n    JsCallFunction('move', [IntToJsNumber(10), IntToJsNumber(10)], CircleObj);\n    CheckEquals(20, JsNumberToInt(JsGetProperty(CircleObj, 'x')), 'circleObj.x after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(CircleObj, 'y')), 'circleObj.y after move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(CircleObj, 'r')), 'circleObj.r after move');\n\n    // var rectangleObj = new Rectangle(10, 10, 60, 40);\n    RectangleObj := JsNew('Rectangle', [IntToJsNumber(10), IntToJsNumber(10), IntToJsNumber(60), IntToJsNumber(40)]);\n    CheckValueType(JsObject, RectangleObj, 'rectangleObj value type');\n    CheckTrue(JsInstanceOf(RectangleObj, 'Shape'), 'rectangleObj instanceof Shape');\n    CheckFalse(JsInstanceOf(RectangleObj, 'Circle'), 'rectangleObj instanceof Circle');\n    CheckTrue(JsInstanceOf(RectangleObj, 'Rectangle'), 'rectangleObj instanceof Rectangle');\n    CheckFalse(JsInstanceOf(RectangleObj, 'Square'), 'rectangleObj instanceof Square');\n\n    CheckEquals(10, JsNumberToInt(JsGetProperty(RectangleObj, 'x')), 'rectangleObj.x before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(RectangleObj, 'y')), 'rectangleObj.y before move');\n    CheckEquals(60, JsNumberToInt(JsGetProperty(RectangleObj, 'w')), 'rectangleObj.w before move');\n    CheckEquals(40, JsNumberToInt(JsGetProperty(RectangleObj, 'h')), 'rectangleObj.h before move');\n    JsCallFunction('move', [IntToJsNumber(10), IntToJsNumber(10)], RectangleObj);\n    CheckEquals(20, JsNumberToInt(JsGetProperty(RectangleObj, 'x')), 'rectangleObj.x after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(RectangleObj, 'y')), 'rectangleObj.y after move');\n    CheckEquals(60, JsNumberToInt(JsGetProperty(RectangleObj, 'w')), 'rectangleObj.w after move');\n    CheckEquals(40, JsNumberToInt(JsGetProperty(RectangleObj, 'h')), 'rectangleObj.h after move');\n\n    // var squareObj = new Square(10, 10, 20);\n    SquareObj := JsNew('Square', [IntToJsNumber(10), IntToJsNumber(10), IntToJsNumber(20)]);\n    CheckValueType(JsObject, SquareObj, 'squareObj value type');\n    CheckTrue(JsInstanceOf(SquareObj, 'Shape'), 'squareObj instanceof Shape');\n    CheckFalse(JsInstanceOf(SquareObj, 'Circle'), 'squareObj instanceof Circle');\n    CheckTrue(JsInstanceOf(SquareObj, 'Rectangle'), 'squareObj instanceof Rectangle');\n    CheckTrue(JsInstanceOf(SquareObj, 'Square'), 'squareObj instanceof Square');\n\n    CheckEquals(10, JsNumberToInt(JsGetProperty(SquareObj, 'x')), 'squareObj.x before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(SquareObj, 'y')), 'sqaureObj.y before move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'w')), 'squareObj.w before move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'h')), 'squareObj.h before move');\n    JsCallFunction('move', [IntToJsNumber(10), IntToJsNumber(10)], SquareObj);\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'x')), 'squareObj.x after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'y')), 'squareObj.y after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'w')), 'squareObj.w after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'h')), 'squareObj.h after move');\n  finally\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\ntype\n\n  { TSquare }\n\n  TSquare = class(TRectangle)\n    class procedure InitializeInstance(AInstance: JsValueRef; Args: PJsValueRef; ArgCount: Word); override;\n  end;\n\n{ TSquare }\n\nclass procedure TSquare.InitializeInstance(AInstance: JsValueRef; Args: PJsValueRef; ArgCount: Word);\nvar\n  ArgsArray: PJsValueRefArray absolute Args;\n  RectangleArgs: array[0..3] of JsValueRef;\nbegin\n  // Rectangle.call(this, x, y, w, w);\n  RectangleArgs[0] := ArgsArray^[0];\n  RectangleArgs[1] := ArgsArray^[1];\n  RectangleArgs[2] := ArgsArray^[2];\n  RectangleArgs[3] := ArgsArray^[2];\n  inherited InitializeInstance(AInstance, @RectangleArgs[0], 4);\nend;\n\nprocedure TNativeClassTestCase.TestInheritance2;\nconst\n  SScript =\n    // Shape: (Javascript) superclass\n    'function Shape(x, y) {'                                     + sLineBreak +\n    '  this.x = x;'                                              + sLineBreak +\n    '  this.y = y;'                                              + sLineBreak +\n    '}'                                                          + sLineBreak +\n                                                                   sLineBreak +\n    'Shape.prototype.move = function(x, y) {'                    + sLineBreak +\n    '  this.x += x;'                                             + sLineBreak +\n    '  this.y += y;'                                             + sLineBreak +\n    '};'                                                         + sLineBreak +\n                                                                   sLineBreak +\n    // Circle: (Javascript) subclass of (Javascript) Shape\n    'function Circle(x, y, r) {'                                 + sLineBreak +\n    '  Shape.call(this, x, y);'                                  + sLineBreak +\n    '  this.r = r;'                                              + sLineBreak +\n    '}'                                                          + sLineBreak +\n                                                                   sLineBreak +\n    'Circle.prototype = Object.create(Shape.prototype);'         + sLineBreak +\n    'Circle.prototype.constructor = Circle;';\n  SName = 'TestInheritance2.js';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\n  ShapeObj, CircleObj, RectangleObj, SquareObj: JsValueRef;\nbegin\n  Runtime := nil;\n  Context := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    TRectangle.Project('Rectangle');\n    TSquare.Project('Square');\n\n    JsRunScript(SScript, SName);\n\n    // var shapeObj = new Shape(10, 10);\n    ShapeObj := JsNew('Shape', [IntToJsNumber(10), IntToJsNumber(10)]);\n    CheckValueType(JsObject, ShapeObj, 'shapeObj value type');\n    CheckTrue(JsInstanceOf(ShapeObj, 'Shape'), 'shapeObj instanceof Shape');\n    CheckFalse(JsInstanceOf(ShapeObj, 'Circle'), 'shapeObj instanceof Circle');\n    CheckFalse(JsInstanceOf(ShapeObj, 'Rectangle'), 'shapeObj instanceof Rectangle');\n    CheckFalse(JsInstanceOf(ShapeObj, 'Square'), 'shapeObj instanceof Square');\n\n    CheckEquals(10, JsNumberToInt(JsGetProperty(ShapeObj, 'x')), 'shapeObj.x before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(ShapeObj, 'y')), 'shapeObj.y before move');\n    JsCallFunction('move', [IntToJsNumber(10), IntToJsNumber(10)], ShapeObj);\n    CheckEquals(20, JsNumberToInt(JsGetProperty(ShapeObj, 'x')), 'shapeObj.x after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(ShapeObj, 'y')), 'shapeObj.y after move');\n\n    // var circleObj = new Circle(10, 10, 10);\n    CircleObj := JsNew('Circle', [IntToJsNumber(10), IntToJsNumber(10), IntToJsNumber(10)]);\n    CheckValueType(JsObject, CircleObj, 'circleObj value type');\n    CheckTrue(JsInstanceOf(CircleObj, 'Shape'), 'circleObj instanceof Shape');\n    CheckTrue(JsInstanceOf(CircleObj, 'Circle'), 'circleObj instanceof Circle');\n    CheckFalse(JsInstanceOf(CircleObj, 'Rectangle'), 'circleObj instanceof Rectangle');\n    CheckFalse(JsInstanceOf(CircleObj, 'Square'), 'circleObj instanceof Square');\n\n    CheckEquals(10, JsNumberToInt(JsGetProperty(CircleObj, 'x')), 'circleObj.x before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(CircleObj, 'y')), 'circleObj.y before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(CircleObj, 'r')), 'circleObj.r before move');\n    JsCallFunction('move', [IntToJsNumber(10), IntToJsNumber(10)], CircleObj);\n    CheckEquals(20, JsNumberToInt(JsGetProperty(CircleObj, 'x')), 'circleObj.x after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(CircleObj, 'y')), 'circleObj.y after move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(CircleObj, 'r')), 'circleObj.r after move');\n\n    // var rectangleObj = new Rectangle(10, 10, 60, 40);\n    RectangleObj := JsNew('Rectangle', [IntToJsNumber(10), IntToJsNumber(10), IntToJsNumber(60), IntToJsNumber(40)]);\n    CheckValueType(JsObject, RectangleObj, 'rectangleObj value type');\n    CheckTrue(JsInstanceOf(RectangleObj, 'Shape'), 'rectangleObj instanceof Shape');\n    CheckFalse(JsInstanceOf(RectangleObj, 'Circle'), 'rectangleObj instanceof Circle');\n    CheckTrue(JsInstanceOf(RectangleObj, 'Rectangle'), 'rectangleObj instanceof Rectangle');\n    CheckFalse(JsInstanceOf(RectangleObj, 'Square'), 'rectangleObj instanceof Square');\n\n    CheckEquals(10, JsNumberToInt(JsGetProperty(RectangleObj, 'x')), 'rectangleObj.x before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(RectangleObj, 'y')), 'rectangleObj.y before move');\n    CheckEquals(60, JsNumberToInt(JsGetProperty(RectangleObj, 'w')), 'rectangleObj.w before move');\n    CheckEquals(40, JsNumberToInt(JsGetProperty(RectangleObj, 'h')), 'rectangleObj.h before move');\n    JsCallFunction('move', [IntToJsNumber(10), IntToJsNumber(10)], RectangleObj);\n    CheckEquals(20, JsNumberToInt(JsGetProperty(RectangleObj, 'x')), 'rectangleObj.x after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(RectangleObj, 'y')), 'rectangleObj.y after move');\n    CheckEquals(60, JsNumberToInt(JsGetProperty(RectangleObj, 'w')), 'rectangleObj.w after move');\n    CheckEquals(40, JsNumberToInt(JsGetProperty(RectangleObj, 'h')), 'rectangleObj.h after move');\n\n    // var squareObj = new Square(10, 10, 20);\n    SquareObj := JsNew('Square', [IntToJsNumber(10), IntToJsNumber(10), IntToJsNumber(20)]);\n    CheckValueType(JsObject, SquareObj, 'squareObj value type');\n    CheckTrue(JsInstanceOf(SquareObj, 'Shape'), 'squareObj instanceof Shape');\n    CheckFalse(JsInstanceOf(SquareObj, 'Circle'), 'squareObj instanceof Circle');\n    CheckTrue(JsInstanceOf(SquareObj, 'Rectangle'), 'squareObj instanceof Rectangle');\n    CheckTrue(JsInstanceOf(SquareObj, 'Square'), 'squareObj instanceof Square');\n\n    CheckEquals(10, JsNumberToInt(JsGetProperty(SquareObj, 'x')), 'squareObj.x before move');\n    CheckEquals(10, JsNumberToInt(JsGetProperty(SquareObj, 'y')), 'sqaureObj.y before move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'w')), 'squareObj.w before move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'h')), 'squareObj.h before move');\n    JsCallFunction('move', [IntToJsNumber(10), IntToJsNumber(10)], SquareObj);\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'x')), 'squareObj.x after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'y')), 'squareObj.y after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'w')), 'squareObj.w after move');\n    CheckEquals(20, JsNumberToInt(JsGetProperty(SquareObj, 'h')), 'squareObj.h after move');\n  finally\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\nvar\n  CreatedCount: Integer = 0;\n  DestroyedCount: Integer = 0;\n\ntype\n  TTestObject2 = class(TNativeObject)\n  public\n    constructor Create(Args: PJsValueRef = nil; ArgCount: Word = 0; AFinalize: Boolean = False); override;\n    destructor Destroy; override;\n  end;\n\nconstructor TTestObject2.Create(Args: PJsValueRef; ArgCount: Word; AFinalize: Boolean);\nbegin\n  inherited Create(Args, ArgCount, AFinalize);\n  Inc(CreatedCount);\nend;\n\ndestructor TTestObject2.Destroy;\nbegin\n  Inc(DestroyedCount);\n  inherited Destroy;\nend;\n\nfunction Get_Alive(Callee: JsValueRef; IsConstructCall: bool; Args: PJsValueRef; ArgCount: Word;\n  CallbackState: Pointer): JsValueRef; {$ifdef WINDOWS}stdcall;{$else}cdecl;{$endif}\nbegin\n  Result := BooleanToJsBoolean(DestroyedCount = 0);\nend;\n\n// see that the finalizer gets called for a native instance if/when GC runs\nprocedure TNativeClassTestCase.TestFinalizer;\nconst\n  SScript =\n    // create native instance from script\n    'var obj = new TestObject2();'                               + sLineBreak +\n    // release reference\n    'obj = null;'                                                + sLineBreak +\n    // wait for GC\n    'while (alive) {'                                            + sLineBreak +\n      // do some allocation to trigger GC eventually\n    '  var obj = new Object();'                                  + sLineBreak +\n    '}';\n  SName = 'TestFinalizer.js';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\nbegin\n  Runtime := nil;\n  Context := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    TTestObject2.Project;\n    JsDefineProperty('alive', False, False, JsCreateFunction(@Get_Alive, nil, UnicodeString('')), nil);\n\n    CreatedCount := 0;\n    DestroyedCount := 0;\n    JsRunScript(SScript, SName);\n\n    CheckEquals(1, CreatedCount, 'constructor calls');\n    CheckEquals(1, DestroyedCount, 'destructor calls');\n  finally\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\n// see that the finalizer gets called for a native instance if/when GC runs, or when the runtime is disposed\nprocedure TNativeClassTestCase.TestFinalizer2;\nconst\n  SScript =\n    'var obj = new TestObject2();'                               + sLineBreak +\n    'obj = null;';\n  SName = 'TestFinalizer2.js';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\nbegin\n  Runtime := nil;\n  Context := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    TTestObject2.Project;\n\n    CreatedCount := 0;\n    DestroyedCount := 0;\n    JsRunScript(SScript, SName);\n  finally\n    Context.Free;\n    Runtime.Free;\n\n    CheckEquals(1, CreatedCount, 'constructor calls');\n    CheckEquals(1, DestroyedCount, 'destructor calls');\n  end;\nend;\n\n// see that the finalizer gets called for a native instance if/when GC runs (invoked by host)\nprocedure TNativeClassTestCase.TestFinalizer3;\nconst\n  SScript =\n    'var obj = new TestObject2();'                               + sLineBreak +\n    'obj = null;';\n  SName = 'TestFinalizer3.js';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\nbegin\n  Runtime := nil;\n  Context := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create([ccroDisableBackgroundWork]); // doesn't seem to work with background GC\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    TTestObject2.Project;\n\n    CreatedCount := 0;\n    DestroyedCount := 0;\n    JsRunScript(SScript, SName);\n    Runtime.CollectGarbage;\n\n    CheckEquals(1, CreatedCount, 'constructor calls');\n    CheckEquals(1, DestroyedCount, 'destructor calls');\n  finally\n    Context.Free;\n    Runtime.Free;\n  end;\nend;\n\nconst\n  FinalizerLoopCount = 10000;\n\n// see that repeated construction of a projected class no longer causes access violation\n// (constructors addrefed to prevent premature GC)\nprocedure TNativeClassTestCase.TestFinalizer4;\nconst\n  SScript =\n    'var obj = new TestObject2();'                               + sLineBreak +\n    'obj = null;'                                                + sLineBreak +\n    '';\n  SName = 'TestFinalizer4.js';\nvar\n  Runtime: TChakraCoreRuntime;\n  Context: TChakraCoreContext;\n  I: Integer;\nbegin\n  Runtime := nil;\n  Context := nil;\n  try\n    Runtime := TChakraCoreRuntime.Create;\n    Context := TChakraCoreContext.Create(Runtime);\n    Context.Activate;\n    TTestObject2.Project;\n\n    CreatedCount := 0;\n    DestroyedCount := 0;\n    for I := 0 to FinalizerLoopCount - 1 do\n      Context.RunScript(SScript, SName);\n  finally\n    Context.Free;\n    Runtime.Free;\n\n    CheckNotEquals(0, CreatedCount, 'constructor calls');\n    CheckEquals(CreatedCount, DestroyedCount, 'destructor calls');\n  end;\nend;\n\ninitialization\n\n{$ifdef FPC}\n  RegisterTests([TChakraCoreContextTestCase, TNativeClassTestCase]);\n{$else}\n  RegisterTests([TChakraCoreContextTestCase.Suite, TNativeClassTestCase.Suite]);\n{$endif}\n\nend.\n"
  },
  {
    "path": "tests/tests.sh",
    "content": "#!/bin/bash\n\nfunction GetChakraCoreLibDir {\n  CPU_TARGET=$1\n  OS_TARGET=$2\n  local __RESULT=$3\n  \n  eval $__RESULT=$BASE_DIR/bin/chakracore/$CPU_TARGET-$OS_TARGET\n}\n\nfunction GetChakraCoreLibName {\n  CPU_TARGET=$1\n  OS_TARGET=$2\n  local __RESULT=$3\n  \n  if [ \"$OS_TARGET\" = \"linux\" ]; then\n    eval $__RESULT=libChakraCore.so\n  elif [ \"$OS_TARGET\" = \"darwin\" ]; then\n    eval $__RESULT=libChakraCore.dylib\n  elif [ \"$OS_TARGET\" = \"win64\" -o \"$OS_TARGET\" = \"win32\" ]; then\n    eval $__RESULT=ChakraCore.dll\n  fi\n}\n\nfunction GetLCL {\n  CPU_TARGET=$1\n  OS_TARGET=$2\n  local __RESULT=$3\n  \n  if [ \"$OS_TARGET\" = \"linux\" ]; then\n    eval $__RESULT=gtk2\n  elif [ \"$OS_TARGET\" = \"darwin\" ]; then\n    eval $__RESULT=cocoa\n  elif [ \"$OS_TARGET\" = \"win64\" ]; then\n    eval $__RESULT=win32\n  elif [ \"$OS_TARGET\" = \"win32\" ]; then\n    eval $__RESULT=win32\n  fi\n}\n\nfunction Clean {\n  CPU_TARGET=$1\n  OS_TARGET=$2\n  \n  echo \"Cleaning $CPU_TARGET-$OS_TARGET...\"\n\n  rm -r $BASE_DIR/bin/$CPU_TARGET-$OS_TARGET/$BUILD_MODE/*\n  rm -r $BASE_DIR/lib/$CPU_TARGET-$OS_TARGET/$BUILD_MODE/*\n}\n\nfunction Build {\n  CPU_TARGET=$1\n  OS_TARGET=$2\n\n  CHAKRA_CORE_LIB_DIR=\n  CHAKRA_CORE_LIB_NAME=\n  GetChakraCoreLibDir $CPU_TARGET $OS_TARGET CHAKRA_CORE_LIB_DIR\n  GetChakraCoreLibName $CPU_TARGET $OS_TARGET CHAKRA_CORE_LIB_NAME\n  CHAKRA_CORE_LIB=$CHAKRA_CORE_LIB_DIR/$CHAKRA_CORE_LIB_NAME\n\n  LCL=\n  GetLCL $CPU_TARGET $OS_TARGET LCL \n\n  FPC_OPTIONS=\"-n \\\n    @$FPC_DIR/fpc.cfg \\\n    -T$OS_TARGET \\\n    -P$CPU_TARGET \\\n    -MDelphiUnicode \\\n    -Scghi \\\n    -O1 \\\n    -gl \\\n    -l \\\n    -vewnhibq \\\n    -Fi$BASE_DIR/lib/$CPU_TARGET-$OS_TARGET/$BUILD_MODE \\\n    -Fl$BASE_DIR/bin/$CPU_TARGET-$OS_TARGET/$BUILD_MODE \\\n    -Fu$BASE_DIR/src \\\n    -Fu$BASE_DIR/ext/jedi \\\n    -Fu$FPCUP_DIR/lazarus/components/fpcunit/lib/$CPU_TARGET-$OS_TARGET/$LCL \\\n    -Fu$FPCUP_DIR/lazarus/components/fpcunit \\\n    -Fu$FPCUP_DIR/lazarus/components/synedit/units/$CPU_TARGET-$OS_TARGET/$LCL \\\n    -Fu$FPCUP_DIR/lazarus/lcl/units/$CPU_TARGET-$OS_TARGET/$LCL \\\n    -Fu$FPCUP_DIR/lazarus/lcl/units/$CPU_TARGET-$OS_TARGET \\\n    -Fu$FPCUP_DIR/lazarus/components/lazutils/lib/$CPU_TARGET-$OS_TARGET \\\n    -Fu$FPCUP_DIR/lazarus/packager/units/$CPU_TARGET-$OS_TARGET \\\n    -Fu$BASE_DIR/. \\\n    -FU$BASE_DIR/lib/$CPU_TARGET-$OS_TARGET/$BUILD_MODE/ \\\n    -FE$BASE_DIR/bin/$CPU_TARGET-$OS_TARGET/$BUILD_MODE/ \\\n    -dLCL \\\n    -dLCL$LCL\"\n\n  if [ \"$OS_TARGET\" = \"linux\" ]; then\n    FPC_OPTIONS+=\" -Cg \\\n      -k\\\"-L $CHAKRA_CORE_LIB_DIR\\\"\"\n  elif [ \"$OS_TARGET\" = \"darwin\" ]; then\n    FPC_OPTIONS+=\" -k\\\"-force_load $CHAKRA_CORE_LIB\\\"\"\n  elif [ \"$OS_TARGET\" = \"win64\" ]; then\n    :;\n  elif [ \"$OS_TARGET\" = \"win32\" ]; then\n    :;\n  fi\n\n  mkdir -p $BASE_DIR/bin/$CPU_TARGET-$OS_TARGET/$BUILD_MODE\n  mkdir -p $BASE_DIR/lib/$CPU_TARGET-$OS_TARGET/$BUILD_MODE\n\n  cp $CHAKRA_CORE_LIB $BASE_DIR/bin/$CPU_TARGET-$OS_TARGET/$BUILD_MODE\n\n  echo \"Building $CPU_TARGET-$OS_TARGET...\"\n  FPC_CMD=\"$FPC_DIR/fpc $FPC_OPTIONS $BASE_DIR/tests/ChakraCoreTests.dpr\"\n  eval $FPC_CMD\n  if [ $? != 0 ]; then\n    exit $?\n  fi\n\n  FPC_CMD=\"$FPC_DIR/fpc $FPC_OPTIONS $BASE_DIR/tests/ChakraCoreTestsUI.dpr\"\n  eval $FPC_CMD\n  if [ $? != 0 ]; then\n    exit $?\n  fi\n\n  ls -lah $BASE_DIR/bin/$CPU_TARGET-$OS_TARGET/$BUILD_MODE\n}\n\n# On Linux/OSX, libChakraCore.so/libChakraCore.dylib should be installed in a directory\n# which is included in the system library path (configured in etc/ld.so.conf),\n# e.g. /usr/local/lib or /usr/lib/x86_64-linux-gnu.\n# Otherwise set the LD_LIBRARY_PATH environment variable.\n\nfunction Test {\n  CPU_TARGET=$1\n  OS_TARGET=$2\n\n  CHAKRA_CORE_LIB_DIR=\n  CHAKRA_CORE_LIB_NAME=\n  GetChakraCoreLibDir $CPU_TARGET $OS_TARGET CHAKRA_CORE_LIB_DIR\n  GetChakraCoreLibName $CPU_TARGET $OS_TARGET CHAKRA_CORE_LIB_NAME\n  CHAKRA_CORE_LIB=$CHAKRA_CORE_LIB_DIR/$CHAKRA_CORE_LIB_NAME\n  \n  TARGET_HOST=\n  TARGET_USER=tondrej\n  TARGET_DIR=\n  \n  if [ \"$OS_TARGET\" = \"linux\" ]; then\n    # arrakis\n    TARGET_HOST=arrakis.local\n    TARGET_DIR=~/Test   \n\n    echo \"Testing $CPU_TARGET-$OS_TARGET on $TARGET_HOST...\"\n    ssh $TARGET_USER@$TARGET_HOST \"mkdir $TARGET_DIR/\"\n    ssh $TARGET_USER@$TARGET_HOST \"rm -r $TARGET_DIR/*\"\n    scp -r $BASE_DIR/bin/$CPU_TARGET-$OS_TARGET/$BUILD_MODE/* $TARGET_USER@$TARGET_HOST:$TARGET_DIR/\n    ssh $TARGET_USER@$TARGET_HOST \"LD_LIBRARY_PATH=$TARGET_DIR/ $TARGET_DIR/ChakraCoreTests --all --progress --format=plain\" >> test.log\n  elif [ \"$OS_TARGET\" = \"darwin\" ]; then\n    # kaitain\n    TARGET_HOST=kaitain.local\n    TARGET_DIR=/Users/tondrej/Test\n    DYLD_DIR=/Users/tondrej/Development/ChakraCore/out/Release/bin/ChakraCore\n\n    echo \"Testing $CPU_TARGET-$OS_TARGET on $TARGET_HOST...\"\n    ssh $TARGET_USER@$TARGET_HOST \"mkdir $TARGET_DIR/\"\n    ssh $TARGET_USER@$TARGET_HOST \"rm -r $TARGET_DIR/*\"\n    scp -r $BASE_DIR/bin/$CPU_TARGET-$OS_TARGET/$BUILD_MODE/* $TARGET_USER@$TARGET_HOST:$TARGET_DIR/\n    ssh $TARGET_USER@$TARGET_HOST \"DYLD_LIBRARY_PATH=$DYLD_DIR $TARGET_DIR/ChakraCoreTests --all --progress --format=plain\" >> test.log\n  elif [ \"$OS_TARGET\" = \"win64\" ]; then\n    # tleilax\n    TARGET_HOST=tleilax.local\n    TARGET_DIR=C:\\\\Users\\\\tondrej\\\\Test64\n\n    echo \"Testing $CPU_TARGET-$OS_TARGET on $TARGET_HOST...\"\n    sshpass -p \"$PASSWORD\" ssh $TARGET_USER@$TARGET_HOST \"mkdir $TARGET_DIR\"\n    sshpass -p \"$PASSWORD\" ssh $TARGET_USER@$TARGET_HOST \"del /q /s $TARGET_DIR\\\\*.*\"\n    sshpass -p \"$PASSWORD\" scp -r $BASE_DIR/bin/$CPU_TARGET-$OS_TARGET/$BUILD_MODE/* $TARGET_USER@$TARGET_HOST:$TARGET_DIR\\\\\n    sshpass -p \"$PASSWORD\" ssh $TARGET_USER@$TARGET_HOST \"$TARGET_DIR\\\\ChakraCoreTests --all --progress --format=plain\" >> test.log\n  elif [ \"$OS_TARGET\" = \"win32\" ]; then\n    # tleilax\n    TARGET_HOST=tleilax.local\n    TARGET_DIR=C:\\\\Users\\\\tondrej\\\\Test32\n\n    echo \"Testing $CPU_TARGET-$OS_TARGET on $TARGET_HOST...\"\n    echo $PWD\n    sshpass -p \"$PASSWORD\" ssh $TARGET_USER@$TARGET_HOST \"mkdir $TARGET_DIR\"\n    sshpass -p \"$PASSWORD\" ssh $TARGET_USER@$TARGET_HOST \"del /q /s $TARGET_DIR\\\\*.*\"\n    sshpass -p \"$PASSWORD\" scp -r $BASE_DIR/bin/$CPU_TARGET-$OS_TARGET/$BUILD_MODE/* $TARGET_USER@$TARGET_HOST:$TARGET_DIR\\\\\n    sshpass -p \"$PASSWORD\" ssh $TARGET_USER@$TARGET_HOST \"$TARGET_DIR\\\\ChakraCoreTests --all --progress --format=plain\" >> test.log\n  fi\n\n}\n\nfunction Linux {\n  Clean x86_64 linux\n  Build x86_64 linux\n  Test  x86_64 linux\n}\n\nfunction Darwin {\n  Clean x86_64 darwin\n  Build x86_64 darwin\n  Test  x86_64 darwin\n}\n\nfunction Win64 {\n  Clean x86_64 win64\n  Build x86_64 win64\n  Test  x86_64 win64\n}\n\nfunction Win32 {\n  Clean i386 win32\n  Build i386 win32\n  Test  i386 win32\n}\n\nBUILD_MODE=Debug\nBASE_DIR=`dirname $0`\nBASE_DIR=$BASE_DIR/..\nFPCUP_DIR=~/fpcupdeluxe\nFPC_DIR=$FPCUP_DIR/fpc/bin/x86_64-linux\n\nrm test.log\nLinux\nDarwin\nWin64\nWin32\ncat test.log\n\n"
  }
]