napi.h 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784
  1. #ifndef SRC_NAPI_H_
  2. #define SRC_NAPI_H_
  3. #include "node_api.h"
  4. #include <functional>
  5. #include <initializer_list>
  6. #include <string>
  7. #include <vector>
  8. // VS2015 RTM has bugs with constexpr, so require min of VS2015 Update 3 (known good version)
  9. #if !defined(_MSC_VER) || _MSC_FULL_VER >= 190024210
  10. #define NAPI_HAS_CONSTEXPR 1
  11. #endif
  12. // VS2013 does not support char16_t literal strings, so we'll work around it using wchar_t strings
  13. // and casting them. This is safe as long as the character sizes are the same.
  14. #if defined(_MSC_VER) && _MSC_VER <= 1800
  15. static_assert(sizeof(char16_t) == sizeof(wchar_t), "Size mismatch between char16_t and wchar_t");
  16. #define NAPI_WIDE_TEXT(x) reinterpret_cast<char16_t*>(L ## x)
  17. #else
  18. #define NAPI_WIDE_TEXT(x) u ## x
  19. #endif
  20. // If C++ exceptions are not explicitly enabled or disabled, enable them
  21. // if exceptions were enabled in the compiler settings.
  22. #if !defined(NAPI_CPP_EXCEPTIONS) && !defined(NAPI_DISABLE_CPP_EXCEPTIONS)
  23. #if defined(_CPPUNWIND) || defined (__EXCEPTIONS)
  24. #define NAPI_CPP_EXCEPTIONS
  25. #else
  26. #error Exception support not detected. \
  27. Define either NAPI_CPP_EXCEPTIONS or NAPI_DISABLE_CPP_EXCEPTIONS.
  28. #endif
  29. #endif
  30. #ifdef _NOEXCEPT
  31. #define NAPI_NOEXCEPT _NOEXCEPT
  32. #else
  33. #define NAPI_NOEXCEPT noexcept
  34. #endif
  35. ////////////////////////////////////////////////////////////////////////////////
  36. /// N-API C++ Wrapper Classes
  37. ///
  38. /// These classes wrap the "N-API" ABI-stable C APIs for Node.js, providing a
  39. /// C++ object model and C++ exception-handling semantics with low overhead.
  40. /// The wrappers are all header-only so that they do not affect the ABI.
  41. ////////////////////////////////////////////////////////////////////////////////
  42. namespace Napi {
  43. // Forward declarations
  44. class Env;
  45. class Value;
  46. class Boolean;
  47. class Number;
  48. // currently experimental guard with version of NAPI_VERSION that it is
  49. // released in once it is no longer experimental
  50. #if (NAPI_VERSION > 2147483646)
  51. class BigInt;
  52. #endif // NAPI_EXPERIMENTAL
  53. class String;
  54. class Object;
  55. class Array;
  56. class Function;
  57. template <typename T> class Buffer;
  58. class Error;
  59. class PropertyDescriptor;
  60. class CallbackInfo;
  61. template <typename T> class Reference;
  62. class TypedArray;
  63. template <typename T> class TypedArrayOf;
  64. typedef TypedArrayOf<int8_t> Int8Array; ///< Typed-array of signed 8-bit integers
  65. typedef TypedArrayOf<uint8_t> Uint8Array; ///< Typed-array of unsigned 8-bit integers
  66. typedef TypedArrayOf<int16_t> Int16Array; ///< Typed-array of signed 16-bit integers
  67. typedef TypedArrayOf<uint16_t> Uint16Array; ///< Typed-array of unsigned 16-bit integers
  68. typedef TypedArrayOf<int32_t> Int32Array; ///< Typed-array of signed 32-bit integers
  69. typedef TypedArrayOf<uint32_t> Uint32Array; ///< Typed-array of unsigned 32-bit integers
  70. typedef TypedArrayOf<float> Float32Array; ///< Typed-array of 32-bit floating-point values
  71. typedef TypedArrayOf<double> Float64Array; ///< Typed-array of 64-bit floating-point values
  72. // currently experimental guard with version of NAPI_VERSION that it is
  73. // released in once it is no longer experimental
  74. #if (NAPI_VERSION > 2147483646)
  75. typedef TypedArrayOf<int64_t> BigInt64Array; ///< Typed array of signed 64-bit integers
  76. typedef TypedArrayOf<uint64_t> BigUint64Array; ///< Typed array of unsigned 64-bit integers
  77. #endif // NAPI_EXPERIMENTAL
  78. /// Defines the signature of a N-API C++ module's registration callback (init) function.
  79. typedef Object (*ModuleRegisterCallback)(Env env, Object exports);
  80. class MemoryManagement;
  81. /// Environment for N-API values and operations.
  82. ///
  83. /// All N-API values and operations must be associated with an environment. An environment
  84. /// instance is always provided to callback functions; that environment must then be used for any
  85. /// creation of N-API values or other N-API operations within the callback. (Many methods infer
  86. /// the environment from the `this` instance that the method is called on.)
  87. ///
  88. /// In the future, multiple environments per process may be supported, although current
  89. /// implementations only support one environment per process.
  90. ///
  91. /// In the V8 JavaScript engine, a N-API environment approximately corresponds to an Isolate.
  92. class Env {
  93. public:
  94. Env(napi_env env);
  95. operator napi_env() const;
  96. Object Global() const;
  97. Value Undefined() const;
  98. Value Null() const;
  99. bool IsExceptionPending() const;
  100. Error GetAndClearPendingException();
  101. private:
  102. napi_env _env;
  103. };
  104. /// A JavaScript value of unknown type.
  105. ///
  106. /// For type-specific operations, convert to one of the Value subclasses using a `To*` or `As()`
  107. /// method. The `To*` methods do type coercion; the `As()` method does not.
  108. ///
  109. /// Napi::Value value = ...
  110. /// if (!value.IsString()) throw Napi::TypeError::New(env, "Invalid arg...");
  111. /// Napi::String str = value.As<Napi::String>(); // Cast to a string value
  112. ///
  113. /// Napi::Value anotherValue = ...
  114. /// bool isTruthy = anotherValue.ToBoolean(); // Coerce to a boolean value
  115. class Value {
  116. public:
  117. Value(); ///< Creates a new _empty_ Value instance.
  118. Value(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
  119. /// Creates a JS value from a C++ primitive.
  120. ///
  121. /// `value` may be any of:
  122. /// - bool
  123. /// - Any integer type
  124. /// - Any floating point type
  125. /// - const char* (encoded using UTF-8, null-terminated)
  126. /// - const char16_t* (encoded using UTF-16-LE, null-terminated)
  127. /// - std::string (encoded using UTF-8)
  128. /// - std::u16string
  129. /// - napi::Value
  130. /// - napi_value
  131. template <typename T>
  132. static Value From(napi_env env, const T& value);
  133. /// Converts to a N-API value primitive.
  134. ///
  135. /// If the instance is _empty_, this returns `nullptr`.
  136. operator napi_value() const;
  137. /// Tests if this value strictly equals another value.
  138. bool operator ==(const Value& other) const;
  139. /// Tests if this value does not strictly equal another value.
  140. bool operator !=(const Value& other) const;
  141. /// Tests if this value strictly equals another value.
  142. bool StrictEquals(const Value& other) const;
  143. /// Gets the environment the value is associated with.
  144. Napi::Env Env() const;
  145. /// Checks if the value is empty (uninitialized).
  146. ///
  147. /// An empty value is invalid, and most attempts to perform an operation on an empty value
  148. /// will result in an exception. Note an empty value is distinct from JavaScript `null` or
  149. /// `undefined`, which are valid values.
  150. ///
  151. /// When C++ exceptions are disabled at compile time, a method with a `Value` return type may
  152. /// return an empty value to indicate a pending exception. So when not using C++ exceptions,
  153. /// callers should check whether the value is empty before attempting to use it.
  154. bool IsEmpty() const;
  155. napi_valuetype Type() const; ///< Gets the type of the value.
  156. bool IsUndefined() const; ///< Tests if a value is an undefined JavaScript value.
  157. bool IsNull() const; ///< Tests if a value is a null JavaScript value.
  158. bool IsBoolean() const; ///< Tests if a value is a JavaScript boolean.
  159. bool IsNumber() const; ///< Tests if a value is a JavaScript number.
  160. // currently experimental guard with version of NAPI_VERSION that it is
  161. // released in once it is no longer experimental
  162. #if (NAPI_VERSION > 2147483646)
  163. bool IsBigInt() const; ///< Tests if a value is a JavaScript bigint.
  164. #endif // NAPI_EXPERIMENTAL
  165. bool IsString() const; ///< Tests if a value is a JavaScript string.
  166. bool IsSymbol() const; ///< Tests if a value is a JavaScript symbol.
  167. bool IsArray() const; ///< Tests if a value is a JavaScript array.
  168. bool IsArrayBuffer() const; ///< Tests if a value is a JavaScript array buffer.
  169. bool IsTypedArray() const; ///< Tests if a value is a JavaScript typed array.
  170. bool IsObject() const; ///< Tests if a value is a JavaScript object.
  171. bool IsFunction() const; ///< Tests if a value is a JavaScript function.
  172. bool IsPromise() const; ///< Tests if a value is a JavaScript promise.
  173. bool IsDataView() const; ///< Tests if a value is a JavaScript data view.
  174. bool IsBuffer() const; ///< Tests if a value is a Node buffer.
  175. bool IsExternal() const; ///< Tests if a value is a pointer to external data.
  176. /// Casts to another type of `Napi::Value`, when the actual type is known or assumed.
  177. ///
  178. /// This conversion does NOT coerce the type. Calling any methods inappropriate for the actual
  179. /// value type will throw `Napi::Error`.
  180. template <typename T> T As() const;
  181. Boolean ToBoolean() const; ///< Coerces a value to a JavaScript boolean.
  182. Number ToNumber() const; ///< Coerces a value to a JavaScript number.
  183. String ToString() const; ///< Coerces a value to a JavaScript string.
  184. Object ToObject() const; ///< Coerces a value to a JavaScript object.
  185. protected:
  186. /// !cond INTERNAL
  187. napi_env _env;
  188. napi_value _value;
  189. /// !endcond
  190. };
  191. /// A JavaScript boolean value.
  192. class Boolean : public Value {
  193. public:
  194. static Boolean New(
  195. napi_env env, ///< N-API environment
  196. bool value ///< Boolean value
  197. );
  198. Boolean(); ///< Creates a new _empty_ Boolean instance.
  199. Boolean(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
  200. operator bool() const; ///< Converts a Boolean value to a boolean primitive.
  201. bool Value() const; ///< Converts a Boolean value to a boolean primitive.
  202. };
  203. /// A JavaScript number value.
  204. class Number : public Value {
  205. public:
  206. static Number New(
  207. napi_env env, ///< N-API environment
  208. double value ///< Number value
  209. );
  210. Number(); ///< Creates a new _empty_ Number instance.
  211. Number(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
  212. operator int32_t() const; ///< Converts a Number value to a 32-bit signed integer value.
  213. operator uint32_t() const; ///< Converts a Number value to a 32-bit unsigned integer value.
  214. operator int64_t() const; ///< Converts a Number value to a 64-bit signed integer value.
  215. operator float() const; ///< Converts a Number value to a 32-bit floating-point value.
  216. operator double() const; ///< Converts a Number value to a 64-bit floating-point value.
  217. int32_t Int32Value() const; ///< Converts a Number value to a 32-bit signed integer value.
  218. uint32_t Uint32Value() const; ///< Converts a Number value to a 32-bit unsigned integer value.
  219. int64_t Int64Value() const; ///< Converts a Number value to a 64-bit signed integer value.
  220. float FloatValue() const; ///< Converts a Number value to a 32-bit floating-point value.
  221. double DoubleValue() const; ///< Converts a Number value to a 64-bit floating-point value.
  222. };
  223. // currently experimental guard with version of NAPI_VERSION that it is
  224. // released in once it is no longer experimental
  225. #if (NAPI_VERSION > 2147483646)
  226. /// A JavaScript bigint value.
  227. class BigInt : public Value {
  228. public:
  229. static BigInt New(
  230. napi_env env, ///< N-API environment
  231. int64_t value ///< Number value
  232. );
  233. static BigInt New(
  234. napi_env env, ///< N-API environment
  235. uint64_t value ///< Number value
  236. );
  237. /// Creates a new BigInt object using a specified sign bit and a
  238. /// specified list of digits/words.
  239. /// The resulting number is calculated as:
  240. /// (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...)
  241. static BigInt New(
  242. napi_env env, ///< N-API environment
  243. int sign_bit, ///< Sign bit. 1 if negative.
  244. size_t word_count, ///< Number of words in array
  245. const uint64_t* words ///< Array of words
  246. );
  247. BigInt(); ///< Creates a new _empty_ BigInt instance.
  248. BigInt(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
  249. int64_t Int64Value(bool* lossless) const; ///< Converts a BigInt value to a 64-bit signed integer value.
  250. uint64_t Uint64Value(bool* lossless) const; ///< Converts a BigInt value to a 64-bit unsigned integer value.
  251. size_t WordCount() const; ///< The number of 64-bit words needed to store the result of ToWords().
  252. /// Writes the contents of this BigInt to a specified memory location.
  253. /// `sign_bit` must be provided and will be set to 1 if this BigInt is negative.
  254. /// `*word_count` has to be initialized to the length of the `words` array.
  255. /// Upon return, it will be set to the actual number of words that would
  256. /// be needed to store this BigInt (i.e. the return value of `WordCount()`).
  257. void ToWords(int* sign_bit, size_t* word_count, uint64_t* words);
  258. };
  259. #endif // NAPI_EXPERIMENTAL
  260. /// A JavaScript string or symbol value (that can be used as a property name).
  261. class Name : public Value {
  262. public:
  263. Name(); ///< Creates a new _empty_ Name instance.
  264. Name(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
  265. };
  266. /// A JavaScript string value.
  267. class String : public Name {
  268. public:
  269. /// Creates a new String value from a UTF-8 encoded C++ string.
  270. static String New(
  271. napi_env env, ///< N-API environment
  272. const std::string& value ///< UTF-8 encoded C++ string
  273. );
  274. /// Creates a new String value from a UTF-16 encoded C++ string.
  275. static String New(
  276. napi_env env, ///< N-API environment
  277. const std::u16string& value ///< UTF-16 encoded C++ string
  278. );
  279. /// Creates a new String value from a UTF-8 encoded C string.
  280. static String New(
  281. napi_env env, ///< N-API environment
  282. const char* value ///< UTF-8 encoded null-terminated C string
  283. );
  284. /// Creates a new String value from a UTF-16 encoded C string.
  285. static String New(
  286. napi_env env, ///< N-API environment
  287. const char16_t* value ///< UTF-16 encoded null-terminated C string
  288. );
  289. /// Creates a new String value from a UTF-8 encoded C string with specified length.
  290. static String New(
  291. napi_env env, ///< N-API environment
  292. const char* value, ///< UTF-8 encoded C string (not necessarily null-terminated)
  293. size_t length ///< length of the string in bytes
  294. );
  295. /// Creates a new String value from a UTF-16 encoded C string with specified length.
  296. static String New(
  297. napi_env env, ///< N-API environment
  298. const char16_t* value, ///< UTF-16 encoded C string (not necessarily null-terminated)
  299. size_t length ///< Length of the string in 2-byte code units
  300. );
  301. /// Creates a new String based on the original object's type.
  302. ///
  303. /// `value` may be any of:
  304. /// - const char* (encoded using UTF-8, null-terminated)
  305. /// - const char16_t* (encoded using UTF-16-LE, null-terminated)
  306. /// - std::string (encoded using UTF-8)
  307. /// - std::u16string
  308. template <typename T>
  309. static String From(napi_env env, const T& value);
  310. String(); ///< Creates a new _empty_ String instance.
  311. String(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
  312. operator std::string() const; ///< Converts a String value to a UTF-8 encoded C++ string.
  313. operator std::u16string() const; ///< Converts a String value to a UTF-16 encoded C++ string.
  314. std::string Utf8Value() const; ///< Converts a String value to a UTF-8 encoded C++ string.
  315. std::u16string Utf16Value() const; ///< Converts a String value to a UTF-16 encoded C++ string.
  316. };
  317. /// A JavaScript symbol value.
  318. class Symbol : public Name {
  319. public:
  320. /// Creates a new Symbol value with an optional description.
  321. static Symbol New(
  322. napi_env env, ///< N-API environment
  323. const char* description = nullptr ///< Optional UTF-8 encoded null-terminated C string
  324. /// describing the symbol
  325. );
  326. /// Creates a new Symbol value with a description.
  327. static Symbol New(
  328. napi_env env, ///< N-API environment
  329. const std::string& description ///< UTF-8 encoded C++ string describing the symbol
  330. );
  331. /// Creates a new Symbol value with a description.
  332. static Symbol New(
  333. napi_env env, ///< N-API environment
  334. String description ///< String value describing the symbol
  335. );
  336. /// Creates a new Symbol value with a description.
  337. static Symbol New(
  338. napi_env env, ///< N-API environment
  339. napi_value description ///< String value describing the symbol
  340. );
  341. /// Get a public Symbol (e.g. Symbol.iterator).
  342. static Symbol WellKnown(napi_env, const std::string& name);
  343. Symbol(); ///< Creates a new _empty_ Symbol instance.
  344. Symbol(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
  345. };
  346. /// A JavaScript object value.
  347. class Object : public Value {
  348. public:
  349. /// Enables property and element assignments using indexing syntax.
  350. ///
  351. /// Example:
  352. ///
  353. /// Napi::Value propertyValue = object1['A'];
  354. /// object2['A'] = propertyValue;
  355. /// Napi::Value elementValue = array[0];
  356. /// array[1] = elementValue;
  357. template <typename Key>
  358. class PropertyLValue {
  359. public:
  360. /// Converts an L-value to a value.
  361. operator Value() const;
  362. /// Assigns a value to the property. The type of value can be
  363. /// anything supported by `Object::Set`.
  364. template <typename ValueType>
  365. PropertyLValue& operator =(ValueType value);
  366. private:
  367. PropertyLValue() = delete;
  368. PropertyLValue(Object object, Key key);
  369. napi_env _env;
  370. napi_value _object;
  371. Key _key;
  372. friend class Napi::Object;
  373. };
  374. /// Creates a new Object value.
  375. static Object New(
  376. napi_env env ///< N-API environment
  377. );
  378. Object(); ///< Creates a new _empty_ Object instance.
  379. Object(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
  380. /// Gets or sets a named property.
  381. PropertyLValue<std::string> operator [](
  382. const char* utf8name ///< UTF-8 encoded null-terminated property name
  383. );
  384. /// Gets or sets a named property.
  385. PropertyLValue<std::string> operator [](
  386. const std::string& utf8name ///< UTF-8 encoded property name
  387. );
  388. /// Gets or sets an indexed property or array element.
  389. PropertyLValue<uint32_t> operator [](
  390. uint32_t index /// Property / element index
  391. );
  392. /// Gets a named property.
  393. Value operator [](
  394. const char* utf8name ///< UTF-8 encoded null-terminated property name
  395. ) const;
  396. /// Gets a named property.
  397. Value operator [](
  398. const std::string& utf8name ///< UTF-8 encoded property name
  399. ) const;
  400. /// Gets an indexed property or array element.
  401. Value operator [](
  402. uint32_t index ///< Property / element index
  403. ) const;
  404. /// Checks whether a property is present.
  405. bool Has(
  406. napi_value key ///< Property key primitive
  407. ) const;
  408. /// Checks whether a property is present.
  409. bool Has(
  410. Value key ///< Property key
  411. ) const;
  412. /// Checks whether a named property is present.
  413. bool Has(
  414. const char* utf8name ///< UTF-8 encoded null-terminated property name
  415. ) const;
  416. /// Checks whether a named property is present.
  417. bool Has(
  418. const std::string& utf8name ///< UTF-8 encoded property name
  419. ) const;
  420. /// Checks whether a own property is present.
  421. bool HasOwnProperty(
  422. napi_value key ///< Property key primitive
  423. ) const;
  424. /// Checks whether a own property is present.
  425. bool HasOwnProperty(
  426. Value key ///< Property key
  427. ) const;
  428. /// Checks whether a own property is present.
  429. bool HasOwnProperty(
  430. const char* utf8name ///< UTF-8 encoded null-terminated property name
  431. ) const;
  432. /// Checks whether a own property is present.
  433. bool HasOwnProperty(
  434. const std::string& utf8name ///< UTF-8 encoded property name
  435. ) const;
  436. /// Gets a property.
  437. Value Get(
  438. napi_value key ///< Property key primitive
  439. ) const;
  440. /// Gets a property.
  441. Value Get(
  442. Value key ///< Property key
  443. ) const;
  444. /// Gets a named property.
  445. Value Get(
  446. const char* utf8name ///< UTF-8 encoded null-terminated property name
  447. ) const;
  448. /// Gets a named property.
  449. Value Get(
  450. const std::string& utf8name ///< UTF-8 encoded property name
  451. ) const;
  452. /// Sets a property.
  453. template <typename ValueType>
  454. void Set(
  455. napi_value key, ///< Property key primitive
  456. const ValueType& value ///< Property value primitive
  457. );
  458. /// Sets a property.
  459. template <typename ValueType>
  460. void Set(
  461. Value key, ///< Property key
  462. const ValueType& value ///< Property value
  463. );
  464. /// Sets a named property.
  465. template <typename ValueType>
  466. void Set(
  467. const char* utf8name, ///< UTF-8 encoded null-terminated property name
  468. const ValueType& value
  469. );
  470. /// Sets a named property.
  471. template <typename ValueType>
  472. void Set(
  473. const std::string& utf8name, ///< UTF-8 encoded property name
  474. const ValueType& value ///< Property value primitive
  475. );
  476. /// Delete property.
  477. bool Delete(
  478. napi_value key ///< Property key primitive
  479. );
  480. /// Delete property.
  481. bool Delete(
  482. Value key ///< Property key
  483. );
  484. /// Delete property.
  485. bool Delete(
  486. const char* utf8name ///< UTF-8 encoded null-terminated property name
  487. );
  488. /// Delete property.
  489. bool Delete(
  490. const std::string& utf8name ///< UTF-8 encoded property name
  491. );
  492. /// Checks whether an indexed property is present.
  493. bool Has(
  494. uint32_t index ///< Property / element index
  495. ) const;
  496. /// Gets an indexed property or array element.
  497. Value Get(
  498. uint32_t index ///< Property / element index
  499. ) const;
  500. /// Sets an indexed property or array element.
  501. template <typename ValueType>
  502. void Set(
  503. uint32_t index, ///< Property / element index
  504. const ValueType& value ///< Property value primitive
  505. );
  506. /// Deletes an indexed property or array element.
  507. bool Delete(
  508. uint32_t index ///< Property / element index
  509. );
  510. Array GetPropertyNames(); ///< Get all property names
  511. /// Defines a property on the object.
  512. void DefineProperty(
  513. const PropertyDescriptor& property ///< Descriptor for the property to be defined
  514. );
  515. /// Defines properties on the object.
  516. void DefineProperties(
  517. const std::initializer_list<PropertyDescriptor>& properties
  518. ///< List of descriptors for the properties to be defined
  519. );
  520. /// Defines properties on the object.
  521. void DefineProperties(
  522. const std::vector<PropertyDescriptor>& properties
  523. ///< Vector of descriptors for the properties to be defined
  524. );
  525. /// Checks if an object is an instance created by a constructor function.
  526. ///
  527. /// This is equivalent to the JavaScript `instanceof` operator.
  528. bool InstanceOf(
  529. const Function& constructor ///< Constructor function
  530. ) const;
  531. };
  532. template <typename T>
  533. class External : public Value {
  534. public:
  535. static External New(napi_env env, T* data);
  536. // Finalizer must implement operator() accepting a T* and returning void.
  537. template <typename Finalizer>
  538. static External New(napi_env env,
  539. T* data,
  540. Finalizer finalizeCallback);
  541. // Finalizer must implement operator() accepting a T* and Hint* and returning void.
  542. template <typename Finalizer, typename Hint>
  543. static External New(napi_env env,
  544. T* data,
  545. Finalizer finalizeCallback,
  546. Hint* finalizeHint);
  547. External();
  548. External(napi_env env, napi_value value);
  549. T* Data() const;
  550. };
  551. class Array : public Object {
  552. public:
  553. static Array New(napi_env env);
  554. static Array New(napi_env env, size_t length);
  555. Array();
  556. Array(napi_env env, napi_value value);
  557. uint32_t Length() const;
  558. };
  559. /// A JavaScript array buffer value.
  560. class ArrayBuffer : public Object {
  561. public:
  562. /// Creates a new ArrayBuffer instance over a new automatically-allocated buffer.
  563. static ArrayBuffer New(
  564. napi_env env, ///< N-API environment
  565. size_t byteLength ///< Length of the buffer to be allocated, in bytes
  566. );
  567. /// Creates a new ArrayBuffer instance, using an external buffer with specified byte length.
  568. static ArrayBuffer New(
  569. napi_env env, ///< N-API environment
  570. void* externalData, ///< Pointer to the external buffer to be used by the array
  571. size_t byteLength ///< Length of the external buffer to be used by the array, in bytes
  572. );
  573. /// Creates a new ArrayBuffer instance, using an external buffer with specified byte length.
  574. template <typename Finalizer>
  575. static ArrayBuffer New(
  576. napi_env env, ///< N-API environment
  577. void* externalData, ///< Pointer to the external buffer to be used by the array
  578. size_t byteLength, ///< Length of the external buffer to be used by the array,
  579. /// in bytes
  580. Finalizer finalizeCallback ///< Function to be called when the array buffer is destroyed;
  581. /// must implement `operator()`, accept a `void*` (which is the
  582. /// data buffer pointer), and return `void`
  583. );
  584. /// Creates a new ArrayBuffer instance, using an external buffer with specified byte length.
  585. template <typename Finalizer, typename Hint>
  586. static ArrayBuffer New(
  587. napi_env env, ///< N-API environment
  588. void* externalData, ///< Pointer to the external buffer to be used by the array
  589. size_t byteLength, ///< Length of the external buffer to be used by the array,
  590. /// in bytes
  591. Finalizer finalizeCallback, ///< Function to be called when the array buffer is destroyed;
  592. /// must implement `operator()`, accept a `void*` (which is the
  593. /// data buffer pointer) and `Hint*`, and return `void`
  594. Hint* finalizeHint ///< Hint (second parameter) to be passed to the finalize callback
  595. );
  596. ArrayBuffer(); ///< Creates a new _empty_ ArrayBuffer instance.
  597. ArrayBuffer(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
  598. void* Data(); ///< Gets a pointer to the data buffer.
  599. size_t ByteLength(); ///< Gets the length of the array buffer in bytes.
  600. private:
  601. mutable void* _data;
  602. mutable size_t _length;
  603. ArrayBuffer(napi_env env, napi_value value, void* data, size_t length);
  604. void EnsureInfo() const;
  605. };
  606. /// A JavaScript typed-array value with unknown array type.
  607. ///
  608. /// For type-specific operations, cast to a `TypedArrayOf<T>` instance using the `As()`
  609. /// method:
  610. ///
  611. /// Napi::TypedArray array = ...
  612. /// if (t.TypedArrayType() == napi_int32_array) {
  613. /// Napi::Int32Array int32Array = t.As<Napi::Int32Array>();
  614. /// }
  615. class TypedArray : public Object {
  616. public:
  617. TypedArray(); ///< Creates a new _empty_ TypedArray instance.
  618. TypedArray(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
  619. napi_typedarray_type TypedArrayType() const; ///< Gets the type of this typed-array.
  620. Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer.
  621. uint8_t ElementSize() const; ///< Gets the size in bytes of one element in the array.
  622. size_t ElementLength() const; ///< Gets the number of elements in the array.
  623. size_t ByteOffset() const; ///< Gets the offset into the buffer where the array starts.
  624. size_t ByteLength() const; ///< Gets the length of the array in bytes.
  625. protected:
  626. /// !cond INTERNAL
  627. napi_typedarray_type _type;
  628. size_t _length;
  629. TypedArray(napi_env env, napi_value value, napi_typedarray_type type, size_t length);
  630. static const napi_typedarray_type unknown_array_type = static_cast<napi_typedarray_type>(-1);
  631. template <typename T>
  632. static
  633. #if defined(NAPI_HAS_CONSTEXPR)
  634. constexpr
  635. #endif
  636. napi_typedarray_type TypedArrayTypeForPrimitiveType() {
  637. return std::is_same<T, int8_t>::value ? napi_int8_array
  638. : std::is_same<T, uint8_t>::value ? napi_uint8_array
  639. : std::is_same<T, int16_t>::value ? napi_int16_array
  640. : std::is_same<T, uint16_t>::value ? napi_uint16_array
  641. : std::is_same<T, int32_t>::value ? napi_int32_array
  642. : std::is_same<T, uint32_t>::value ? napi_uint32_array
  643. : std::is_same<T, float>::value ? napi_float32_array
  644. : std::is_same<T, double>::value ? napi_float64_array
  645. // currently experimental guard with version of NAPI_VERSION that it is
  646. // released in once it is no longer experimental
  647. #if (NAPI_VERSION > 2147483646)
  648. : std::is_same<T, int64_t>::value ? napi_bigint64_array
  649. : std::is_same<T, uint64_t>::value ? napi_biguint64_array
  650. #endif // NAPI_EXPERIMENTAL
  651. : unknown_array_type;
  652. }
  653. /// !endcond
  654. };
  655. /// A JavaScript typed-array value with known array type.
  656. ///
  657. /// Note while it is possible to create and access Uint8 "clamped" arrays using this class,
  658. /// the _clamping_ behavior is only applied in JavaScript.
  659. template <typename T>
  660. class TypedArrayOf : public TypedArray {
  661. public:
  662. /// Creates a new TypedArray instance over a new automatically-allocated array buffer.
  663. ///
  664. /// The array type parameter can normally be omitted (because it is inferred from the template
  665. /// parameter T), except when creating a "clamped" array:
  666. ///
  667. /// Uint8Array::New(env, length, napi_uint8_clamped_array)
  668. static TypedArrayOf New(
  669. napi_env env, ///< N-API environment
  670. size_t elementLength, ///< Length of the created array, as a number of elements
  671. #if defined(NAPI_HAS_CONSTEXPR)
  672. napi_typedarray_type type = TypedArray::TypedArrayTypeForPrimitiveType<T>()
  673. #else
  674. napi_typedarray_type type
  675. #endif
  676. ///< Type of array, if different from the default array type for the template parameter T.
  677. );
  678. /// Creates a new TypedArray instance over a provided array buffer.
  679. ///
  680. /// The array type parameter can normally be omitted (because it is inferred from the template
  681. /// parameter T), except when creating a "clamped" array:
  682. ///
  683. /// Uint8Array::New(env, length, buffer, 0, napi_uint8_clamped_array)
  684. static TypedArrayOf New(
  685. napi_env env, ///< N-API environment
  686. size_t elementLength, ///< Length of the created array, as a number of elements
  687. Napi::ArrayBuffer arrayBuffer, ///< Backing array buffer instance to use
  688. size_t bufferOffset, ///< Offset into the array buffer where the typed-array starts
  689. #if defined(NAPI_HAS_CONSTEXPR)
  690. napi_typedarray_type type = TypedArray::TypedArrayTypeForPrimitiveType<T>()
  691. #else
  692. napi_typedarray_type type
  693. #endif
  694. ///< Type of array, if different from the default array type for the template parameter T.
  695. );
  696. TypedArrayOf(); ///< Creates a new _empty_ TypedArrayOf instance.
  697. TypedArrayOf(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
  698. T& operator [](size_t index); ///< Gets or sets an element in the array.
  699. const T& operator [](size_t index) const; ///< Gets an element in the array.
  700. /// Gets a pointer to the array's backing buffer.
  701. ///
  702. /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, because the
  703. /// typed-array may have a non-zero `ByteOffset()` into the `ArrayBuffer`.
  704. T* Data();
  705. /// Gets a pointer to the array's backing buffer.
  706. ///
  707. /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, because the
  708. /// typed-array may have a non-zero `ByteOffset()` into the `ArrayBuffer`.
  709. const T* Data() const;
  710. private:
  711. T* _data;
  712. TypedArrayOf(napi_env env,
  713. napi_value value,
  714. napi_typedarray_type type,
  715. size_t length,
  716. T* data);
  717. };
  718. /// The DataView provides a low-level interface for reading/writing multiple
  719. /// number types in an ArrayBuffer irrespective of the platform's endianness.
  720. class DataView : public Object {
  721. public:
  722. static DataView New(napi_env env,
  723. Napi::ArrayBuffer arrayBuffer);
  724. static DataView New(napi_env env,
  725. Napi::ArrayBuffer arrayBuffer,
  726. size_t byteOffset);
  727. static DataView New(napi_env env,
  728. Napi::ArrayBuffer arrayBuffer,
  729. size_t byteOffset,
  730. size_t byteLength);
  731. DataView(); ///< Creates a new _empty_ DataView instance.
  732. DataView(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
  733. Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer.
  734. size_t ByteOffset() const; ///< Gets the offset into the buffer where the array starts.
  735. size_t ByteLength() const; ///< Gets the length of the array in bytes.
  736. void* Data() const;
  737. float GetFloat32(size_t byteOffset) const;
  738. double GetFloat64(size_t byteOffset) const;
  739. int8_t GetInt8(size_t byteOffset) const;
  740. int16_t GetInt16(size_t byteOffset) const;
  741. int32_t GetInt32(size_t byteOffset) const;
  742. uint8_t GetUint8(size_t byteOffset) const;
  743. uint16_t GetUint16(size_t byteOffset) const;
  744. uint32_t GetUint32(size_t byteOffset) const;
  745. void SetFloat32(size_t byteOffset, float value) const;
  746. void SetFloat64(size_t byteOffset, double value) const;
  747. void SetInt8(size_t byteOffset, int8_t value) const;
  748. void SetInt16(size_t byteOffset, int16_t value) const;
  749. void SetInt32(size_t byteOffset, int32_t value) const;
  750. void SetUint8(size_t byteOffset, uint8_t value) const;
  751. void SetUint16(size_t byteOffset, uint16_t value) const;
  752. void SetUint32(size_t byteOffset, uint32_t value) const;
  753. private:
  754. template <typename T>
  755. T ReadData(size_t byteOffset) const;
  756. template <typename T>
  757. void WriteData(size_t byteOffset, T value) const;
  758. void* _data;
  759. size_t _length;
  760. };
  761. class Function : public Object {
  762. public:
  763. /// Callable must implement operator() accepting a const CallbackInfo&
  764. /// and return either void or Value.
  765. template <typename Callable>
  766. static Function New(napi_env env,
  767. Callable cb,
  768. const char* utf8name = nullptr,
  769. void* data = nullptr);
  770. /// Callable must implement operator() accepting a const CallbackInfo&
  771. /// and return either void or Value.
  772. template <typename Callable>
  773. static Function New(napi_env env,
  774. Callable cb,
  775. const std::string& utf8name,
  776. void* data = nullptr);
  777. Function();
  778. Function(napi_env env, napi_value value);
  779. Value operator ()(const std::initializer_list<napi_value>& args) const;
  780. Value Call(const std::initializer_list<napi_value>& args) const;
  781. Value Call(const std::vector<napi_value>& args) const;
  782. Value Call(size_t argc, const napi_value* args) const;
  783. Value Call(napi_value recv, const std::initializer_list<napi_value>& args) const;
  784. Value Call(napi_value recv, const std::vector<napi_value>& args) const;
  785. Value Call(napi_value recv, size_t argc, const napi_value* args) const;
  786. Value MakeCallback(napi_value recv,
  787. const std::initializer_list<napi_value>& args,
  788. napi_async_context context = nullptr) const;
  789. Value MakeCallback(napi_value recv,
  790. const std::vector<napi_value>& args,
  791. napi_async_context context = nullptr) const;
  792. Value MakeCallback(napi_value recv,
  793. size_t argc,
  794. const napi_value* args,
  795. napi_async_context context = nullptr) const;
  796. Object New(const std::initializer_list<napi_value>& args) const;
  797. Object New(const std::vector<napi_value>& args) const;
  798. Object New(size_t argc, const napi_value* args) const;
  799. };
  800. class Promise : public Object {
  801. public:
  802. class Deferred {
  803. public:
  804. static Deferred New(napi_env env);
  805. Deferred(napi_env env);
  806. Napi::Promise Promise() const;
  807. Napi::Env Env() const;
  808. void Resolve(napi_value value) const;
  809. void Reject(napi_value value) const;
  810. private:
  811. napi_env _env;
  812. napi_deferred _deferred;
  813. napi_value _promise;
  814. };
  815. Promise(napi_env env, napi_value value);
  816. };
  817. template <typename T>
  818. class Buffer : public Uint8Array {
  819. public:
  820. static Buffer<T> New(napi_env env, size_t length);
  821. static Buffer<T> New(napi_env env, T* data, size_t length);
  822. // Finalizer must implement operator() accepting a T* and returning void.
  823. template <typename Finalizer>
  824. static Buffer<T> New(napi_env env, T* data,
  825. size_t length,
  826. Finalizer finalizeCallback);
  827. // Finalizer must implement operator() accepting a T* and Hint* and returning void.
  828. template <typename Finalizer, typename Hint>
  829. static Buffer<T> New(napi_env env, T* data,
  830. size_t length,
  831. Finalizer finalizeCallback,
  832. Hint* finalizeHint);
  833. static Buffer<T> Copy(napi_env env, const T* data, size_t length);
  834. Buffer();
  835. Buffer(napi_env env, napi_value value);
  836. size_t Length() const;
  837. T* Data() const;
  838. private:
  839. mutable size_t _length;
  840. mutable T* _data;
  841. Buffer(napi_env env, napi_value value, size_t length, T* data);
  842. void EnsureInfo() const;
  843. };
  844. /// Holds a counted reference to a value; initially a weak reference unless otherwise specified,
  845. /// may be changed to/from a strong reference by adjusting the refcount.
  846. ///
  847. /// The referenced value is not immediately destroyed when the reference count is zero; it is
  848. /// merely then eligible for garbage-collection if there are no other references to the value.
  849. template <typename T>
  850. class Reference {
  851. public:
  852. static Reference<T> New(const T& value, uint32_t initialRefcount = 0);
  853. Reference();
  854. Reference(napi_env env, napi_ref ref);
  855. ~Reference();
  856. // A reference can be moved but cannot be copied.
  857. Reference(Reference<T>&& other);
  858. Reference<T>& operator =(Reference<T>&& other);
  859. Reference<T>& operator =(Reference<T>&) = delete;
  860. operator napi_ref() const;
  861. bool operator ==(const Reference<T> &other) const;
  862. bool operator !=(const Reference<T> &other) const;
  863. Napi::Env Env() const;
  864. bool IsEmpty() const;
  865. // Note when getting the value of a Reference it is usually correct to do so
  866. // within a HandleScope so that the value handle gets cleaned up efficiently.
  867. T Value() const;
  868. uint32_t Ref();
  869. uint32_t Unref();
  870. void Reset();
  871. void Reset(const T& value, uint32_t refcount = 0);
  872. // Call this on a reference that is declared as static data, to prevent its destructor
  873. // from running at program shutdown time, which would attempt to reset the reference when
  874. // the environment is no longer valid.
  875. void SuppressDestruct();
  876. protected:
  877. Reference(const Reference<T>&);
  878. /// !cond INTERNAL
  879. napi_env _env;
  880. napi_ref _ref;
  881. /// !endcond
  882. private:
  883. bool _suppressDestruct;
  884. };
  885. class ObjectReference: public Reference<Object> {
  886. public:
  887. ObjectReference();
  888. ObjectReference(napi_env env, napi_ref ref);
  889. // A reference can be moved but cannot be copied.
  890. ObjectReference(Reference<Object>&& other);
  891. ObjectReference& operator =(Reference<Object>&& other);
  892. ObjectReference(ObjectReference&& other);
  893. ObjectReference& operator =(ObjectReference&& other);
  894. ObjectReference& operator =(ObjectReference&) = delete;
  895. Napi::Value Get(const char* utf8name) const;
  896. Napi::Value Get(const std::string& utf8name) const;
  897. void Set(const char* utf8name, napi_value value);
  898. void Set(const char* utf8name, Napi::Value value);
  899. void Set(const char* utf8name, const char* utf8value);
  900. void Set(const char* utf8name, bool boolValue);
  901. void Set(const char* utf8name, double numberValue);
  902. void Set(const std::string& utf8name, napi_value value);
  903. void Set(const std::string& utf8name, Napi::Value value);
  904. void Set(const std::string& utf8name, std::string& utf8value);
  905. void Set(const std::string& utf8name, bool boolValue);
  906. void Set(const std::string& utf8name, double numberValue);
  907. Napi::Value Get(uint32_t index) const;
  908. void Set(uint32_t index, const napi_value value);
  909. void Set(uint32_t index, const Napi::Value value);
  910. void Set(uint32_t index, const char* utf8value);
  911. void Set(uint32_t index, const std::string& utf8value);
  912. void Set(uint32_t index, bool boolValue);
  913. void Set(uint32_t index, double numberValue);
  914. protected:
  915. ObjectReference(const ObjectReference&);
  916. };
  917. class FunctionReference: public Reference<Function> {
  918. public:
  919. FunctionReference();
  920. FunctionReference(napi_env env, napi_ref ref);
  921. // A reference can be moved but cannot be copied.
  922. FunctionReference(Reference<Function>&& other);
  923. FunctionReference& operator =(Reference<Function>&& other);
  924. FunctionReference(FunctionReference&& other);
  925. FunctionReference& operator =(FunctionReference&& other);
  926. FunctionReference(const FunctionReference&) = delete;
  927. FunctionReference& operator =(FunctionReference&) = delete;
  928. Napi::Value operator ()(const std::initializer_list<napi_value>& args) const;
  929. Napi::Value Call(const std::initializer_list<napi_value>& args) const;
  930. Napi::Value Call(const std::vector<napi_value>& args) const;
  931. Napi::Value Call(napi_value recv, const std::initializer_list<napi_value>& args) const;
  932. Napi::Value Call(napi_value recv, const std::vector<napi_value>& args) const;
  933. Napi::Value Call(napi_value recv, size_t argc, const napi_value* args) const;
  934. Napi::Value MakeCallback(napi_value recv,
  935. const std::initializer_list<napi_value>& args,
  936. napi_async_context context = nullptr) const;
  937. Napi::Value MakeCallback(napi_value recv,
  938. const std::vector<napi_value>& args,
  939. napi_async_context context = nullptr) const;
  940. Napi::Value MakeCallback(napi_value recv,
  941. size_t argc,
  942. const napi_value* args,
  943. napi_async_context context = nullptr) const;
  944. Object New(const std::initializer_list<napi_value>& args) const;
  945. Object New(const std::vector<napi_value>& args) const;
  946. };
  947. // Shortcuts to creating a new reference with inferred type and refcount = 0.
  948. template <typename T> Reference<T> Weak(T value);
  949. ObjectReference Weak(Object value);
  950. FunctionReference Weak(Function value);
  951. // Shortcuts to creating a new reference with inferred type and refcount = 1.
  952. template <typename T> Reference<T> Persistent(T value);
  953. ObjectReference Persistent(Object value);
  954. FunctionReference Persistent(Function value);
  955. /// A persistent reference to a JavaScript error object. Use of this class depends somewhat
  956. /// on whether C++ exceptions are enabled at compile time.
  957. ///
  958. /// ### Handling Errors With C++ Exceptions
  959. ///
  960. /// If C++ exceptions are enabled, then the `Error` class extends `std::exception` and enables
  961. /// integrated error-handling for C++ exceptions and JavaScript exceptions.
  962. ///
  963. /// If a N-API call fails without executing any JavaScript code (for example due to an invalid
  964. /// argument), then the N-API wrapper automatically converts and throws the error as a C++
  965. /// exception of type `Napi::Error`. Or if a JavaScript function called by C++ code via N-API
  966. /// throws a JavaScript exception, then the N-API wrapper automatically converts and throws it as
  967. /// a C++ exception of type `Napi::Error`.
  968. ///
  969. /// If a C++ exception of type `Napi::Error` escapes from a N-API C++ callback, then the N-API
  970. /// wrapper automatically converts and throws it as a JavaScript exception. Therefore, catching
  971. /// a C++ exception of type `Napi::Error` prevents a JavaScript exception from being thrown.
  972. ///
  973. /// #### Example 1A - Throwing a C++ exception:
  974. ///
  975. /// Napi::Env env = ...
  976. /// throw Napi::Error::New(env, "Example exception");
  977. ///
  978. /// Following C++ statements will not be executed. The exception will bubble up as a C++
  979. /// exception of type `Napi::Error`, until it is either caught while still in C++, or else
  980. /// automatically propataged as a JavaScript exception when the callback returns to JavaScript.
  981. ///
  982. /// #### Example 2A - Propagating a N-API C++ exception:
  983. ///
  984. /// Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>();
  985. /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 });
  986. ///
  987. /// Following C++ statements will not be executed. The exception will bubble up as a C++
  988. /// exception of type `Napi::Error`, until it is either caught while still in C++, or else
  989. /// automatically propagated as a JavaScript exception when the callback returns to JavaScript.
  990. ///
  991. /// #### Example 3A - Handling a N-API C++ exception:
  992. ///
  993. /// Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>();
  994. /// Napi::Value result;
  995. /// try {
  996. /// result = jsFunctionThatThrows({ arg1, arg2 });
  997. /// } catch (const Napi::Error& e) {
  998. /// cerr << "Caught JavaScript exception: " + e.what();
  999. /// }
  1000. ///
  1001. /// Since the exception was caught here, it will not be propagated as a JavaScript exception.
  1002. ///
  1003. /// ### Handling Errors Without C++ Exceptions
  1004. ///
  1005. /// If C++ exceptions are disabled (by defining `NAPI_DISABLE_CPP_EXCEPTIONS`) then this class
  1006. /// does not extend `std::exception`, and APIs in the `Napi` namespace do not throw C++
  1007. /// exceptions when they fail. Instead, they raise _pending_ JavaScript exceptions and
  1008. /// return _empty_ `Value`s. Calling code should check `Value::IsEmpty()` before attempting
  1009. /// to use a returned value, and may use methods on the `Env` class to check for, get, and
  1010. /// clear a pending JavaScript exception. If the pending exception is not cleared, it will
  1011. /// be thrown when the native callback returns to JavaScript.
  1012. ///
  1013. /// #### Example 1B - Throwing a JS exception
  1014. ///
  1015. /// Napi::Env env = ...
  1016. /// Napi::Error::New(env, "Example exception").ThrowAsJavaScriptException();
  1017. /// return;
  1018. ///
  1019. /// After throwing a JS exception, the code should generally return immediately from the native
  1020. /// callback, after performing any necessary cleanup.
  1021. ///
  1022. /// #### Example 2B - Propagating a N-API JS exception:
  1023. ///
  1024. /// Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>();
  1025. /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 });
  1026. /// if (result.IsEmpty()) return;
  1027. ///
  1028. /// An empty value result from a N-API call indicates an error occurred, and a JavaScript
  1029. /// exception is pending. To let the exception propagate, the code should generally return
  1030. /// immediately from the native callback, after performing any necessary cleanup.
  1031. ///
  1032. /// #### Example 3B - Handling a N-API JS exception:
  1033. ///
  1034. /// Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>();
  1035. /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 });
  1036. /// if (result.IsEmpty()) {
  1037. /// Napi::Error e = env.GetAndClearPendingException();
  1038. /// cerr << "Caught JavaScript exception: " + e.Message();
  1039. /// }
  1040. ///
  1041. /// Since the exception was cleared here, it will not be propagated as a JavaScript exception
  1042. /// after the native callback returns.
  1043. class Error : public ObjectReference
  1044. #ifdef NAPI_CPP_EXCEPTIONS
  1045. , public std::exception
  1046. #endif // NAPI_CPP_EXCEPTIONS
  1047. {
  1048. public:
  1049. static Error New(napi_env env);
  1050. static Error New(napi_env env, const char* message);
  1051. static Error New(napi_env env, const std::string& message);
  1052. static NAPI_NO_RETURN void Fatal(const char* location, const char* message);
  1053. Error();
  1054. Error(napi_env env, napi_value value);
  1055. // An error can be moved or copied.
  1056. Error(Error&& other);
  1057. Error& operator =(Error&& other);
  1058. Error(const Error&);
  1059. Error& operator =(Error&);
  1060. const std::string& Message() const NAPI_NOEXCEPT;
  1061. void ThrowAsJavaScriptException() const;
  1062. #ifdef NAPI_CPP_EXCEPTIONS
  1063. const char* what() const NAPI_NOEXCEPT override;
  1064. #endif // NAPI_CPP_EXCEPTIONS
  1065. protected:
  1066. /// !cond INTERNAL
  1067. typedef napi_status (*create_error_fn)(napi_env envb, napi_value code, napi_value msg, napi_value* result);
  1068. template <typename TError>
  1069. static TError New(napi_env env,
  1070. const char* message,
  1071. size_t length,
  1072. create_error_fn create_error);
  1073. /// !endcond
  1074. private:
  1075. mutable std::string _message;
  1076. };
  1077. class TypeError : public Error {
  1078. public:
  1079. static TypeError New(napi_env env, const char* message);
  1080. static TypeError New(napi_env env, const std::string& message);
  1081. TypeError();
  1082. TypeError(napi_env env, napi_value value);
  1083. };
  1084. class RangeError : public Error {
  1085. public:
  1086. static RangeError New(napi_env env, const char* message);
  1087. static RangeError New(napi_env env, const std::string& message);
  1088. RangeError();
  1089. RangeError(napi_env env, napi_value value);
  1090. };
  1091. class CallbackInfo {
  1092. public:
  1093. CallbackInfo(napi_env env, napi_callback_info info);
  1094. ~CallbackInfo();
  1095. // Disallow copying to prevent multiple free of _dynamicArgs
  1096. CallbackInfo(CallbackInfo const &) = delete;
  1097. void operator=(CallbackInfo const &) = delete;
  1098. Napi::Env Env() const;
  1099. Value NewTarget() const;
  1100. bool IsConstructCall() const;
  1101. size_t Length() const;
  1102. const Value operator [](size_t index) const;
  1103. Value This() const;
  1104. void* Data() const;
  1105. void SetData(void* data);
  1106. private:
  1107. const size_t _staticArgCount = 6;
  1108. napi_env _env;
  1109. napi_callback_info _info;
  1110. napi_value _this;
  1111. size_t _argc;
  1112. napi_value* _argv;
  1113. napi_value _staticArgs[6];
  1114. napi_value* _dynamicArgs;
  1115. void* _data;
  1116. };
  1117. class PropertyDescriptor {
  1118. public:
  1119. #ifndef NODE_ADDON_API_DISABLE_DEPRECATED
  1120. template <typename Getter>
  1121. static PropertyDescriptor Accessor(const char* utf8name,
  1122. Getter getter,
  1123. napi_property_attributes attributes = napi_default,
  1124. void* data = nullptr);
  1125. template <typename Getter>
  1126. static PropertyDescriptor Accessor(const std::string& utf8name,
  1127. Getter getter,
  1128. napi_property_attributes attributes = napi_default,
  1129. void* data = nullptr);
  1130. template <typename Getter>
  1131. static PropertyDescriptor Accessor(napi_value name,
  1132. Getter getter,
  1133. napi_property_attributes attributes = napi_default,
  1134. void* data = nullptr);
  1135. template <typename Getter>
  1136. static PropertyDescriptor Accessor(Name name,
  1137. Getter getter,
  1138. napi_property_attributes attributes = napi_default,
  1139. void* data = nullptr);
  1140. template <typename Getter, typename Setter>
  1141. static PropertyDescriptor Accessor(const char* utf8name,
  1142. Getter getter,
  1143. Setter setter,
  1144. napi_property_attributes attributes = napi_default,
  1145. void* data = nullptr);
  1146. template <typename Getter, typename Setter>
  1147. static PropertyDescriptor Accessor(const std::string& utf8name,
  1148. Getter getter,
  1149. Setter setter,
  1150. napi_property_attributes attributes = napi_default,
  1151. void* data = nullptr);
  1152. template <typename Getter, typename Setter>
  1153. static PropertyDescriptor Accessor(napi_value name,
  1154. Getter getter,
  1155. Setter setter,
  1156. napi_property_attributes attributes = napi_default,
  1157. void* data = nullptr);
  1158. template <typename Getter, typename Setter>
  1159. static PropertyDescriptor Accessor(Name name,
  1160. Getter getter,
  1161. Setter setter,
  1162. napi_property_attributes attributes = napi_default,
  1163. void* data = nullptr);
  1164. template <typename Callable>
  1165. static PropertyDescriptor Function(const char* utf8name,
  1166. Callable cb,
  1167. napi_property_attributes attributes = napi_default,
  1168. void* data = nullptr);
  1169. template <typename Callable>
  1170. static PropertyDescriptor Function(const std::string& utf8name,
  1171. Callable cb,
  1172. napi_property_attributes attributes = napi_default,
  1173. void* data = nullptr);
  1174. template <typename Callable>
  1175. static PropertyDescriptor Function(napi_value name,
  1176. Callable cb,
  1177. napi_property_attributes attributes = napi_default,
  1178. void* data = nullptr);
  1179. template <typename Callable>
  1180. static PropertyDescriptor Function(Name name,
  1181. Callable cb,
  1182. napi_property_attributes attributes = napi_default,
  1183. void* data = nullptr);
  1184. #endif // !NODE_ADDON_API_DISABLE_DEPRECATED
  1185. template <typename Getter>
  1186. static PropertyDescriptor Accessor(Napi::Env env,
  1187. Napi::Object object,
  1188. const char* utf8name,
  1189. Getter getter,
  1190. napi_property_attributes attributes = napi_default,
  1191. void* data = nullptr);
  1192. template <typename Getter>
  1193. static PropertyDescriptor Accessor(Napi::Env env,
  1194. Napi::Object object,
  1195. const std::string& utf8name,
  1196. Getter getter,
  1197. napi_property_attributes attributes = napi_default,
  1198. void* data = nullptr);
  1199. template <typename Getter>
  1200. static PropertyDescriptor Accessor(Napi::Env env,
  1201. Napi::Object object,
  1202. Name name,
  1203. Getter getter,
  1204. napi_property_attributes attributes = napi_default,
  1205. void* data = nullptr);
  1206. template <typename Getter, typename Setter>
  1207. static PropertyDescriptor Accessor(Napi::Env env,
  1208. Napi::Object object,
  1209. const char* utf8name,
  1210. Getter getter,
  1211. Setter setter,
  1212. napi_property_attributes attributes = napi_default,
  1213. void* data = nullptr);
  1214. template <typename Getter, typename Setter>
  1215. static PropertyDescriptor Accessor(Napi::Env env,
  1216. Napi::Object object,
  1217. const std::string& utf8name,
  1218. Getter getter,
  1219. Setter setter,
  1220. napi_property_attributes attributes = napi_default,
  1221. void* data = nullptr);
  1222. template <typename Getter, typename Setter>
  1223. static PropertyDescriptor Accessor(Napi::Env env,
  1224. Napi::Object object,
  1225. Name name,
  1226. Getter getter,
  1227. Setter setter,
  1228. napi_property_attributes attributes = napi_default,
  1229. void* data = nullptr);
  1230. template <typename Callable>
  1231. static PropertyDescriptor Function(Napi::Env env,
  1232. Napi::Object object,
  1233. const char* utf8name,
  1234. Callable cb,
  1235. napi_property_attributes attributes = napi_default,
  1236. void* data = nullptr);
  1237. template <typename Callable>
  1238. static PropertyDescriptor Function(Napi::Env env,
  1239. Napi::Object object,
  1240. const std::string& utf8name,
  1241. Callable cb,
  1242. napi_property_attributes attributes = napi_default,
  1243. void* data = nullptr);
  1244. template <typename Callable>
  1245. static PropertyDescriptor Function(Napi::Env env,
  1246. Napi::Object object,
  1247. Name name,
  1248. Callable cb,
  1249. napi_property_attributes attributes = napi_default,
  1250. void* data = nullptr);
  1251. static PropertyDescriptor Value(const char* utf8name,
  1252. napi_value value,
  1253. napi_property_attributes attributes = napi_default);
  1254. static PropertyDescriptor Value(const std::string& utf8name,
  1255. napi_value value,
  1256. napi_property_attributes attributes = napi_default);
  1257. static PropertyDescriptor Value(napi_value name,
  1258. napi_value value,
  1259. napi_property_attributes attributes = napi_default);
  1260. static PropertyDescriptor Value(Name name,
  1261. Napi::Value value,
  1262. napi_property_attributes attributes = napi_default);
  1263. PropertyDescriptor(napi_property_descriptor desc);
  1264. operator napi_property_descriptor&();
  1265. operator const napi_property_descriptor&() const;
  1266. private:
  1267. napi_property_descriptor _desc;
  1268. };
  1269. /// Property descriptor for use with `ObjectWrap::DefineClass()`.
  1270. ///
  1271. /// This is different from the standalone `PropertyDescriptor` because it is specific to each
  1272. /// `ObjectWrap<T>` subclass. This prevents using descriptors from a different class when
  1273. /// defining a new class (preventing the callbacks from having incorrect `this` pointers).
  1274. template <typename T>
  1275. class ClassPropertyDescriptor {
  1276. public:
  1277. ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {}
  1278. operator napi_property_descriptor&() { return _desc; }
  1279. operator const napi_property_descriptor&() const { return _desc; }
  1280. private:
  1281. napi_property_descriptor _desc;
  1282. };
  1283. /// Base class to be extended by C++ classes exposed to JavaScript; each C++ class instance gets
  1284. /// "wrapped" by a JavaScript object that is managed by this class.
  1285. ///
  1286. /// At initialization time, the `DefineClass()` method must be used to
  1287. /// hook up the accessor and method callbacks. It takes a list of
  1288. /// property descriptors, which can be constructed via the various
  1289. /// static methods on the base class.
  1290. ///
  1291. /// #### Example:
  1292. ///
  1293. /// class Example: public Napi::ObjectWrap<Example> {
  1294. /// public:
  1295. /// static void Initialize(Napi::Env& env, Napi::Object& target) {
  1296. /// Napi::Function constructor = DefineClass(env, "Example", {
  1297. /// InstanceAccessor("value", &Example::GetSomething, &Example::SetSomething),
  1298. /// InstanceMethod("doSomething", &Example::DoSomething),
  1299. /// });
  1300. /// target.Set("Example", constructor);
  1301. /// }
  1302. ///
  1303. /// Example(const Napi::CallbackInfo& info); // Constructor
  1304. /// Napi::Value GetSomething(const Napi::CallbackInfo& info);
  1305. /// void SetSomething(const Napi::CallbackInfo& info, const Napi::Value& value);
  1306. /// Napi::Value DoSomething(const Napi::CallbackInfo& info);
  1307. /// }
  1308. template <typename T>
  1309. class ObjectWrap : public Reference<Object> {
  1310. public:
  1311. ObjectWrap(const CallbackInfo& callbackInfo);
  1312. static T* Unwrap(Object wrapper);
  1313. // Methods exposed to JavaScript must conform to one of these callback signatures.
  1314. typedef void (*StaticVoidMethodCallback)(const CallbackInfo& info);
  1315. typedef Napi::Value (*StaticMethodCallback)(const CallbackInfo& info);
  1316. typedef Napi::Value (*StaticGetterCallback)(const CallbackInfo& info);
  1317. typedef void (*StaticSetterCallback)(const CallbackInfo& info, const Napi::Value& value);
  1318. typedef void (T::*InstanceVoidMethodCallback)(const CallbackInfo& info);
  1319. typedef Napi::Value (T::*InstanceMethodCallback)(const CallbackInfo& info);
  1320. typedef Napi::Value (T::*InstanceGetterCallback)(const CallbackInfo& info);
  1321. typedef void (T::*InstanceSetterCallback)(const CallbackInfo& info, const Napi::Value& value);
  1322. typedef ClassPropertyDescriptor<T> PropertyDescriptor;
  1323. static Function DefineClass(Napi::Env env,
  1324. const char* utf8name,
  1325. const std::initializer_list<PropertyDescriptor>& properties,
  1326. void* data = nullptr);
  1327. static Function DefineClass(Napi::Env env,
  1328. const char* utf8name,
  1329. const std::vector<PropertyDescriptor>& properties,
  1330. void* data = nullptr);
  1331. static PropertyDescriptor StaticMethod(const char* utf8name,
  1332. StaticVoidMethodCallback method,
  1333. napi_property_attributes attributes = napi_default,
  1334. void* data = nullptr);
  1335. static PropertyDescriptor StaticMethod(const char* utf8name,
  1336. StaticMethodCallback method,
  1337. napi_property_attributes attributes = napi_default,
  1338. void* data = nullptr);
  1339. static PropertyDescriptor StaticMethod(Symbol name,
  1340. StaticVoidMethodCallback method,
  1341. napi_property_attributes attributes = napi_default,
  1342. void* data = nullptr);
  1343. static PropertyDescriptor StaticMethod(Symbol name,
  1344. StaticMethodCallback method,
  1345. napi_property_attributes attributes = napi_default,
  1346. void* data = nullptr);
  1347. static PropertyDescriptor StaticAccessor(const char* utf8name,
  1348. StaticGetterCallback getter,
  1349. StaticSetterCallback setter,
  1350. napi_property_attributes attributes = napi_default,
  1351. void* data = nullptr);
  1352. static PropertyDescriptor StaticAccessor(Symbol name,
  1353. StaticGetterCallback getter,
  1354. StaticSetterCallback setter,
  1355. napi_property_attributes attributes = napi_default,
  1356. void* data = nullptr);
  1357. static PropertyDescriptor InstanceMethod(const char* utf8name,
  1358. InstanceVoidMethodCallback method,
  1359. napi_property_attributes attributes = napi_default,
  1360. void* data = nullptr);
  1361. static PropertyDescriptor InstanceMethod(const char* utf8name,
  1362. InstanceMethodCallback method,
  1363. napi_property_attributes attributes = napi_default,
  1364. void* data = nullptr);
  1365. static PropertyDescriptor InstanceMethod(Symbol name,
  1366. InstanceVoidMethodCallback method,
  1367. napi_property_attributes attributes = napi_default,
  1368. void* data = nullptr);
  1369. static PropertyDescriptor InstanceMethod(Symbol name,
  1370. InstanceMethodCallback method,
  1371. napi_property_attributes attributes = napi_default,
  1372. void* data = nullptr);
  1373. static PropertyDescriptor InstanceAccessor(const char* utf8name,
  1374. InstanceGetterCallback getter,
  1375. InstanceSetterCallback setter,
  1376. napi_property_attributes attributes = napi_default,
  1377. void* data = nullptr);
  1378. static PropertyDescriptor InstanceAccessor(Symbol name,
  1379. InstanceGetterCallback getter,
  1380. InstanceSetterCallback setter,
  1381. napi_property_attributes attributes = napi_default,
  1382. void* data = nullptr);
  1383. static PropertyDescriptor StaticValue(const char* utf8name,
  1384. Napi::Value value,
  1385. napi_property_attributes attributes = napi_default);
  1386. static PropertyDescriptor StaticValue(Symbol name,
  1387. Napi::Value value,
  1388. napi_property_attributes attributes = napi_default);
  1389. static PropertyDescriptor InstanceValue(const char* utf8name,
  1390. Napi::Value value,
  1391. napi_property_attributes attributes = napi_default);
  1392. static PropertyDescriptor InstanceValue(Symbol name,
  1393. Napi::Value value,
  1394. napi_property_attributes attributes = napi_default);
  1395. private:
  1396. static napi_value ConstructorCallbackWrapper(napi_env env, napi_callback_info info);
  1397. static napi_value StaticVoidMethodCallbackWrapper(napi_env env, napi_callback_info info);
  1398. static napi_value StaticMethodCallbackWrapper(napi_env env, napi_callback_info info);
  1399. static napi_value StaticGetterCallbackWrapper(napi_env env, napi_callback_info info);
  1400. static napi_value StaticSetterCallbackWrapper(napi_env env, napi_callback_info info);
  1401. static napi_value InstanceVoidMethodCallbackWrapper(napi_env env, napi_callback_info info);
  1402. static napi_value InstanceMethodCallbackWrapper(napi_env env, napi_callback_info info);
  1403. static napi_value InstanceGetterCallbackWrapper(napi_env env, napi_callback_info info);
  1404. static napi_value InstanceSetterCallbackWrapper(napi_env env, napi_callback_info info);
  1405. static void FinalizeCallback(napi_env env, void* data, void* hint);
  1406. static Function DefineClass(Napi::Env env,
  1407. const char* utf8name,
  1408. const size_t props_count,
  1409. const napi_property_descriptor* props,
  1410. void* data = nullptr);
  1411. template <typename TCallback>
  1412. struct MethodCallbackData {
  1413. TCallback callback;
  1414. void* data;
  1415. };
  1416. typedef MethodCallbackData<StaticVoidMethodCallback> StaticVoidMethodCallbackData;
  1417. typedef MethodCallbackData<StaticMethodCallback> StaticMethodCallbackData;
  1418. typedef MethodCallbackData<InstanceVoidMethodCallback> InstanceVoidMethodCallbackData;
  1419. typedef MethodCallbackData<InstanceMethodCallback> InstanceMethodCallbackData;
  1420. template <typename TGetterCallback, typename TSetterCallback>
  1421. struct AccessorCallbackData {
  1422. TGetterCallback getterCallback;
  1423. TSetterCallback setterCallback;
  1424. void* data;
  1425. };
  1426. typedef AccessorCallbackData<StaticGetterCallback, StaticSetterCallback>
  1427. StaticAccessorCallbackData;
  1428. typedef AccessorCallbackData<InstanceGetterCallback, InstanceSetterCallback>
  1429. InstanceAccessorCallbackData;
  1430. };
  1431. class HandleScope {
  1432. public:
  1433. HandleScope(napi_env env, napi_handle_scope scope);
  1434. explicit HandleScope(Napi::Env env);
  1435. ~HandleScope();
  1436. operator napi_handle_scope() const;
  1437. Napi::Env Env() const;
  1438. private:
  1439. napi_env _env;
  1440. napi_handle_scope _scope;
  1441. };
  1442. class EscapableHandleScope {
  1443. public:
  1444. EscapableHandleScope(napi_env env, napi_escapable_handle_scope scope);
  1445. explicit EscapableHandleScope(Napi::Env env);
  1446. ~EscapableHandleScope();
  1447. operator napi_escapable_handle_scope() const;
  1448. Napi::Env Env() const;
  1449. Value Escape(napi_value escapee);
  1450. private:
  1451. napi_env _env;
  1452. napi_escapable_handle_scope _scope;
  1453. };
  1454. #if (NAPI_VERSION > 2)
  1455. class CallbackScope {
  1456. public:
  1457. CallbackScope(napi_env env, napi_callback_scope scope);
  1458. CallbackScope(napi_env env, napi_async_context context);
  1459. virtual ~CallbackScope();
  1460. operator napi_callback_scope() const;
  1461. Napi::Env Env() const;
  1462. private:
  1463. napi_env _env;
  1464. napi_callback_scope _scope;
  1465. };
  1466. #endif
  1467. class AsyncContext {
  1468. public:
  1469. explicit AsyncContext(napi_env env, const char* resource_name);
  1470. explicit AsyncContext(napi_env env, const char* resource_name, const Object& resource);
  1471. virtual ~AsyncContext();
  1472. AsyncContext(AsyncContext&& other);
  1473. AsyncContext& operator =(AsyncContext&& other);
  1474. AsyncContext(const AsyncContext&) = delete;
  1475. AsyncContext& operator =(AsyncContext&) = delete;
  1476. operator napi_async_context() const;
  1477. private:
  1478. napi_env _env;
  1479. napi_async_context _context;
  1480. };
  1481. class AsyncWorker {
  1482. public:
  1483. virtual ~AsyncWorker();
  1484. // An async worker can be moved but cannot be copied.
  1485. AsyncWorker(AsyncWorker&& other);
  1486. AsyncWorker& operator =(AsyncWorker&& other);
  1487. AsyncWorker(const AsyncWorker&) = delete;
  1488. AsyncWorker& operator =(AsyncWorker&) = delete;
  1489. operator napi_async_work() const;
  1490. Napi::Env Env() const;
  1491. void Queue();
  1492. void Cancel();
  1493. ObjectReference& Receiver();
  1494. FunctionReference& Callback();
  1495. protected:
  1496. explicit AsyncWorker(const Function& callback);
  1497. explicit AsyncWorker(const Function& callback,
  1498. const char* resource_name);
  1499. explicit AsyncWorker(const Function& callback,
  1500. const char* resource_name,
  1501. const Object& resource);
  1502. explicit AsyncWorker(const Object& receiver,
  1503. const Function& callback);
  1504. explicit AsyncWorker(const Object& receiver,
  1505. const Function& callback,
  1506. const char* resource_name);
  1507. explicit AsyncWorker(const Object& receiver,
  1508. const Function& callback,
  1509. const char* resource_name,
  1510. const Object& resource);
  1511. virtual void Execute() = 0;
  1512. virtual void OnOK();
  1513. virtual void OnError(const Error& e);
  1514. void SetError(const std::string& error);
  1515. private:
  1516. static void OnExecute(napi_env env, void* this_pointer);
  1517. static void OnWorkComplete(napi_env env,
  1518. napi_status status,
  1519. void* this_pointer);
  1520. napi_env _env;
  1521. napi_async_work _work;
  1522. ObjectReference _receiver;
  1523. FunctionReference _callback;
  1524. std::string _error;
  1525. };
  1526. // Memory management.
  1527. class MemoryManagement {
  1528. public:
  1529. static int64_t AdjustExternalMemory(Env env, int64_t change_in_bytes);
  1530. };
  1531. // Version management
  1532. class VersionManagement {
  1533. public:
  1534. static uint32_t GetNapiVersion(Env env);
  1535. static const napi_node_version* GetNodeVersion(Env env);
  1536. };
  1537. } // namespace Napi
  1538. // Inline implementations of all the above class methods are included here.
  1539. #include "napi-inl.h"
  1540. #endif // SRC_NAPI_H_