napi.h
117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
#ifndef SRC_NAPI_H_
#define SRC_NAPI_H_
#include <node_api.h>
#include <functional>
#include <initializer_list>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
// 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<char16_t*>(L ## x)
#else
#define NAPI_WIDE_TEXT(x) u ## x
#endif
// If C++ exceptions are not explicitly enabled or disabled, enable them
// if exceptions were enabled in the compiler settings.
#if !defined(NAPI_CPP_EXCEPTIONS) && !defined(NAPI_DISABLE_CPP_EXCEPTIONS)
#if defined(_CPPUNWIND) || defined (__EXCEPTIONS)
#define NAPI_CPP_EXCEPTIONS
#else
#error Exception support not detected. \
Define either NAPI_CPP_EXCEPTIONS or NAPI_DISABLE_CPP_EXCEPTIONS.
#endif
#endif
// If C++ NAPI_CPP_EXCEPTIONS are enabled, NODE_ADDON_API_ENABLE_MAYBE should
// not be set
#if defined(NAPI_CPP_EXCEPTIONS) && defined(NODE_ADDON_API_ENABLE_MAYBE)
#error NODE_ADDON_API_ENABLE_MAYBE should not be set when \
NAPI_CPP_EXCEPTIONS is defined.
#endif
#ifdef _NOEXCEPT
#define NAPI_NOEXCEPT _NOEXCEPT
#else
#define NAPI_NOEXCEPT noexcept
#endif
#ifdef NAPI_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 // NAPI_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 // NAPI_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<type>())
#define NAPI_RETURN_OR_THROW_IF_FAILED(env, status, result, type) \
NAPI_MAYBE_THROW_IF_FAILED(env, status, type); \
return Napi::Just<type>(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)
#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 {
// 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 <typename T> class TypedArrayOf;
using Int8Array =
TypedArrayOf<int8_t>; ///< Typed-array of signed 8-bit integers
using Uint8Array =
TypedArrayOf<uint8_t>; ///< Typed-array of unsigned 8-bit integers
using Int16Array =
TypedArrayOf<int16_t>; ///< Typed-array of signed 16-bit integers
using Uint16Array =
TypedArrayOf<uint16_t>; ///< Typed-array of unsigned 16-bit integers
using Int32Array =
TypedArrayOf<int32_t>; ///< Typed-array of signed 32-bit integers
using Uint32Array =
TypedArrayOf<uint32_t>; ///< Typed-array of unsigned 32-bit integers
using Float32Array =
TypedArrayOf<float>; ///< Typed-array of 32-bit floating-point values
using Float64Array =
TypedArrayOf<double>; ///< Typed-array of 64-bit floating-point values
#if NAPI_VERSION > 5
using BigInt64Array =
TypedArrayOf<int64_t>; ///< Typed array of signed 64-bit integers
using BigUint64Array =
TypedArrayOf<uint64_t>; ///< 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 T>
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 <class U>
friend Maybe<U> Nothing();
template <class U>
friend Maybe<U> Just(const U& u);
};
template <class T>
inline Maybe<T> Nothing();
template <class T>
inline Maybe<T> Just(const T& t);
#if defined(NODE_ADDON_API_ENABLE_MAYBE)
template <typename T>
using MaybeOrValue = Maybe<T>;
#else
template <typename T>
using MaybeOrValue = T;
#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.)
///
/// In the future, multiple environments per process may be supported,
/// although current implementations only support one environment per process.
///
/// In the V8 JavaScript engine, a Node-API environment approximately
/// corresponds to an Isolate.
class Env {
private:
#if NAPI_VERSION > 2
template <typename Hook, typename Arg = void>
class CleanupHook;
#endif // NAPI_VERSION > 2
#if NAPI_VERSION > 5
template <typename T> static void DefaultFini(Env, T* data);
template <typename DataType, typename HintType>
static void DefaultFiniWithHint(Env, DataType* data, HintType* hint);
#endif // NAPI_VERSION > 5
public:
Env(napi_env env);
operator napi_env() const;
Object Global() const;
Value Undefined() const;
Value Null() const;
bool IsExceptionPending() const;
Error GetAndClearPendingException();
MaybeOrValue<Value> RunScript(const char* utf8script);
MaybeOrValue<Value> RunScript(const std::string& utf8script);
MaybeOrValue<Value> RunScript(String script);
#if NAPI_VERSION > 2
template <typename Hook>
CleanupHook<Hook> AddCleanupHook(Hook hook);
template <typename Hook, typename Arg>
CleanupHook<Hook, Arg> AddCleanupHook(Hook hook, Arg* arg);
#endif // NAPI_VERSION > 2
#if NAPI_VERSION > 5
template <typename T> T* GetInstanceData();
template <typename T> using Finalizer = void (*)(Env, T*);
template <typename T, Finalizer<T> fini = Env::DefaultFini<T>>
void SetInstanceData(T* data);
template <typename DataType, typename HintType>
using FinalizerWithHint = void (*)(Env, DataType*, HintType*);
template <typename DataType,
typename HintType,
FinalizerWithHint<DataType, HintType> fini =
Env::DefaultFiniWithHint<DataType, HintType>>
void SetInstanceData(DataType* data, HintType* hint);
#endif // NAPI_VERSION > 5
private:
napi_env _env;
#if NAPI_VERSION > 2
template <typename Hook, typename Arg>
class CleanupHook {
public:
CleanupHook(Env env, Hook hook, Arg* arg);
CleanupHook(Env env, Hook hook);
bool Remove(Env 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
/// 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<Napi::String>(); // 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 <typename T>
static Value From(napi_env env, const T& 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.
/// 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`.
template <typename T> T As() const;
MaybeOrValue<Boolean> ToBoolean()
const; ///< Coerces a value to a JavaScript boolean.
MaybeOrValue<Number> ToNumber()
const; ///< Coerces a value to a JavaScript number.
MaybeOrValue<String> ToString()
const; ///< Coerces a value to a JavaScript string.
MaybeOrValue<Object> 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
);
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
);
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
);
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
);
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:
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.
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 <typename T>
static String From(napi_env env, const T& 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
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<Symbol> WellKnown(napi_env, const std::string& name);
// Create a symbol in the global registry, UTF-8 Encoded cpp string
static MaybeOrValue<Symbol> For(napi_env env,
const std::string& description);
// Create a symbol in the global registry, C style string (null terminated)
static MaybeOrValue<Symbol> For(napi_env env, const char* description);
// Create a symbol in the global registry, String value describing the symbol
static MaybeOrValue<Symbol> For(napi_env env, String description);
// Create a symbol in the global registry, napi_value describing the symbol
static MaybeOrValue<Symbol> For(napi_env env, napi_value description);
Symbol(); ///< Creates a new _empty_ Symbol instance.
Symbol(napi_env env,
napi_value value); ///< Wraps a Node-API value primitive.
};
/// A JavaScript object value.
class Object : public Value {
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 <typename Key>
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 <typename ValueType>
PropertyLValue& operator =(ValueType value);
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
);
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<std::string> operator [](
const char* utf8name ///< UTF-8 encoded null-terminated property name
);
/// Gets or sets a named property.
PropertyLValue<std::string> operator [](
const std::string& utf8name ///< UTF-8 encoded property name
);
/// Gets or sets an indexed property or array element.
PropertyLValue<uint32_t> operator [](
uint32_t index /// Property / element index
);
/// Gets a named property.
MaybeOrValue<Value> operator[](
const char* utf8name ///< UTF-8 encoded null-terminated property name
) const;
/// Gets a named property.
MaybeOrValue<Value> operator[](
const std::string& utf8name ///< UTF-8 encoded property name
) const;
/// Gets an indexed property or array element.
MaybeOrValue<Value> operator[](uint32_t index ///< Property / element index
) const;
/// Checks whether a property is present.
MaybeOrValue<bool> Has(napi_value key ///< Property key primitive
) const;
/// Checks whether a property is present.
MaybeOrValue<bool> Has(Value key ///< Property key
) const;
/// Checks whether a named property is present.
MaybeOrValue<bool> Has(
const char* utf8name ///< UTF-8 encoded null-terminated property name
) const;
/// Checks whether a named property is present.
MaybeOrValue<bool> Has(
const std::string& utf8name ///< UTF-8 encoded property name
) const;
/// Checks whether a own property is present.
MaybeOrValue<bool> HasOwnProperty(
napi_value key ///< Property key primitive
) const;
/// Checks whether a own property is present.
MaybeOrValue<bool> HasOwnProperty(Value key ///< Property key
) const;
/// Checks whether a own property is present.
MaybeOrValue<bool> HasOwnProperty(
const char* utf8name ///< UTF-8 encoded null-terminated property name
) const;
/// Checks whether a own property is present.
MaybeOrValue<bool> HasOwnProperty(
const std::string& utf8name ///< UTF-8 encoded property name
) const;
/// Gets a property.
MaybeOrValue<Value> Get(napi_value key ///< Property key primitive
) const;
/// Gets a property.
MaybeOrValue<Value> Get(Value key ///< Property key
) const;
/// Gets a named property.
MaybeOrValue<Value> Get(
const char* utf8name ///< UTF-8 encoded null-terminated property name
) const;
/// Gets a named property.
MaybeOrValue<Value> Get(
const std::string& utf8name ///< UTF-8 encoded property name
) const;
/// Sets a property.
template <typename ValueType>
MaybeOrValue<bool> Set(napi_value key, ///< Property key primitive
const ValueType& value ///< Property value primitive
);
/// Sets a property.
template <typename ValueType>
MaybeOrValue<bool> Set(Value key, ///< Property key
const ValueType& value ///< Property value
);
/// Sets a named property.
template <typename ValueType>
MaybeOrValue<bool> Set(
const char* utf8name, ///< UTF-8 encoded null-terminated property name
const ValueType& value);
/// Sets a named property.
template <typename ValueType>
MaybeOrValue<bool> Set(
const std::string& utf8name, ///< UTF-8 encoded property name
const ValueType& value ///< Property value primitive
);
/// Delete property.
MaybeOrValue<bool> Delete(napi_value key ///< Property key primitive
);
/// Delete property.
MaybeOrValue<bool> Delete(Value key ///< Property key
);
/// Delete property.
MaybeOrValue<bool> Delete(
const char* utf8name ///< UTF-8 encoded null-terminated property name
);
/// Delete property.
MaybeOrValue<bool> Delete(
const std::string& utf8name ///< UTF-8 encoded property name
);
/// Checks whether an indexed property is present.
MaybeOrValue<bool> Has(uint32_t index ///< Property / element index
) const;
/// Gets an indexed property or array element.
MaybeOrValue<Value> Get(uint32_t index ///< Property / element index
) const;
/// Sets an indexed property or array element.
template <typename ValueType>
MaybeOrValue<bool> Set(uint32_t index, ///< Property / element index
const ValueType& value ///< Property value primitive
);
/// Deletes an indexed property or array element.
MaybeOrValue<bool> Delete(uint32_t index ///< Property / element index
);
/// 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<Array> 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<bool> DefineProperty(
const PropertyDescriptor&
property ///< Descriptor for the property to be defined
);
/// 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<bool> DefineProperties(
const std::initializer_list<PropertyDescriptor>& properties
///< List of descriptors for the properties to be defined
);
/// 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<bool> DefineProperties(
const std::vector<PropertyDescriptor>& properties
///< Vector of descriptors for the properties to be defined
);
/// 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<bool> InstanceOf(
const Function& constructor ///< Constructor function
) const;
template <typename Finalizer, typename T>
inline void AddFinalizer(Finalizer finalizeCallback, T* data);
template <typename Finalizer, typename T, typename Hint>
inline void AddFinalizer(Finalizer finalizeCallback,
T* data,
Hint* finalizeHint);
#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<bool> Freeze();
/// 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<bool> Seal();
#endif // NAPI_VERSION >= 8
};
template <typename T>
class External : public Value {
public:
static External New(napi_env env, T* data);
// Finalizer must implement `void operator()(Env env, T* data)`.
template <typename Finalizer>
static External New(napi_env env,
T* data,
Finalizer finalizeCallback);
// Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`.
template <typename Finalizer, typename Hint>
static External New(napi_env env,
T* data,
Finalizer finalizeCallback,
Hint* finalizeHint);
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);
Array();
Array(napi_env env, napi_value value);
uint32_t Length() const;
};
/// 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
);
/// 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 <typename Finalizer>
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 <typename Finalizer, typename Hint>
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
);
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<T>` instance using the `As()`
/// method:
///
/// Napi::TypedArray array = ...
/// if (t.TypedArrayType() == napi_int32_array) {
/// Napi::Int32Array int32Array = t.As<Napi::Int32Array>();
/// }
class TypedArray : public Object {
public:
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.
Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer.
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);
static const napi_typedarray_type unknown_array_type = static_cast<napi_typedarray_type>(-1);
template <typename T>
static
#if defined(NAPI_HAS_CONSTEXPR)
constexpr
#endif
napi_typedarray_type TypedArrayTypeForPrimitiveType() {
return std::is_same<T, int8_t>::value ? napi_int8_array
: std::is_same<T, uint8_t>::value ? napi_uint8_array
: std::is_same<T, int16_t>::value ? napi_int16_array
: std::is_same<T, uint16_t>::value ? napi_uint16_array
: std::is_same<T, int32_t>::value ? napi_int32_array
: std::is_same<T, uint32_t>::value ? napi_uint32_array
: std::is_same<T, float>::value ? napi_float32_array
: std::is_same<T, double>::value ? napi_float64_array
#if NAPI_VERSION > 5
: std::is_same<T, int64_t>::value ? napi_bigint64_array
: std::is_same<T, uint64_t>::value ? napi_biguint64_array
#endif // NAPI_VERSION > 5
: unknown_array_type;
}
/// !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 <typename T>
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<T>()
#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<T>()
#else
napi_typedarray_type type
#endif
///< Type of array, if different from the default array type for the
///< template parameter T.
);
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);
DataView(); ///< Creates a new _empty_ DataView instance.
DataView(napi_env env,
napi_value value); ///< Wraps a Node-API value primitive.
Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer.
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 <typename T>
T ReadData(size_t byteOffset) const;
template <typename T>
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 <VoidCallback cb>
static Function New(napi_env env,
const char* utf8name = nullptr,
void* data = nullptr);
template <Callback cb>
static Function New(napi_env env,
const char* utf8name = nullptr,
void* data = nullptr);
template <VoidCallback cb>
static Function New(napi_env env,
const std::string& utf8name,
void* data = nullptr);
template <Callback cb>
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 <typename Callable>
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 <typename Callable>
static Function New(napi_env env,
Callable cb,
const std::string& utf8name,
void* data = nullptr);
Function();
Function(napi_env env, napi_value value);
MaybeOrValue<Value> operator()(
const std::initializer_list<napi_value>& args) const;
MaybeOrValue<Value> Call(
const std::initializer_list<napi_value>& args) const;
MaybeOrValue<Value> Call(const std::vector<napi_value>& args) const;
MaybeOrValue<Value> Call(size_t argc, const napi_value* args) const;
MaybeOrValue<Value> Call(
napi_value recv, const std::initializer_list<napi_value>& args) const;
MaybeOrValue<Value> Call(napi_value recv,
const std::vector<napi_value>& args) const;
MaybeOrValue<Value> Call(napi_value recv,
size_t argc,
const napi_value* args) const;
MaybeOrValue<Value> MakeCallback(
napi_value recv,
const std::initializer_list<napi_value>& args,
napi_async_context context = nullptr) const;
MaybeOrValue<Value> MakeCallback(napi_value recv,
const std::vector<napi_value>& args,
napi_async_context context = nullptr) const;
MaybeOrValue<Value> MakeCallback(napi_value recv,
size_t argc,
const napi_value* args,
napi_async_context context = nullptr) const;
MaybeOrValue<Object> New(
const std::initializer_list<napi_value>& args) const;
MaybeOrValue<Object> New(const std::vector<napi_value>& args) const;
MaybeOrValue<Object> 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;
};
Promise(napi_env env, napi_value value);
};
template <typename T>
class Buffer : public Uint8Array {
public:
static Buffer<T> New(napi_env env, size_t length);
static Buffer<T> New(napi_env env, T* data, size_t length);
// Finalizer must implement `void operator()(Env env, T* data)`.
template <typename Finalizer>
static Buffer<T> New(napi_env env, T* data,
size_t length,
Finalizer finalizeCallback);
// Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`.
template <typename Finalizer, typename Hint>
static Buffer<T> New(napi_env env, T* data,
size_t length,
Finalizer finalizeCallback,
Hint* finalizeHint);
static Buffer<T> Copy(napi_env env, const T* data, size_t length);
Buffer();
Buffer(napi_env env, napi_value value);
size_t Length() const;
T* Data() const;
private:
mutable size_t _length;
mutable T* _data;
Buffer(napi_env env, napi_value value, size_t length, T* data);
void EnsureInfo() const;
};
/// 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 <typename T>
class Reference {
public:
static Reference<T> 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<T>&& other);
Reference<T>& operator =(Reference<T>&& other);
NAPI_DISALLOW_ASSIGN(Reference<T>)
operator napi_ref() const;
bool operator ==(const Reference<T> &other) const;
bool operator !=(const Reference<T> &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();
uint32_t Unref();
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<T>&);
/// !cond INTERNAL
napi_env _env;
napi_ref _ref;
/// !endcond
private:
bool _suppressDestruct;
};
class ObjectReference: public Reference<Object> {
public:
ObjectReference();
ObjectReference(napi_env env, napi_ref ref);
// A reference can be moved but cannot be copied.
ObjectReference(Reference<Object>&& other);
ObjectReference& operator =(Reference<Object>&& other);
ObjectReference(ObjectReference&& other);
ObjectReference& operator =(ObjectReference&& other);
NAPI_DISALLOW_ASSIGN(ObjectReference)
MaybeOrValue<Napi::Value> Get(const char* utf8name) const;
MaybeOrValue<Napi::Value> Get(const std::string& utf8name) const;
MaybeOrValue<bool> Set(const char* utf8name, napi_value value);
MaybeOrValue<bool> Set(const char* utf8name, Napi::Value value);
MaybeOrValue<bool> Set(const char* utf8name, const char* utf8value);
MaybeOrValue<bool> Set(const char* utf8name, bool boolValue);
MaybeOrValue<bool> Set(const char* utf8name, double numberValue);
MaybeOrValue<bool> Set(const std::string& utf8name, napi_value value);
MaybeOrValue<bool> Set(const std::string& utf8name, Napi::Value value);
MaybeOrValue<bool> Set(const std::string& utf8name, std::string& utf8value);
MaybeOrValue<bool> Set(const std::string& utf8name, bool boolValue);
MaybeOrValue<bool> Set(const std::string& utf8name, double numberValue);
MaybeOrValue<Napi::Value> Get(uint32_t index) const;
MaybeOrValue<bool> Set(uint32_t index, const napi_value value);
MaybeOrValue<bool> Set(uint32_t index, const Napi::Value value);
MaybeOrValue<bool> Set(uint32_t index, const char* utf8value);
MaybeOrValue<bool> Set(uint32_t index, const std::string& utf8value);
MaybeOrValue<bool> Set(uint32_t index, bool boolValue);
MaybeOrValue<bool> Set(uint32_t index, double numberValue);
protected:
ObjectReference(const ObjectReference&);
};
class FunctionReference: public Reference<Function> {
public:
FunctionReference();
FunctionReference(napi_env env, napi_ref ref);
// A reference can be moved but cannot be copied.
FunctionReference(Reference<Function>&& other);
FunctionReference& operator =(Reference<Function>&& other);
FunctionReference(FunctionReference&& other);
FunctionReference& operator =(FunctionReference&& other);
NAPI_DISALLOW_ASSIGN_COPY(FunctionReference)
MaybeOrValue<Napi::Value> operator()(
const std::initializer_list<napi_value>& args) const;
MaybeOrValue<Napi::Value> Call(
const std::initializer_list<napi_value>& args) const;
MaybeOrValue<Napi::Value> Call(const std::vector<napi_value>& args) const;
MaybeOrValue<Napi::Value> Call(
napi_value recv, const std::initializer_list<napi_value>& args) const;
MaybeOrValue<Napi::Value> Call(napi_value recv,
const std::vector<napi_value>& args) const;
MaybeOrValue<Napi::Value> Call(napi_value recv,
size_t argc,
const napi_value* args) const;
MaybeOrValue<Napi::Value> MakeCallback(
napi_value recv,
const std::initializer_list<napi_value>& args,
napi_async_context context = nullptr) const;
MaybeOrValue<Napi::Value> MakeCallback(
napi_value recv,
const std::vector<napi_value>& args,
napi_async_context context = nullptr) const;
MaybeOrValue<Napi::Value> MakeCallback(
napi_value recv,
size_t argc,
const napi_value* args,
napi_async_context context = nullptr) const;
MaybeOrValue<Object> New(
const std::initializer_list<napi_value>& args) const;
MaybeOrValue<Object> New(const std::vector<napi_value>& args) const;
};
// Shortcuts to creating a new reference with inferred type and refcount = 0.
template <typename T> Reference<T> Weak(T value);
ObjectReference Weak(Object value);
FunctionReference Weak(Function value);
// Shortcuts to creating a new reference with inferred type and refcount = 1.
template <typename T> Reference<T> 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 propataged as a JavaScript
/// exception when the callback returns to JavaScript.
///
/// #### Example 2A - Propagating a Node-API C++ exception:
///
/// Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>();
/// 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::Function>();
/// 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 `NAPI_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::Function>();
/// 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::Function>();
/// 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 NAPI_CPP_EXCEPTIONS
, public std::exception
#endif // NAPI_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;
#ifdef NAPI_CPP_EXCEPTIONS
const char* what() const NAPI_NOEXCEPT override;
#endif // NAPI_CPP_EXCEPTIONS
protected:
/// !cond INTERNAL
using create_error_fn = napi_status (*)(napi_env envb,
napi_value code,
napi_value msg,
napi_value* result);
template <typename TError>
static TError New(napi_env env,
const char* message,
size_t length,
create_error_fn create_error);
/// !endcond
private:
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);
};
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);
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 <typename Getter>
static PropertyDescriptor Accessor(const char* utf8name,
Getter getter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter>
static PropertyDescriptor Accessor(const std::string& utf8name,
Getter getter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter>
static PropertyDescriptor Accessor(napi_value name,
Getter getter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter>
static PropertyDescriptor Accessor(Name name,
Getter getter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter, typename Setter>
static PropertyDescriptor Accessor(const char* utf8name,
Getter getter,
Setter setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter, typename Setter>
static PropertyDescriptor Accessor(const std::string& utf8name,
Getter getter,
Setter setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter, typename Setter>
static PropertyDescriptor Accessor(napi_value name,
Getter getter,
Setter setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter, typename Setter>
static PropertyDescriptor Accessor(Name name,
Getter getter,
Setter setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Callable>
static PropertyDescriptor Function(const char* utf8name,
Callable cb,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Callable>
static PropertyDescriptor Function(const std::string& utf8name,
Callable cb,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Callable>
static PropertyDescriptor Function(napi_value name,
Callable cb,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Callable>
static PropertyDescriptor Function(Name name,
Callable cb,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
#endif // !NODE_ADDON_API_DISABLE_DEPRECATED
template <GetterCallback Getter>
static PropertyDescriptor Accessor(const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <GetterCallback Getter>
static PropertyDescriptor Accessor(const std::string& utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <GetterCallback Getter>
static PropertyDescriptor Accessor(Name name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <GetterCallback Getter, SetterCallback Setter>
static PropertyDescriptor Accessor(const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <GetterCallback Getter, SetterCallback Setter>
static PropertyDescriptor Accessor(const std::string& utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <GetterCallback Getter, SetterCallback Setter>
static PropertyDescriptor Accessor(Name name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter>
static PropertyDescriptor Accessor(Napi::Env env,
Napi::Object object,
const char* utf8name,
Getter getter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter>
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 <typename Getter>
static PropertyDescriptor Accessor(Napi::Env env,
Napi::Object object,
Name name,
Getter getter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Getter, typename Setter>
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 <typename Getter, typename Setter>
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 <typename Getter, typename Setter>
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 <typename Callable>
static PropertyDescriptor Function(Napi::Env env,
Napi::Object object,
const char* utf8name,
Callable cb,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <typename Callable>
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 <typename Callable>
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<T>` subclass. This prevents using descriptors from a different class when
/// defining a new class (preventing the callbacks from having incorrect `this` pointers).
template <typename T>
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 <typename T, typename TCallback>
struct MethodCallbackData {
TCallback callback;
void* data;
};
template <typename T, typename TGetterCallback, typename TSetterCallback>
struct AccessorCallbackData {
TGetterCallback getterCallback;
TSetterCallback setterCallback;
void* data;
};
template <typename T>
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<T>;
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 <InstanceVoidMethodCallback method>
static PropertyDescriptor InstanceMethod(const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <InstanceMethodCallback method>
static PropertyDescriptor InstanceMethod(const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <InstanceVoidMethodCallback method>
static PropertyDescriptor InstanceMethod(Symbol name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <InstanceMethodCallback method>
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 <InstanceGetterCallback getter, InstanceSetterCallback setter=nullptr>
static PropertyDescriptor InstanceAccessor(const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <InstanceGetterCallback getter, InstanceSetterCallback setter=nullptr>
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<T>;
using InstanceVoidMethodCallbackData =
MethodCallbackData<T, InstanceVoidMethodCallback>;
using InstanceMethodCallbackData =
MethodCallbackData<T, InstanceMethodCallback>;
using InstanceAccessorCallbackData =
AccessorCallbackData<T, InstanceGetterCallback, InstanceSetterCallback>;
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 <InstanceSetterCallback method>
static napi_value WrappedMethod(napi_env env,
napi_callback_info info) NAPI_NOEXCEPT;
template <InstanceSetterCallback setter> struct SetterTag {};
template <InstanceSetterCallback setter>
static napi_callback WrapSetter(SetterTag<setter>) NAPI_NOEXCEPT {
return &This::WrappedMethod<setter>;
}
static napi_callback WrapSetter(SetterTag<nullptr>) 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<Example> {
/// 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 <typename T>
class ObjectWrap : public InstanceWrap<T>, public Reference<Object> {
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<T>;
static Function DefineClass(Napi::Env env,
const char* utf8name,
const std::initializer_list<PropertyDescriptor>& properties,
void* data = nullptr);
static Function DefineClass(Napi::Env env,
const char* utf8name,
const std::vector<PropertyDescriptor>& 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 <StaticVoidMethodCallback method>
static PropertyDescriptor StaticMethod(const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <StaticVoidMethodCallback method>
static PropertyDescriptor StaticMethod(Symbol name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <StaticMethodCallback method>
static PropertyDescriptor StaticMethod(const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <StaticMethodCallback method>
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 <StaticGetterCallback getter, StaticSetterCallback setter=nullptr>
static PropertyDescriptor StaticAccessor(const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
template <StaticGetterCallback getter, StaticSetterCallback setter=nullptr>
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);
virtual void Finalize(Napi::Env env);
private:
using This = ObjectWrap<T>;
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(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<T, StaticVoidMethodCallback>;
using StaticMethodCallbackData =
MethodCallbackData<T, StaticMethodCallback>;
using StaticAccessorCallbackData =
AccessorCallbackData<T, StaticGetterCallback, StaticSetterCallback>;
template <StaticSetterCallback method>
static napi_value WrappedMethod(napi_env env,
napi_callback_info info) NAPI_NOEXCEPT;
template <StaticSetterCallback setter> struct StaticSetterTag {};
template <StaticSetterCallback setter>
static napi_callback WrapStaticSetter(StaticSetterTag<setter>)
NAPI_NOEXCEPT {
return &This::WrappedMethod<setter>;
}
static napi_callback WrapStaticSetter(StaticSetterTag<nullptr>)
NAPI_NOEXCEPT {
return nullptr;
}
bool _construction_failed = true;
};
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;
};
class AsyncWorker {
public:
virtual ~AsyncWorker();
// An async worker can be moved but cannot be copied.
AsyncWorker(AsyncWorker&& other);
AsyncWorker& operator =(AsyncWorker&& other);
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<napi_value> 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;
};
#if (NAPI_VERSION > 3 && !defined(__wasm32__))
class ThreadSafeFunction {
public:
// This API may only be called from the main thread.
template <typename ResourceString>
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 <typename ResourceString, typename ContextType>
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 <typename ResourceString, typename Finalizer>
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 <typename ResourceString, typename Finalizer,
typename FinalizerDataType>
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 <typename ResourceString, typename ContextType, typename Finalizer>
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 <typename ResourceString, typename ContextType,
typename Finalizer, typename FinalizerDataType>
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 <typename ResourceString>
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 <typename ResourceString, typename ContextType>
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 <typename ResourceString, typename Finalizer>
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 <typename ResourceString, typename Finalizer,
typename FinalizerDataType>
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 <typename ResourceString, typename ContextType, typename Finalizer>
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 <typename ResourceString, typename ContextType,
typename Finalizer, typename FinalizerDataType>
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 <typename Callback>
napi_status BlockingCall(Callback callback) const;
// This API may be called from any thread.
template <typename DataType, typename Callback>
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 <typename Callback>
napi_status NonBlockingCall(Callback callback) const;
// This API may be called from any thread.
template <typename DataType, typename Callback>
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();
// This API may be called from any thread.
napi_status Abort();
struct ConvertibleContext
{
template <class T>
operator T*() { return static_cast<T*>(context); }
void* context;
};
// This API may be called from any thread.
ConvertibleContext GetContext() const;
private:
using CallbackWrapper = std::function<void(Napi::Env, Napi::Function)>;
template <typename ResourceString, typename ContextType,
typename Finalizer, typename FinalizerDataType>
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 <typename ContextType = std::nullptr_t,
typename DataType = void,
void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*) =
nullptr>
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 <typename ResourceString>
static TypedThreadSafeFunction<ContextType, DataType, CallJs> 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 <typename ResourceString>
static TypedThreadSafeFunction<ContextType, DataType, CallJs> 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 <typename ResourceString,
typename Finalizer,
typename FinalizerDataType = void>
static TypedThreadSafeFunction<ContextType, DataType, CallJs> 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 <typename ResourceString,
typename Finalizer,
typename FinalizerDataType = void>
static TypedThreadSafeFunction<ContextType, DataType, CallJs> 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 <typename ResourceString>
static TypedThreadSafeFunction<ContextType, DataType, CallJs> 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 <typename ResourceString>
static TypedThreadSafeFunction<ContextType, DataType, CallJs> 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 <typename ResourceString,
typename Finalizer,
typename FinalizerDataType = void>
static TypedThreadSafeFunction<ContextType, DataType, CallJs> 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 <typename CallbackType,
typename ResourceString,
typename Finalizer,
typename FinalizerDataType>
static TypedThreadSafeFunction<ContextType, DataType, CallJs> 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();
// This API may be called from any thread.
napi_status Abort();
// This API may be called from any thread.
ContextType* GetContext() const;
private:
template <typename ResourceString,
typename Finalizer,
typename FinalizerDataType>
static TypedThreadSafeFunction<ContextType, DataType, CallJs> 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 <typename DataType>
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 T>
class AsyncProgressWorker : public AsyncProgressWorkerBase<void> {
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() const;
void SendProgress_(const T* data, size_t count);
std::mutex _mutex;
T* _asyncdata;
size_t _asyncsize;
};
template<class T>
class AsyncProgressQueueWorker : public AsyncProgressWorkerBase<std::pair<T*, size_t>> {
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<T*, size_t>*) 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 && !defined(__wasm32__)
// Memory management.
class MemoryManagement {
public:
static int64_t AdjustExternalMemory(Env env, int64_t change_in_bytes);
};
// Version management
class VersionManagement {
public:
static uint32_t GetNapiVersion(Env env);
static const napi_node_version* GetNodeVersion(Env env);
};
#if NAPI_VERSION > 5
template <typename T>
class Addon : public InstanceWrap<T> {
public:
static inline Object Init(Env env, Object exports);
static T* Unwrap(Object wrapper);
protected:
using AddonProp = ClassPropertyDescriptor<T>;
void DefineAddon(Object exports,
const std::initializer_list<AddonProp>& props);
Napi::Object DefineProperties(Object object,
const std::initializer_list<AddonProp>& props);
private:
Object entry_point_;
};
#endif // NAPI_VERSION > 5
} // namespace Napi
// Inline implementations of all the above class methods are included here.
#include "napi-inl.h"
#endif // SRC_NAPI_H_