// Copyright (c) The NodeRT Contributors
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the ""License""); you may
// not use this file except in compliance with the License. You may obtain a
// copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing permissions
// and limitations under the License.

// TODO: Verify that this is is still needed..
#define NTDDI_VERSION 0x06010000

#include <v8.h>
#include "nan.h"
#include <string>
#include <ppltasks.h>
#include "CollectionsConverter.h"
#include "CollectionsWrap.h"
#include "node-async.h"
#include "NodeRtUtils.h"
#include "OpaqueWrapper.h"
#include "WrapperBase.h"

#using <Windows.WinMD>

// this undefs fixes the issues of compiling Windows.Data.Json, Windows.Storag.FileProperties, and Windows.Stroage.Search
// Some of the node header files brings windows definitions with the same names as some of the WinRT methods
#undef DocumentProperties
#undef GetObject
#undef CreateEvent
#undef FindText
#undef SendMessage

const char* REGISTRATION_TOKEN_MAP_PROPERTY_NAME = "__registrationTokenMap__";

using v8::Array;
using v8::String;
using v8::Value;
using v8::Boolean;
using v8::Integer;
using v8::FunctionTemplate;
using v8::Object;
using v8::Local;
using v8::Function;
using v8::Date;
using v8::Number;
using v8::PropertyAttribute;
using v8::Primitive;
using Nan::HandleScope;
using Nan::Persistent;
using Nan::Undefined;
using Nan::True;
using Nan::False;
using Nan::Null;
using Nan::MaybeLocal;
using Nan::EscapableHandleScope;
using Nan::HandleScope;
using Nan::TryCatch;
using namespace concurrency;

namespace NodeRT { namespace Windows { namespace Security { namespace Authentication { namespace Web { namespace Core { 
  v8::Local<v8::Value> WrapWebTokenRequest(::Windows::Security::Authentication::Web::Core::WebTokenRequest^ wintRtInstance);
  ::Windows::Security::Authentication::Web::Core::WebTokenRequest^ UnwrapWebTokenRequest(Local<Value> value);
  
  v8::Local<v8::Value> WrapWebAccountEventArgs(::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^ wintRtInstance);
  ::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^ UnwrapWebAccountEventArgs(Local<Value> value);
  
  v8::Local<v8::Value> WrapFindAllAccountsResult(::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^ wintRtInstance);
  ::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^ UnwrapFindAllAccountsResult(Local<Value> value);
  
  v8::Local<v8::Value> WrapWebAccountMonitor(::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ wintRtInstance);
  ::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ UnwrapWebAccountMonitor(Local<Value> value);
  
  v8::Local<v8::Value> WrapWebAuthenticationCoreManager(::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^ wintRtInstance);
  ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^ UnwrapWebAuthenticationCoreManager(Local<Value> value);
  
  v8::Local<v8::Value> WrapWebProviderError(::Windows::Security::Authentication::Web::Core::WebProviderError^ wintRtInstance);
  ::Windows::Security::Authentication::Web::Core::WebProviderError^ UnwrapWebProviderError(Local<Value> value);
  
  v8::Local<v8::Value> WrapWebTokenResponse(::Windows::Security::Authentication::Web::Core::WebTokenResponse^ wintRtInstance);
  ::Windows::Security::Authentication::Web::Core::WebTokenResponse^ UnwrapWebTokenResponse(Local<Value> value);
  
  v8::Local<v8::Value> WrapWebTokenRequestResult(::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^ wintRtInstance);
  ::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^ UnwrapWebTokenRequestResult(Local<Value> value);
  



  static void InitWebTokenRequestPromptTypeEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("WebTokenRequestPromptType").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("default").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Security::Authentication::Web::Core::WebTokenRequestPromptType::Default)));
    Nan::Set(enumObject, Nan::New<String>("forceAuthentication").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Security::Authentication::Web::Core::WebTokenRequestPromptType::ForceAuthentication)));
  }

  static void InitFindAllWebAccountsStatusEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("FindAllWebAccountsStatus").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("success").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Security::Authentication::Web::Core::FindAllWebAccountsStatus::Success)));
    Nan::Set(enumObject, Nan::New<String>("notAllowedByProvider").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Security::Authentication::Web::Core::FindAllWebAccountsStatus::NotAllowedByProvider)));
    Nan::Set(enumObject, Nan::New<String>("notSupportedByProvider").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Security::Authentication::Web::Core::FindAllWebAccountsStatus::NotSupportedByProvider)));
    Nan::Set(enumObject, Nan::New<String>("providerError").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Security::Authentication::Web::Core::FindAllWebAccountsStatus::ProviderError)));
  }

  static void InitWebTokenRequestStatusEnum(const Local<Object> exports) {
    HandleScope scope;

    Local<Object> enumObject = Nan::New<Object>();

    Nan::Set(exports, Nan::New<String>("WebTokenRequestStatus").ToLocalChecked(), enumObject);
    Nan::Set(enumObject, Nan::New<String>("success").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Security::Authentication::Web::Core::WebTokenRequestStatus::Success)));
    Nan::Set(enumObject, Nan::New<String>("userCancel").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Security::Authentication::Web::Core::WebTokenRequestStatus::UserCancel)));
    Nan::Set(enumObject, Nan::New<String>("accountSwitch").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Security::Authentication::Web::Core::WebTokenRequestStatus::AccountSwitch)));
    Nan::Set(enumObject, Nan::New<String>("userInteractionRequired").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Security::Authentication::Web::Core::WebTokenRequestStatus::UserInteractionRequired)));
    Nan::Set(enumObject, Nan::New<String>("accountProviderNotAvailable").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Security::Authentication::Web::Core::WebTokenRequestStatus::AccountProviderNotAvailable)));
    Nan::Set(enumObject, Nan::New<String>("providerError").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::Security::Authentication::Web::Core::WebTokenRequestStatus::ProviderError)));
  }



  class WebTokenRequest : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("WebTokenRequest").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("clientId").ToLocalChecked(), ClientIdGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("promptType").ToLocalChecked(), PromptTypeGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("properties").ToLocalChecked(), PropertiesGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("scope").ToLocalChecked(), ScopeGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("webAccountProvider").ToLocalChecked(), WebAccountProviderGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("appProperties").ToLocalChecked(), AppPropertiesGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("correlationId").ToLocalChecked(), CorrelationIdGetter, CorrelationIdSetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("WebTokenRequest").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      WebTokenRequest(::Windows::Security::Authentication::Web::Core::WebTokenRequest^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Security::Authentication::Web::Core::WebTokenRequest^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info[0])) {
        try {
          winRtInstance = (::Windows::Security::Authentication::Web::Core::WebTokenRequest^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 3
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccountProvider^>(info[0])
        && info[1]->IsString()
        && info[2]->IsString())
      {
        try {
          ::Windows::Security::Credentials::WebAccountProvider^ arg0 = dynamic_cast<::Windows::Security::Credentials::WebAccountProvider^>(NodeRT::Utils::GetObjectInstance(info[0]));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
          Platform::String^ arg2 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[2])));
          
          winRtInstance = ref new ::Windows::Security::Authentication::Web::Core::WebTokenRequest(arg0,arg1,arg2);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 4
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccountProvider^>(info[0])
        && info[1]->IsString()
        && info[2]->IsString()
        && info[3]->IsInt32())
      {
        try {
          ::Windows::Security::Credentials::WebAccountProvider^ arg0 = dynamic_cast<::Windows::Security::Credentials::WebAccountProvider^>(NodeRT::Utils::GetObjectInstance(info[0]));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
          Platform::String^ arg2 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[2])));
          ::Windows::Security::Authentication::Web::Core::WebTokenRequestPromptType arg3 = static_cast<::Windows::Security::Authentication::Web::Core::WebTokenRequestPromptType>(Nan::To<int32_t>(info[3]).FromMaybe(0));
          
          winRtInstance = ref new ::Windows::Security::Authentication::Web::Core::WebTokenRequest(arg0,arg1,arg2,arg3);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 1
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccountProvider^>(info[0]))
      {
        try {
          ::Windows::Security::Credentials::WebAccountProvider^ arg0 = dynamic_cast<::Windows::Security::Credentials::WebAccountProvider^>(NodeRT::Utils::GetObjectInstance(info[0]));
          
          winRtInstance = ref new ::Windows::Security::Authentication::Web::Core::WebTokenRequest(arg0);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 2
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccountProvider^>(info[0])
        && info[1]->IsString())
      {
        try {
          ::Windows::Security::Credentials::WebAccountProvider^ arg0 = dynamic_cast<::Windows::Security::Credentials::WebAccountProvider^>(NodeRT::Utils::GetObjectInstance(info[0]));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
          
          winRtInstance = ref new ::Windows::Security::Authentication::Web::Core::WebTokenRequest(arg0,arg1);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      WebTokenRequest *wrapperInstance = new WebTokenRequest(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Security::Authentication::Web::Core::WebTokenRequest^ winRtInstance;
      try {
        winRtInstance = (::Windows::Security::Authentication::Web::Core::WebTokenRequest^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapWebTokenRequest(winRtInstance));
    }





    static void ClientIdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info.This())) {
        return;
      }

      WebTokenRequest *wrapper = WebTokenRequest::Unwrap<WebTokenRequest>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->ClientId;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void PromptTypeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info.This())) {
        return;
      }

      WebTokenRequest *wrapper = WebTokenRequest::Unwrap<WebTokenRequest>(info.This());

      try  {
        ::Windows::Security::Authentication::Web::Core::WebTokenRequestPromptType result = wrapper->_instance->PromptType;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void PropertiesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info.This())) {
        return;
      }

      WebTokenRequest *wrapper = WebTokenRequest::Unwrap<WebTokenRequest>(info.This());

      try  {
        ::Windows::Foundation::Collections::IMap<::Platform::String^, ::Platform::String^>^ result = wrapper->_instance->Properties;
        info.GetReturnValue().Set(NodeRT::Collections::MapWrapper<::Platform::String^,::Platform::String^>::CreateMapWrapper(result, 
            [](::Platform::String^ val) -> Local<Value> {
              return NodeRT::Utils::NewString(val->Data());
            },
            [](Local<Value> value) -> bool {
              return value->IsString();
            },
            [](Local<Value> value) -> ::Platform::String^ {
              return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), value)));
            },
            [](::Platform::String^ val) -> Local<Value> {
              return NodeRT::Utils::NewString(val->Data());
            },
            [](Local<Value> value) -> bool {
              return value->IsString();
            },
            [](Local<Value> value) -> ::Platform::String^ {
              return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), value)));
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ScopeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info.This())) {
        return;
      }

      WebTokenRequest *wrapper = WebTokenRequest::Unwrap<WebTokenRequest>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->Scope;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void WebAccountProviderGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info.This())) {
        return;
      }

      WebTokenRequest *wrapper = WebTokenRequest::Unwrap<WebTokenRequest>(info.This());

      try  {
        ::Windows::Security::Credentials::WebAccountProvider^ result = wrapper->_instance->WebAccountProvider;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Security.Credentials", "WebAccountProvider", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void AppPropertiesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info.This())) {
        return;
      }

      WebTokenRequest *wrapper = WebTokenRequest::Unwrap<WebTokenRequest>(info.This());

      try  {
        ::Windows::Foundation::Collections::IMap<::Platform::String^, ::Platform::String^>^ result = wrapper->_instance->AppProperties;
        info.GetReturnValue().Set(NodeRT::Collections::MapWrapper<::Platform::String^,::Platform::String^>::CreateMapWrapper(result, 
            [](::Platform::String^ val) -> Local<Value> {
              return NodeRT::Utils::NewString(val->Data());
            },
            [](Local<Value> value) -> bool {
              return value->IsString();
            },
            [](Local<Value> value) -> ::Platform::String^ {
              return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), value)));
            },
            [](::Platform::String^ val) -> Local<Value> {
              return NodeRT::Utils::NewString(val->Data());
            },
            [](Local<Value> value) -> bool {
              return value->IsString();
            },
            [](Local<Value> value) -> ::Platform::String^ {
              return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), value)));
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void CorrelationIdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info.This())) {
        return;
      }

      WebTokenRequest *wrapper = WebTokenRequest::Unwrap<WebTokenRequest>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->CorrelationId;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void CorrelationIdSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) {
      HandleScope scope;

      if (!value->IsString()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type")));
        return;
      }

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info.This())) {
        return;
      }

      WebTokenRequest *wrapper = WebTokenRequest::Unwrap<WebTokenRequest>(info.This());

      try {

        Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), value)));

        wrapper->_instance->CorrelationId = winRtValue;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }
    }
      


    private:
      ::Windows::Security::Authentication::Web::Core::WebTokenRequest^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapWebTokenRequest(::Windows::Security::Authentication::Web::Core::WebTokenRequest^ wintRtInstance);
      friend ::Windows::Security::Authentication::Web::Core::WebTokenRequest^ UnwrapWebTokenRequest(Local<Value> value);
  };

  Persistent<FunctionTemplate> WebTokenRequest::s_constructorTemplate;

  v8::Local<v8::Value> WrapWebTokenRequest(::Windows::Security::Authentication::Web::Core::WebTokenRequest^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(WebTokenRequest::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Security::Authentication::Web::Core::WebTokenRequest^ UnwrapWebTokenRequest(Local<Value> value) {
     return WebTokenRequest::Unwrap<WebTokenRequest>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitWebTokenRequest(Local<Object> exports) {
    WebTokenRequest::Init(exports);
  }

  class WebAccountEventArgs : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("WebAccountEventArgs").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("account").ToLocalChecked(), AccountGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("WebAccountEventArgs").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      WebAccountEventArgs(::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^>(info[0])) {
        try {
          winRtInstance = (::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      WebAccountEventArgs *wrapperInstance = new WebAccountEventArgs(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^ winRtInstance;
      try {
        winRtInstance = (::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapWebAccountEventArgs(winRtInstance));
    }





    static void AccountGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^>(info.This())) {
        return;
      }

      WebAccountEventArgs *wrapper = WebAccountEventArgs::Unwrap<WebAccountEventArgs>(info.This());

      try  {
        ::Windows::Security::Credentials::WebAccount^ result = wrapper->_instance->Account;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Security.Credentials", "WebAccount", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapWebAccountEventArgs(::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^ wintRtInstance);
      friend ::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^ UnwrapWebAccountEventArgs(Local<Value> value);
  };

  Persistent<FunctionTemplate> WebAccountEventArgs::s_constructorTemplate;

  v8::Local<v8::Value> WrapWebAccountEventArgs(::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(WebAccountEventArgs::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^ UnwrapWebAccountEventArgs(Local<Value> value) {
     return WebAccountEventArgs::Unwrap<WebAccountEventArgs>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitWebAccountEventArgs(Local<Object> exports) {
    WebAccountEventArgs::Init(exports);
  }

  class FindAllAccountsResult : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("FindAllAccountsResult").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("accounts").ToLocalChecked(), AccountsGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("providerError").ToLocalChecked(), ProviderErrorGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("status").ToLocalChecked(), StatusGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("FindAllAccountsResult").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      FindAllAccountsResult(::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^>(info[0])) {
        try {
          winRtInstance = (::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      FindAllAccountsResult *wrapperInstance = new FindAllAccountsResult(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^ winRtInstance;
      try {
        winRtInstance = (::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapFindAllAccountsResult(winRtInstance));
    }





    static void AccountsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^>(info.This())) {
        return;
      }

      FindAllAccountsResult *wrapper = FindAllAccountsResult::Unwrap<FindAllAccountsResult>(info.This());

      try  {
        ::Windows::Foundation::Collections::IVectorView<::Windows::Security::Credentials::WebAccount^>^ result = wrapper->_instance->Accounts;
        info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::Security::Credentials::WebAccount^>::CreateVectorViewWrapper(result, 
            [](::Windows::Security::Credentials::WebAccount^ val) -> Local<Value> {
              return NodeRT::Utils::CreateExternalWinRTObject("Windows.Security.Credentials", "WebAccount", val);
            },
            [](Local<Value> value) -> bool {
              return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccount^>(value);
            },
            [](Local<Value> value) -> ::Windows::Security::Credentials::WebAccount^ {
              return dynamic_cast<::Windows::Security::Credentials::WebAccount^>(NodeRT::Utils::GetObjectInstance(value));
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ProviderErrorGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^>(info.This())) {
        return;
      }

      FindAllAccountsResult *wrapper = FindAllAccountsResult::Unwrap<FindAllAccountsResult>(info.This());

      try  {
        ::Windows::Security::Authentication::Web::Core::WebProviderError^ result = wrapper->_instance->ProviderError;
        info.GetReturnValue().Set(WrapWebProviderError(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void StatusGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^>(info.This())) {
        return;
      }

      FindAllAccountsResult *wrapper = FindAllAccountsResult::Unwrap<FindAllAccountsResult>(info.This());

      try  {
        ::Windows::Security::Authentication::Web::Core::FindAllWebAccountsStatus result = wrapper->_instance->Status;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapFindAllAccountsResult(::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^ wintRtInstance);
      friend ::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^ UnwrapFindAllAccountsResult(Local<Value> value);
  };

  Persistent<FunctionTemplate> FindAllAccountsResult::s_constructorTemplate;

  v8::Local<v8::Value> WrapFindAllAccountsResult(::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(FindAllAccountsResult::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^ UnwrapFindAllAccountsResult(Local<Value> value) {
     return FindAllAccountsResult::Unwrap<FindAllAccountsResult>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitFindAllAccountsResult(Local<Object> exports) {
    FindAllAccountsResult::Init(exports);
  }

  class WebAccountMonitor : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("WebAccountMonitor").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);




          
          Nan::SetPrototypeMethod(localRef,"addListener", AddListener);
          Nan::SetPrototypeMethod(localRef,"on", AddListener);
          Nan::SetPrototypeMethod(localRef,"removeListener", RemoveListener);
          Nan::SetPrototypeMethod(localRef, "off", RemoveListener);


        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("WebAccountMonitor").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      WebAccountMonitor(::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAccountMonitor^>(info[0])) {
        try {
          winRtInstance = (::Windows::Security::Authentication::Web::Core::WebAccountMonitor^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      WebAccountMonitor *wrapperInstance = new WebAccountMonitor(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAccountMonitor^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ winRtInstance;
      try {
        winRtInstance = (::Windows::Security::Authentication::Web::Core::WebAccountMonitor^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapWebAccountMonitor(winRtInstance));
    }







    static void AddListener(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"wrong arguments, expected arguments are eventName(string),callback(function)")));
        return;
      }

      String::Value eventName(v8::Isolate::GetCurrent(), info[0]);
      auto str = *eventName;

      Local<Function> callback = info[1].As<Function>();

      ::Windows::Foundation::EventRegistrationToken registrationToken;
      if (NodeRT::Utils::CaseInsenstiveEquals(L"defaultSignInAccountChanged", str))
      {
        if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAccountMonitor^>(info.This()))
        {
          Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
      return;
        }
        WebAccountMonitor *wrapper = WebAccountMonitor::Unwrap<WebAccountMonitor>(info.This());
      
        try {
          Persistent<Object>* perstPtr = new Persistent<Object>();
          perstPtr->Reset(NodeRT::Utils::CreateCallbackObjectInDomain(callback));
          std::shared_ptr<Persistent<Object>> callbackObjPtr(perstPtr,
            [] (Persistent<Object> *ptr ) {
              NodeUtils::Async::RunOnMain([ptr]() {
                ptr->Reset();
                delete ptr;
            });
          });

          registrationToken = wrapper->_instance->DefaultSignInAccountChanged::add(
            ref new ::Windows::Foundation::TypedEventHandler<::Windows::Security::Authentication::Web::Core::WebAccountMonitor^, ::Platform::Object^>(
            [callbackObjPtr](::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ arg0, ::Platform::Object^ arg1) {
              NodeUtils::Async::RunOnMain([callbackObjPtr , arg0, arg1]() {
                HandleScope scope;


                Local<Value> wrappedArg0;
                Local<Value> wrappedArg1;

                {
                  TryCatch tryCatch;


                  wrappedArg0 = WrapWebAccountMonitor(arg0);
                  wrappedArg1 = CreateOpaqueWrapper(arg1);


                  if (wrappedArg0.IsEmpty()) wrappedArg0 = Undefined();
                  if (wrappedArg1.IsEmpty()) wrappedArg1 = Undefined();
                }

                Local<Value> args[] = { wrappedArg0, wrappedArg1 };
                Local<Object> callbackObjLocalRef = Nan::New<Object>(*callbackObjPtr);
                NodeRT::Utils::CallCallbackInDomain(callbackObjLocalRef, _countof(args), args);
              });
            })
          );
        }
        catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }

      }
      else if (NodeRT::Utils::CaseInsenstiveEquals(L"removed", str))
      {
        if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAccountMonitor^>(info.This()))
        {
          Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
      return;
        }
        WebAccountMonitor *wrapper = WebAccountMonitor::Unwrap<WebAccountMonitor>(info.This());
      
        try {
          Persistent<Object>* perstPtr = new Persistent<Object>();
          perstPtr->Reset(NodeRT::Utils::CreateCallbackObjectInDomain(callback));
          std::shared_ptr<Persistent<Object>> callbackObjPtr(perstPtr,
            [] (Persistent<Object> *ptr ) {
              NodeUtils::Async::RunOnMain([ptr]() {
                ptr->Reset();
                delete ptr;
            });
          });

          registrationToken = wrapper->_instance->Removed::add(
            ref new ::Windows::Foundation::TypedEventHandler<::Windows::Security::Authentication::Web::Core::WebAccountMonitor^, ::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^>(
            [callbackObjPtr](::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ arg0, ::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^ arg1) {
              NodeUtils::Async::RunOnMain([callbackObjPtr , arg0, arg1]() {
                HandleScope scope;


                Local<Value> wrappedArg0;
                Local<Value> wrappedArg1;

                {
                  TryCatch tryCatch;


                  wrappedArg0 = WrapWebAccountMonitor(arg0);
                  wrappedArg1 = WrapWebAccountEventArgs(arg1);


                  if (wrappedArg0.IsEmpty()) wrappedArg0 = Undefined();
                  if (wrappedArg1.IsEmpty()) wrappedArg1 = Undefined();
                }

                Local<Value> args[] = { wrappedArg0, wrappedArg1 };
                Local<Object> callbackObjLocalRef = Nan::New<Object>(*callbackObjPtr);
                NodeRT::Utils::CallCallbackInDomain(callbackObjLocalRef, _countof(args), args);
              });
            })
          );
        }
        catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }

      }
      else if (NodeRT::Utils::CaseInsenstiveEquals(L"updated", str))
      {
        if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAccountMonitor^>(info.This()))
        {
          Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
      return;
        }
        WebAccountMonitor *wrapper = WebAccountMonitor::Unwrap<WebAccountMonitor>(info.This());
      
        try {
          Persistent<Object>* perstPtr = new Persistent<Object>();
          perstPtr->Reset(NodeRT::Utils::CreateCallbackObjectInDomain(callback));
          std::shared_ptr<Persistent<Object>> callbackObjPtr(perstPtr,
            [] (Persistent<Object> *ptr ) {
              NodeUtils::Async::RunOnMain([ptr]() {
                ptr->Reset();
                delete ptr;
            });
          });

          registrationToken = wrapper->_instance->Updated::add(
            ref new ::Windows::Foundation::TypedEventHandler<::Windows::Security::Authentication::Web::Core::WebAccountMonitor^, ::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^>(
            [callbackObjPtr](::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ arg0, ::Windows::Security::Authentication::Web::Core::WebAccountEventArgs^ arg1) {
              NodeUtils::Async::RunOnMain([callbackObjPtr , arg0, arg1]() {
                HandleScope scope;


                Local<Value> wrappedArg0;
                Local<Value> wrappedArg1;

                {
                  TryCatch tryCatch;


                  wrappedArg0 = WrapWebAccountMonitor(arg0);
                  wrappedArg1 = WrapWebAccountEventArgs(arg1);


                  if (wrappedArg0.IsEmpty()) wrappedArg0 = Undefined();
                  if (wrappedArg1.IsEmpty()) wrappedArg1 = Undefined();
                }

                Local<Value> args[] = { wrappedArg0, wrappedArg1 };
                Local<Object> callbackObjLocalRef = Nan::New<Object>(*callbackObjPtr);
                NodeRT::Utils::CallCallbackInDomain(callbackObjLocalRef, _countof(args), args);
              });
            })
          );
        }
        catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }

      }
 else  {
        Nan::ThrowError(Nan::Error(String::Concat(v8::Isolate::GetCurrent(), NodeRT::Utils::NewString(L"given event name isn't supported: "), info[0].As<String>())));
        return;
      }

      Local<Value> tokenMapVal = NodeRT::Utils::GetHiddenValue(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked());
      Local<Object> tokenMap;

      if (tokenMapVal.IsEmpty() || Nan::Equals(tokenMapVal, Undefined()).FromMaybe(false)) {
        tokenMap = Nan::New<Object>();
        NodeRT::Utils::SetHiddenValueWithObject(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked(), tokenMap);
      } else {
        tokenMap = Nan::To<Object>(tokenMapVal).ToLocalChecked();
      }

      Nan::Set(tokenMap, info[0], CreateOpaqueWrapper(::Windows::Foundation::PropertyValue::CreateInt64(registrationToken.Value)));
    }

    static void RemoveListener(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"wrong arguments, expected a string and a callback")));
        return;
      }

      String::Value eventName(v8::Isolate::GetCurrent(), info[0]);
      auto str = *eventName;

      if ((!NodeRT::Utils::CaseInsenstiveEquals(L"defaultSignInAccountChanged", str)) &&(!NodeRT::Utils::CaseInsenstiveEquals(L"removed", str)) &&(!NodeRT::Utils::CaseInsenstiveEquals(L"updated", str))) {
        Nan::ThrowError(Nan::Error(String::Concat(v8::Isolate::GetCurrent(), NodeRT::Utils::NewString(L"given event name isn't supported: "), info[0].As<String>())));
        return;
      }

      Local<Function> callback = info[1].As<Function>();
      Local<Value> tokenMap = NodeRT::Utils::GetHiddenValue(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked());

      if (tokenMap.IsEmpty() || Nan::Equals(tokenMap, Undefined()).FromMaybe(false)) {
        return;
      }

      Local<Value> opaqueWrapperObj =  Nan::Get(Nan::To<Object>(tokenMap).ToLocalChecked(), info[0]).ToLocalChecked();

      if (opaqueWrapperObj.IsEmpty() || Nan::Equals(opaqueWrapperObj,Undefined()).FromMaybe(false)) {
        return;
      }

      OpaqueWrapper *opaqueWrapper = OpaqueWrapper::Unwrap<OpaqueWrapper>(opaqueWrapperObj.As<Object>());

      long long tokenValue = (long long) opaqueWrapper->GetObjectInstance();
      ::Windows::Foundation::EventRegistrationToken registrationToken;
      registrationToken.Value = tokenValue;

      try  {
        if (NodeRT::Utils::CaseInsenstiveEquals(L"defaultSignInAccountChanged", str)) {
          if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAccountMonitor^>(info.This()))
          {
            Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
            return;
          }
          WebAccountMonitor *wrapper = WebAccountMonitor::Unwrap<WebAccountMonitor>(info.This());
          wrapper->_instance->DefaultSignInAccountChanged::remove(registrationToken);
        }
        else if (NodeRT::Utils::CaseInsenstiveEquals(L"removed", str))
        {
          if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAccountMonitor^>(info.This()))
          {
            Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
            return;
          }
          WebAccountMonitor *wrapper = WebAccountMonitor::Unwrap<WebAccountMonitor>(info.This());
          wrapper->_instance->Removed::remove(registrationToken);
        }
        else if (NodeRT::Utils::CaseInsenstiveEquals(L"updated", str))
        {
          if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAccountMonitor^>(info.This()))
          {
            Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed")));
            return;
          }
          WebAccountMonitor *wrapper = WebAccountMonitor::Unwrap<WebAccountMonitor>(info.This());
          wrapper->_instance->Updated::remove(registrationToken);
        }
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
      }

      Nan::Delete(Nan::To<Object>(tokenMap).ToLocalChecked(), Nan::To<String>(info[0]).ToLocalChecked());
    }
    private:
      ::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapWebAccountMonitor(::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ wintRtInstance);
      friend ::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ UnwrapWebAccountMonitor(Local<Value> value);
  };

  Persistent<FunctionTemplate> WebAccountMonitor::s_constructorTemplate;

  v8::Local<v8::Value> WrapWebAccountMonitor(::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(WebAccountMonitor::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ UnwrapWebAccountMonitor(Local<Value> value) {
     return WebAccountMonitor::Unwrap<WebAccountMonitor>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitWebAccountMonitor(Local<Object> exports) {
    WebAccountMonitor::Init(exports);
  }

  class WebAuthenticationCoreManager : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("WebAuthenticationCoreManager").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;





        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);

        Nan::SetMethod(constructor, "createWebAccountMonitor", CreateWebAccountMonitor);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(FindAllAccountsAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("findAllAccountsAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(FindSystemAccountProviderAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("findSystemAccountProviderAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(FindAccountProviderAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("findAccountProviderAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(GetTokenSilentlyAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("getTokenSilentlyAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(RequestTokenAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("requestTokenAsync").ToLocalChecked(), func);
        func = Nan::GetFunction(Nan::New<FunctionTemplate>(FindAccountAsync)).ToLocalChecked();
        Nan::Set(constructor, Nan::New<String>("findAccountAsync").ToLocalChecked(), func);


        Nan::Set(exports, Nan::New<String>("WebAuthenticationCoreManager").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      WebAuthenticationCoreManager(::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^>(info[0])) {
        try {
          winRtInstance = (::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      WebAuthenticationCoreManager *wrapperInstance = new WebAuthenticationCoreManager(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^ winRtInstance;
      try {
        winRtInstance = (::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapWebAuthenticationCoreManager(winRtInstance));
    }




    static void FindAllAccountsAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      ::Windows::Foundation::IAsyncOperation<::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^>^ op;


      if (info.Length() == 2
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccountProvider^>(info[0]))
      {
        try
        {
          ::Windows::Security::Credentials::WebAccountProvider^ arg0 = dynamic_cast<::Windows::Security::Credentials::WebAccountProvider^>(NodeRT::Utils::GetObjectInstance(info[0]));
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::FindAllAccountsAsync(arg0);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else if (info.Length() == 3
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccountProvider^>(info[0])
          && info[1]->IsString())
      {
        try
        {
          ::Windows::Security::Credentials::WebAccountProvider^ arg0 = dynamic_cast<::Windows::Security::Credentials::WebAccountProvider^>(NodeRT::Utils::GetObjectInstance(info[0]));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::FindAllAccountsAsync(arg0,arg1);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }

      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(info[info.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<::Windows::Security::Authentication::Web::Core::FindAllAccountsResult^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapFindAllAccountsResult(result);
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }

    static void FindSystemAccountProviderAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      ::Windows::Foundation::IAsyncOperation<::Windows::Security::Credentials::WebAccountProvider^>^ op;


      if (info.Length() == 2
          && info[0]->IsString())
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::FindSystemAccountProviderAsync(arg0);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else if (info.Length() == 3
          && info[0]->IsString()
          && info[1]->IsString())
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::FindSystemAccountProviderAsync(arg0,arg1);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else if (info.Length() == 4
          && info[0]->IsString()
          && info[1]->IsString()
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::User^>(info[2]))
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
          ::Windows::System::User^ arg2 = dynamic_cast<::Windows::System::User^>(NodeRT::Utils::GetObjectInstance(info[2]));
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::FindSystemAccountProviderAsync(arg0,arg1,arg2);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }

      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(info[info.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<::Windows::Security::Credentials::WebAccountProvider^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = NodeRT::Utils::CreateExternalWinRTObject("Windows.Security.Credentials", "WebAccountProvider", result);
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }

    static void FindAccountProviderAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      ::Windows::Foundation::IAsyncOperation<::Windows::Security::Credentials::WebAccountProvider^>^ op;


      if (info.Length() == 4
          && info[0]->IsString()
          && info[1]->IsString()
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::User^>(info[2]))
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
          ::Windows::System::User^ arg2 = dynamic_cast<::Windows::System::User^>(NodeRT::Utils::GetObjectInstance(info[2]));
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::FindAccountProviderAsync(arg0,arg1,arg2);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else if (info.Length() == 2
          && info[0]->IsString())
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::FindAccountProviderAsync(arg0);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else if (info.Length() == 3
          && info[0]->IsString()
          && info[1]->IsString())
      {
        try
        {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::FindAccountProviderAsync(arg0,arg1);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }

      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(info[info.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<::Windows::Security::Credentials::WebAccountProvider^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = NodeRT::Utils::CreateExternalWinRTObject("Windows.Security.Credentials", "WebAccountProvider", result);
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }

    static void GetTokenSilentlyAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      ::Windows::Foundation::IAsyncOperation<::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^>^ op;


      if (info.Length() == 2
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info[0]))
      {
        try
        {
          ::Windows::Security::Authentication::Web::Core::WebTokenRequest^ arg0 = UnwrapWebTokenRequest(info[0]);
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::GetTokenSilentlyAsync(arg0);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else if (info.Length() == 3
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info[0])
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccount^>(info[1]))
      {
        try
        {
          ::Windows::Security::Authentication::Web::Core::WebTokenRequest^ arg0 = UnwrapWebTokenRequest(info[0]);
          ::Windows::Security::Credentials::WebAccount^ arg1 = dynamic_cast<::Windows::Security::Credentials::WebAccount^>(NodeRT::Utils::GetObjectInstance(info[1]));
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::GetTokenSilentlyAsync(arg0,arg1);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }

      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(info[info.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapWebTokenRequestResult(result);
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }

    static void RequestTokenAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      ::Windows::Foundation::IAsyncOperation<::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^>^ op;


      if (info.Length() == 2
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info[0]))
      {
        try
        {
          ::Windows::Security::Authentication::Web::Core::WebTokenRequest^ arg0 = UnwrapWebTokenRequest(info[0]);
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::RequestTokenAsync(arg0);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
      else if (info.Length() == 3
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequest^>(info[0])
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccount^>(info[1]))
      {
        try
        {
          ::Windows::Security::Authentication::Web::Core::WebTokenRequest^ arg0 = UnwrapWebTokenRequest(info[0]);
          ::Windows::Security::Credentials::WebAccount^ arg1 = dynamic_cast<::Windows::Security::Credentials::WebAccount^>(NodeRT::Utils::GetObjectInstance(info[1]));
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::RequestTokenAsync(arg0,arg1);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }

      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(info[info.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = WrapWebTokenRequestResult(result);
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }

    static void FindAccountAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      ::Windows::Foundation::IAsyncOperation<::Windows::Security::Credentials::WebAccount^>^ op;


      if (info.Length() == 3
          && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccountProvider^>(info[0])
          && info[1]->IsString())
      {
        try
        {
          ::Windows::Security::Credentials::WebAccountProvider^ arg0 = dynamic_cast<::Windows::Security::Credentials::WebAccountProvider^>(NodeRT::Utils::GetObjectInstance(info[0]));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
            
          op = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::FindAccountAsync(arg0,arg1);
        } catch (Platform::Exception ^exception) {
            NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
            return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }

      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(info[info.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<::Windows::Security::Credentials::WebAccount^> t)
      {
        try {
          auto result = t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [result](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> error;
            Local<Value> arg1;
            {
              TryCatch tryCatch;
              arg1 = NodeRT::Utils::CreateExternalWinRTObject("Windows.Security.Credentials", "WebAccount", result);
              if (tryCatch.HasCaught())
              {
                error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked();
              }
              else
              {
                error = Undefined();
              }
              if (arg1.IsEmpty()) arg1 = Undefined();
            }
            Local<Value> args[] = {error, arg1};


            invokeCallback(_countof(args), args);
          });
        }
        catch (Platform::Exception^ exception)
        {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {

            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }


    static void CreateWebAccountMonitor(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (info.Length() == 1
        && (NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Collections::IIterable<::Windows::Security::Credentials::WebAccount^>^>(info[0]) || info[0]->IsArray()))
      {
        try
        {
          ::Windows::Foundation::Collections::IIterable<::Windows::Security::Credentials::WebAccount^>^ arg0 = 
            [] (v8::Local<v8::Value> value) -> ::Windows::Foundation::Collections::IIterable<::Windows::Security::Credentials::WebAccount^>^
            {
              if (value->IsArray())
              {
                return NodeRT::Collections::JsArrayToWinrtVector<::Windows::Security::Credentials::WebAccount^>(value.As<Array>(), 
                 [](Local<Value> value) -> bool {
                   return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccount^>(value);
                 },
                 [](Local<Value> value) -> ::Windows::Security::Credentials::WebAccount^ {
                   return dynamic_cast<::Windows::Security::Credentials::WebAccount^>(NodeRT::Utils::GetObjectInstance(value));
                 }
                );
              }
              else
              {
                return dynamic_cast<::Windows::Foundation::Collections::IIterable<::Windows::Security::Credentials::WebAccount^>^>(NodeRT::Utils::GetObjectInstance(value));
              }
            } (info[0]);
          
          ::Windows::Security::Authentication::Web::Core::WebAccountMonitor^ result;
          result = ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager::CreateWebAccountMonitor(arg0);
          info.GetReturnValue().Set(WrapWebAccountMonitor(result));
          return;
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else  {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }
    }



    private:
      ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapWebAuthenticationCoreManager(::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^ wintRtInstance);
      friend ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^ UnwrapWebAuthenticationCoreManager(Local<Value> value);
  };

  Persistent<FunctionTemplate> WebAuthenticationCoreManager::s_constructorTemplate;

  v8::Local<v8::Value> WrapWebAuthenticationCoreManager(::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(WebAuthenticationCoreManager::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Security::Authentication::Web::Core::WebAuthenticationCoreManager^ UnwrapWebAuthenticationCoreManager(Local<Value> value) {
     return WebAuthenticationCoreManager::Unwrap<WebAuthenticationCoreManager>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitWebAuthenticationCoreManager(Local<Object> exports) {
    WebAuthenticationCoreManager::Init(exports);
  }

  class WebProviderError : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("WebProviderError").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("errorCode").ToLocalChecked(), ErrorCodeGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("errorMessage").ToLocalChecked(), ErrorMessageGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("properties").ToLocalChecked(), PropertiesGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("WebProviderError").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      WebProviderError(::Windows::Security::Authentication::Web::Core::WebProviderError^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Security::Authentication::Web::Core::WebProviderError^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebProviderError^>(info[0])) {
        try {
          winRtInstance = (::Windows::Security::Authentication::Web::Core::WebProviderError^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 2
        && info[0]->IsUint32()
        && info[1]->IsString())
      {
        try {
          unsigned int arg0 = static_cast<unsigned int>(Nan::To<uint32_t>(info[0]).FromMaybe(0));
          Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[1])));
          
          winRtInstance = ref new ::Windows::Security::Authentication::Web::Core::WebProviderError(arg0,arg1);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      WebProviderError *wrapperInstance = new WebProviderError(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebProviderError^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Security::Authentication::Web::Core::WebProviderError^ winRtInstance;
      try {
        winRtInstance = (::Windows::Security::Authentication::Web::Core::WebProviderError^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapWebProviderError(winRtInstance));
    }





    static void ErrorCodeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebProviderError^>(info.This())) {
        return;
      }

      WebProviderError *wrapper = WebProviderError::Unwrap<WebProviderError>(info.This());

      try  {
        unsigned int result = wrapper->_instance->ErrorCode;
        info.GetReturnValue().Set(Nan::New<Integer>(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ErrorMessageGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebProviderError^>(info.This())) {
        return;
      }

      WebProviderError *wrapper = WebProviderError::Unwrap<WebProviderError>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->ErrorMessage;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void PropertiesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebProviderError^>(info.This())) {
        return;
      }

      WebProviderError *wrapper = WebProviderError::Unwrap<WebProviderError>(info.This());

      try  {
        ::Windows::Foundation::Collections::IMap<::Platform::String^, ::Platform::String^>^ result = wrapper->_instance->Properties;
        info.GetReturnValue().Set(NodeRT::Collections::MapWrapper<::Platform::String^,::Platform::String^>::CreateMapWrapper(result, 
            [](::Platform::String^ val) -> Local<Value> {
              return NodeRT::Utils::NewString(val->Data());
            },
            [](Local<Value> value) -> bool {
              return value->IsString();
            },
            [](Local<Value> value) -> ::Platform::String^ {
              return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), value)));
            },
            [](::Platform::String^ val) -> Local<Value> {
              return NodeRT::Utils::NewString(val->Data());
            },
            [](Local<Value> value) -> bool {
              return value->IsString();
            },
            [](Local<Value> value) -> ::Platform::String^ {
              return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), value)));
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Security::Authentication::Web::Core::WebProviderError^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapWebProviderError(::Windows::Security::Authentication::Web::Core::WebProviderError^ wintRtInstance);
      friend ::Windows::Security::Authentication::Web::Core::WebProviderError^ UnwrapWebProviderError(Local<Value> value);
  };

  Persistent<FunctionTemplate> WebProviderError::s_constructorTemplate;

  v8::Local<v8::Value> WrapWebProviderError(::Windows::Security::Authentication::Web::Core::WebProviderError^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(WebProviderError::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Security::Authentication::Web::Core::WebProviderError^ UnwrapWebProviderError(Local<Value> value) {
     return WebProviderError::Unwrap<WebProviderError>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitWebProviderError(Local<Object> exports) {
    WebProviderError::Init(exports);
  }

  class WebTokenResponse : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("WebTokenResponse").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);





          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("properties").ToLocalChecked(), PropertiesGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("providerError").ToLocalChecked(), ProviderErrorGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("token").ToLocalChecked(), TokenGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("webAccount").ToLocalChecked(), WebAccountGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("WebTokenResponse").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      WebTokenResponse(::Windows::Security::Authentication::Web::Core::WebTokenResponse^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Security::Authentication::Web::Core::WebTokenResponse^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenResponse^>(info[0])) {
        try {
          winRtInstance = (::Windows::Security::Authentication::Web::Core::WebTokenResponse^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 1
        && info[0]->IsString())
      {
        try {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
          
          winRtInstance = ref new ::Windows::Security::Authentication::Web::Core::WebTokenResponse(arg0);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 2
        && info[0]->IsString()
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccount^>(info[1]))
      {
        try {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
          ::Windows::Security::Credentials::WebAccount^ arg1 = dynamic_cast<::Windows::Security::Credentials::WebAccount^>(NodeRT::Utils::GetObjectInstance(info[1]));
          
          winRtInstance = ref new ::Windows::Security::Authentication::Web::Core::WebTokenResponse(arg0,arg1);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 3
        && info[0]->IsString()
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Credentials::WebAccount^>(info[1])
        && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebProviderError^>(info[2]))
      {
        try {
          Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), info[0])));
          ::Windows::Security::Credentials::WebAccount^ arg1 = dynamic_cast<::Windows::Security::Credentials::WebAccount^>(NodeRT::Utils::GetObjectInstance(info[1]));
          ::Windows::Security::Authentication::Web::Core::WebProviderError^ arg2 = UnwrapWebProviderError(info[2]);
          
          winRtInstance = ref new ::Windows::Security::Authentication::Web::Core::WebTokenResponse(arg0,arg1,arg2);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
      else if (info.Length() == 0)
      {
        try {
          winRtInstance = ref new ::Windows::Security::Authentication::Web::Core::WebTokenResponse();
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      WebTokenResponse *wrapperInstance = new WebTokenResponse(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenResponse^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Security::Authentication::Web::Core::WebTokenResponse^ winRtInstance;
      try {
        winRtInstance = (::Windows::Security::Authentication::Web::Core::WebTokenResponse^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapWebTokenResponse(winRtInstance));
    }





    static void PropertiesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenResponse^>(info.This())) {
        return;
      }

      WebTokenResponse *wrapper = WebTokenResponse::Unwrap<WebTokenResponse>(info.This());

      try  {
        ::Windows::Foundation::Collections::IMap<::Platform::String^, ::Platform::String^>^ result = wrapper->_instance->Properties;
        info.GetReturnValue().Set(NodeRT::Collections::MapWrapper<::Platform::String^,::Platform::String^>::CreateMapWrapper(result, 
            [](::Platform::String^ val) -> Local<Value> {
              return NodeRT::Utils::NewString(val->Data());
            },
            [](Local<Value> value) -> bool {
              return value->IsString();
            },
            [](Local<Value> value) -> ::Platform::String^ {
              return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), value)));
            },
            [](::Platform::String^ val) -> Local<Value> {
              return NodeRT::Utils::NewString(val->Data());
            },
            [](Local<Value> value) -> bool {
              return value->IsString();
            },
            [](Local<Value> value) -> ::Platform::String^ {
              return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(v8::Isolate::GetCurrent(), value)));
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ProviderErrorGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenResponse^>(info.This())) {
        return;
      }

      WebTokenResponse *wrapper = WebTokenResponse::Unwrap<WebTokenResponse>(info.This());

      try  {
        ::Windows::Security::Authentication::Web::Core::WebProviderError^ result = wrapper->_instance->ProviderError;
        info.GetReturnValue().Set(WrapWebProviderError(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void TokenGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenResponse^>(info.This())) {
        return;
      }

      WebTokenResponse *wrapper = WebTokenResponse::Unwrap<WebTokenResponse>(info.This());

      try  {
        Platform::String^ result = wrapper->_instance->Token;
        info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data()));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void WebAccountGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenResponse^>(info.This())) {
        return;
      }

      WebTokenResponse *wrapper = WebTokenResponse::Unwrap<WebTokenResponse>(info.This());

      try  {
        ::Windows::Security::Credentials::WebAccount^ result = wrapper->_instance->WebAccount;
        info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Security.Credentials", "WebAccount", result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Security::Authentication::Web::Core::WebTokenResponse^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapWebTokenResponse(::Windows::Security::Authentication::Web::Core::WebTokenResponse^ wintRtInstance);
      friend ::Windows::Security::Authentication::Web::Core::WebTokenResponse^ UnwrapWebTokenResponse(Local<Value> value);
  };

  Persistent<FunctionTemplate> WebTokenResponse::s_constructorTemplate;

  v8::Local<v8::Value> WrapWebTokenResponse(::Windows::Security::Authentication::Web::Core::WebTokenResponse^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(WebTokenResponse::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Security::Authentication::Web::Core::WebTokenResponse^ UnwrapWebTokenResponse(Local<Value> value) {
     return WebTokenResponse::Unwrap<WebTokenResponse>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitWebTokenResponse(Local<Object> exports) {
    WebTokenResponse::Init(exports);
  }

  class WebTokenRequestResult : public WrapperBase {
    public:
      
      static void Init(const Local<Object> exports) {
        HandleScope scope;

        Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New);
        s_constructorTemplate.Reset(localRef);
        localRef->SetClassName(Nan::New<String>("WebTokenRequestResult").ToLocalChecked());
        localRef->InstanceTemplate()->SetInternalFieldCount(1);

        Local<Function> func;
        Local<FunctionTemplate> funcTemplate;


          
            Nan::SetPrototypeMethod(localRef, "invalidateCacheAsync", InvalidateCacheAsync);
          


          
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("responseData").ToLocalChecked(), ResponseDataGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("responseError").ToLocalChecked(), ResponseErrorGetter);
            Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("responseStatus").ToLocalChecked(), ResponseStatusGetter);

        Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked();
        Nan::SetMethod(constructor, "castFrom", CastFrom);



        Nan::Set(exports, Nan::New<String>("WebTokenRequestResult").ToLocalChecked(), constructor);
      }

      virtual ::Platform::Object^ GetObjectInstance() const override {
        return _instance;
      }

    private:

      WebTokenRequestResult(::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^ instance) {
        _instance = instance;
      }

      
    static void New(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate);

      // in case the constructor was called without the new operator
      if (!localRef->HasInstance(info.This())) {
        if (info.Length() > 0) {
          std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]);

          Local<Value> *argsPtr = constructorArgs.get();
          for (int i = 0; i < info.Length(); i++) {
            argsPtr[i] = info[i];
          }

          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get());
          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        } else {
          MaybeLocal<Object> res = Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr);

          if (res.IsEmpty()) {
            return;
          }

          info.GetReturnValue().Set(res.ToLocalChecked());
          return;
        }
      }

      ::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^ winRtInstance;


      if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) &&
        NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^>(info[0])) {
        try {
          winRtInstance = (::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^) NodeRT::Utils::GetObjectInstance(info[0]);
        } catch (Platform::Exception ^exception) {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found")));
        return;
      }

      NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True());

      WebTokenRequestResult *wrapperInstance = new WebTokenRequestResult(winRtInstance);
      wrapperInstance->Wrap(info.This());

      info.GetReturnValue().Set(info.This());
    }


      
    static void CastFrom(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;
      if (info.Length() < 1 || !NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^>(info[0])) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no object provided, or given object could not be casted to requested type")));
        return;
      }

      ::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^ winRtInstance;
      try {
        winRtInstance = (::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^) NodeRT::Utils::GetObjectInstance(info[0]);
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }

      info.GetReturnValue().Set(WrapWebTokenRequestResult(winRtInstance));
    }

    static void InvalidateCacheAsync(Nan::NAN_METHOD_ARGS_TYPE info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^>(info.This())) {
        return;
      }

      if (info.Length() == 0 || !info[info.Length() -1]->IsFunction()) {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: No callback was given")));
        return;
      }

      WebTokenRequestResult *wrapper = WebTokenRequestResult::Unwrap<WebTokenRequestResult>(info.This());

      ::Windows::Foundation::IAsyncAction^ op;


      if (info.Length() == 1)
      {
        try
        {
          op = wrapper->_instance->InvalidateCacheAsync();
        }
        catch (Platform::Exception ^exception)
        {
          NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
          return;
        }
      }
 else {
        Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found")));
        return;
      }

      auto opTask = create_task(op);
      uv_async_t* asyncToken = NodeUtils::Async::GetAsyncToken(info[info.Length() -1].As<Function>());

      opTask.then( [asyncToken] (task<void> t) {
        try {
          t.get();
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [](NodeUtils::InvokeCallbackDelegate invokeCallback) {


            Local<Value> args[] = {Undefined()};


            invokeCallback(_countof(args), args);
          });
        } catch (Platform::Exception^ exception) {
          NodeUtils::Async::RunCallbackOnMain(asyncToken, [exception](NodeUtils::InvokeCallbackDelegate invokeCallback) {
            Local<Value> error = NodeRT::Utils::WinRtExceptionToJsError(exception);

            Local<Value> args[] = {error};
            invokeCallback(_countof(args), args);
          });
        }
      });
    }




    static void ResponseDataGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^>(info.This())) {
        return;
      }

      WebTokenRequestResult *wrapper = WebTokenRequestResult::Unwrap<WebTokenRequestResult>(info.This());

      try  {
        ::Windows::Foundation::Collections::IVectorView<::Windows::Security::Authentication::Web::Core::WebTokenResponse^>^ result = wrapper->_instance->ResponseData;
        info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::Security::Authentication::Web::Core::WebTokenResponse^>::CreateVectorViewWrapper(result, 
            [](::Windows::Security::Authentication::Web::Core::WebTokenResponse^ val) -> Local<Value> {
              return WrapWebTokenResponse(val);
            },
            [](Local<Value> value) -> bool {
              return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenResponse^>(value);
            },
            [](Local<Value> value) -> ::Windows::Security::Authentication::Web::Core::WebTokenResponse^ {
              return UnwrapWebTokenResponse(value);
            }
          ));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ResponseErrorGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^>(info.This())) {
        return;
      }

      WebTokenRequestResult *wrapper = WebTokenRequestResult::Unwrap<WebTokenRequestResult>(info.This());

      try  {
        ::Windows::Security::Authentication::Web::Core::WebProviderError^ result = wrapper->_instance->ResponseError;
        info.GetReturnValue().Set(WrapWebProviderError(result));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      
    static void ResponseStatusGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
      HandleScope scope;

      if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^>(info.This())) {
        return;
      }

      WebTokenRequestResult *wrapper = WebTokenRequestResult::Unwrap<WebTokenRequestResult>(info.This());

      try  {
        ::Windows::Security::Authentication::Web::Core::WebTokenRequestStatus result = wrapper->_instance->ResponseStatus;
        info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result)));
        return;
      } catch (Platform::Exception ^exception) {
        NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
        return;
      }
    }
      


    private:
      ::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^ _instance;
      static Persistent<FunctionTemplate> s_constructorTemplate;

      friend v8::Local<v8::Value> WrapWebTokenRequestResult(::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^ wintRtInstance);
      friend ::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^ UnwrapWebTokenRequestResult(Local<Value> value);
  };

  Persistent<FunctionTemplate> WebTokenRequestResult::s_constructorTemplate;

  v8::Local<v8::Value> WrapWebTokenRequestResult(::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^ winRtInstance) {
    EscapableHandleScope scope;

    if (winRtInstance == nullptr) {
      return scope.Escape(Undefined());
    }

    Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance);
    Local<Value> args[] = {opaqueWrapper};
    Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(WebTokenRequestResult::s_constructorTemplate);
    return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked());
  }

  ::Windows::Security::Authentication::Web::Core::WebTokenRequestResult^ UnwrapWebTokenRequestResult(Local<Value> value) {
     return WebTokenRequestResult::Unwrap<WebTokenRequestResult>(Nan::To<Object>(value).ToLocalChecked())->_instance;
  }

  void InitWebTokenRequestResult(Local<Object> exports) {
    WebTokenRequestResult::Init(exports);
  }


} } } } } } 

NAN_MODULE_INIT(init) {
  // We ignore failures for now since it probably means that
  // the initialization already happened for STA, and that's cool

  CoInitializeEx(nullptr, COINIT_MULTITHREADED);

  /*
  if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) {
    Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"error in CoInitializeEx()")));
    return;
  }
  */

      NodeRT::Windows::Security::Authentication::Web::Core::InitWebTokenRequestPromptTypeEnum(target);
      NodeRT::Windows::Security::Authentication::Web::Core::InitFindAllWebAccountsStatusEnum(target);
      NodeRT::Windows::Security::Authentication::Web::Core::InitWebTokenRequestStatusEnum(target);
      NodeRT::Windows::Security::Authentication::Web::Core::InitWebTokenRequest(target);
      NodeRT::Windows::Security::Authentication::Web::Core::InitWebAccountEventArgs(target);
      NodeRT::Windows::Security::Authentication::Web::Core::InitFindAllAccountsResult(target);
      NodeRT::Windows::Security::Authentication::Web::Core::InitWebAccountMonitor(target);
      NodeRT::Windows::Security::Authentication::Web::Core::InitWebAuthenticationCoreManager(target);
      NodeRT::Windows::Security::Authentication::Web::Core::InitWebProviderError(target);
      NodeRT::Windows::Security::Authentication::Web::Core::InitWebTokenResponse(target);
      NodeRT::Windows::Security::Authentication::Web::Core::InitWebTokenRequestResult(target);


  NodeRT::Utils::RegisterNameSpace("Windows.Security.Authentication.Web.Core", target);
}



NODE_MODULE(binding, init)
