napi-inl.h 213 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588
  1. #ifndef SRC_NAPI_INL_H_
  2. #define SRC_NAPI_INL_H_
  3. ////////////////////////////////////////////////////////////////////////////////
  4. // Node-API C++ Wrapper Classes
  5. //
  6. // Inline header-only implementations for "Node-API" ABI-stable C APIs for
  7. // Node.js.
  8. ////////////////////////////////////////////////////////////////////////////////
  9. // Note: Do not include this file directly! Include "napi.h" instead.
  10. #include <algorithm>
  11. #include <cstring>
  12. #if NAPI_HAS_THREADS
  13. #include <mutex>
  14. #endif // NAPI_HAS_THREADS
  15. #include <type_traits>
  16. #include <utility>
  17. namespace Napi {
  18. #ifdef NAPI_CPP_CUSTOM_NAMESPACE
  19. namespace NAPI_CPP_CUSTOM_NAMESPACE {
  20. #endif
  21. // Helpers to handle functions exposed from C++ and internal constants.
  22. namespace details {
  23. // New napi_status constants not yet available in all supported versions of
  24. // Node.js releases. Only necessary when they are used in napi.h and napi-inl.h.
  25. constexpr int napi_no_external_buffers_allowed = 22;
  26. // Attach a data item to an object and delete it when the object gets
  27. // garbage-collected.
  28. // TODO: Replace this code with `napi_add_finalizer()` whenever it becomes
  29. // available on all supported versions of Node.js.
  30. template <typename FreeType>
  31. inline napi_status AttachData(napi_env env,
  32. napi_value obj,
  33. FreeType* data,
  34. napi_finalize finalizer = nullptr,
  35. void* hint = nullptr) {
  36. napi_status status;
  37. if (finalizer == nullptr) {
  38. finalizer = [](napi_env /*env*/, void* data, void* /*hint*/) {
  39. delete static_cast<FreeType*>(data);
  40. };
  41. }
  42. #if (NAPI_VERSION < 5)
  43. napi_value symbol, external;
  44. status = napi_create_symbol(env, nullptr, &symbol);
  45. if (status == napi_ok) {
  46. status = napi_create_external(env, data, finalizer, hint, &external);
  47. if (status == napi_ok) {
  48. napi_property_descriptor desc = {nullptr,
  49. symbol,
  50. nullptr,
  51. nullptr,
  52. nullptr,
  53. external,
  54. napi_default,
  55. nullptr};
  56. status = napi_define_properties(env, obj, 1, &desc);
  57. }
  58. }
  59. #else // NAPI_VERSION >= 5
  60. status = napi_add_finalizer(env, obj, data, finalizer, hint, nullptr);
  61. #endif
  62. return status;
  63. }
  64. // For use in JS to C++ callback wrappers to catch any Napi::Error exceptions
  65. // and rethrow them as JavaScript exceptions before returning from the callback.
  66. template <typename Callable>
  67. inline napi_value WrapCallback(Callable callback) {
  68. #ifdef NAPI_CPP_EXCEPTIONS
  69. try {
  70. return callback();
  71. } catch (const Error& e) {
  72. e.ThrowAsJavaScriptException();
  73. return nullptr;
  74. }
  75. #else // NAPI_CPP_EXCEPTIONS
  76. // When C++ exceptions are disabled, errors are immediately thrown as JS
  77. // exceptions, so there is no need to catch and rethrow them here.
  78. return callback();
  79. #endif // NAPI_CPP_EXCEPTIONS
  80. }
  81. // For use in JS to C++ void callback wrappers to catch any Napi::Error
  82. // exceptions and rethrow them as JavaScript exceptions before returning from
  83. // the callback.
  84. template <typename Callable>
  85. inline void WrapVoidCallback(Callable callback) {
  86. #ifdef NAPI_CPP_EXCEPTIONS
  87. try {
  88. callback();
  89. } catch (const Error& e) {
  90. e.ThrowAsJavaScriptException();
  91. }
  92. #else // NAPI_CPP_EXCEPTIONS
  93. // When C++ exceptions are disabled, errors are immediately thrown as JS
  94. // exceptions, so there is no need to catch and rethrow them here.
  95. callback();
  96. #endif // NAPI_CPP_EXCEPTIONS
  97. }
  98. template <typename Callable, typename Return>
  99. struct CallbackData {
  100. static inline napi_value Wrapper(napi_env env, napi_callback_info info) {
  101. return details::WrapCallback([&] {
  102. CallbackInfo callbackInfo(env, info);
  103. CallbackData* callbackData =
  104. static_cast<CallbackData*>(callbackInfo.Data());
  105. callbackInfo.SetData(callbackData->data);
  106. return callbackData->callback(callbackInfo);
  107. });
  108. }
  109. Callable callback;
  110. void* data;
  111. };
  112. template <typename Callable>
  113. struct CallbackData<Callable, void> {
  114. static inline napi_value Wrapper(napi_env env, napi_callback_info info) {
  115. return details::WrapCallback([&] {
  116. CallbackInfo callbackInfo(env, info);
  117. CallbackData* callbackData =
  118. static_cast<CallbackData*>(callbackInfo.Data());
  119. callbackInfo.SetData(callbackData->data);
  120. callbackData->callback(callbackInfo);
  121. return nullptr;
  122. });
  123. }
  124. Callable callback;
  125. void* data;
  126. };
  127. template <void (*Callback)(const CallbackInfo& info)>
  128. napi_value TemplatedVoidCallback(napi_env env,
  129. napi_callback_info info) NAPI_NOEXCEPT {
  130. return details::WrapCallback([&] {
  131. CallbackInfo cbInfo(env, info);
  132. Callback(cbInfo);
  133. return nullptr;
  134. });
  135. }
  136. template <Napi::Value (*Callback)(const CallbackInfo& info)>
  137. napi_value TemplatedCallback(napi_env env,
  138. napi_callback_info info) NAPI_NOEXCEPT {
  139. return details::WrapCallback([&] {
  140. CallbackInfo cbInfo(env, info);
  141. return Callback(cbInfo);
  142. });
  143. }
  144. template <typename T,
  145. Napi::Value (T::*UnwrapCallback)(const CallbackInfo& info)>
  146. napi_value TemplatedInstanceCallback(napi_env env,
  147. napi_callback_info info) NAPI_NOEXCEPT {
  148. return details::WrapCallback([&] {
  149. CallbackInfo cbInfo(env, info);
  150. T* instance = T::Unwrap(cbInfo.This().As<Object>());
  151. return (instance->*UnwrapCallback)(cbInfo);
  152. });
  153. }
  154. template <typename T, void (T::*UnwrapCallback)(const CallbackInfo& info)>
  155. napi_value TemplatedInstanceVoidCallback(napi_env env, napi_callback_info info)
  156. NAPI_NOEXCEPT {
  157. return details::WrapCallback([&] {
  158. CallbackInfo cbInfo(env, info);
  159. T* instance = T::Unwrap(cbInfo.This().As<Object>());
  160. (instance->*UnwrapCallback)(cbInfo);
  161. return nullptr;
  162. });
  163. }
  164. template <typename T, typename Finalizer, typename Hint = void>
  165. struct FinalizeData {
  166. static inline void Wrapper(napi_env env,
  167. void* data,
  168. void* finalizeHint) NAPI_NOEXCEPT {
  169. WrapVoidCallback([&] {
  170. FinalizeData* finalizeData = static_cast<FinalizeData*>(finalizeHint);
  171. finalizeData->callback(Env(env), static_cast<T*>(data));
  172. delete finalizeData;
  173. });
  174. }
  175. static inline void WrapperWithHint(napi_env env,
  176. void* data,
  177. void* finalizeHint) NAPI_NOEXCEPT {
  178. WrapVoidCallback([&] {
  179. FinalizeData* finalizeData = static_cast<FinalizeData*>(finalizeHint);
  180. finalizeData->callback(
  181. Env(env), static_cast<T*>(data), finalizeData->hint);
  182. delete finalizeData;
  183. });
  184. }
  185. Finalizer callback;
  186. Hint* hint;
  187. };
  188. #if (NAPI_VERSION > 3 && NAPI_HAS_THREADS)
  189. template <typename ContextType = void,
  190. typename Finalizer = std::function<void(Env, void*, ContextType*)>,
  191. typename FinalizerDataType = void>
  192. struct ThreadSafeFinalize {
  193. static inline void Wrapper(napi_env env,
  194. void* rawFinalizeData,
  195. void* /* rawContext */) {
  196. if (rawFinalizeData == nullptr) return;
  197. ThreadSafeFinalize* finalizeData =
  198. static_cast<ThreadSafeFinalize*>(rawFinalizeData);
  199. finalizeData->callback(Env(env));
  200. delete finalizeData;
  201. }
  202. static inline void FinalizeWrapperWithData(napi_env env,
  203. void* rawFinalizeData,
  204. void* /* rawContext */) {
  205. if (rawFinalizeData == nullptr) return;
  206. ThreadSafeFinalize* finalizeData =
  207. static_cast<ThreadSafeFinalize*>(rawFinalizeData);
  208. finalizeData->callback(Env(env), finalizeData->data);
  209. delete finalizeData;
  210. }
  211. static inline void FinalizeWrapperWithContext(napi_env env,
  212. void* rawFinalizeData,
  213. void* rawContext) {
  214. if (rawFinalizeData == nullptr) return;
  215. ThreadSafeFinalize* finalizeData =
  216. static_cast<ThreadSafeFinalize*>(rawFinalizeData);
  217. finalizeData->callback(Env(env), static_cast<ContextType*>(rawContext));
  218. delete finalizeData;
  219. }
  220. static inline void FinalizeFinalizeWrapperWithDataAndContext(
  221. napi_env env, void* rawFinalizeData, void* rawContext) {
  222. if (rawFinalizeData == nullptr) return;
  223. ThreadSafeFinalize* finalizeData =
  224. static_cast<ThreadSafeFinalize*>(rawFinalizeData);
  225. finalizeData->callback(
  226. Env(env), finalizeData->data, static_cast<ContextType*>(rawContext));
  227. delete finalizeData;
  228. }
  229. FinalizerDataType* data;
  230. Finalizer callback;
  231. };
  232. template <typename ContextType, typename DataType, typename CallJs, CallJs call>
  233. inline typename std::enable_if<call != static_cast<CallJs>(nullptr)>::type
  234. CallJsWrapper(napi_env env, napi_value jsCallback, void* context, void* data) {
  235. call(env,
  236. Function(env, jsCallback),
  237. static_cast<ContextType*>(context),
  238. static_cast<DataType*>(data));
  239. }
  240. template <typename ContextType, typename DataType, typename CallJs, CallJs call>
  241. inline typename std::enable_if<call == static_cast<CallJs>(nullptr)>::type
  242. CallJsWrapper(napi_env env,
  243. napi_value jsCallback,
  244. void* /*context*/,
  245. void* /*data*/) {
  246. if (jsCallback != nullptr) {
  247. Function(env, jsCallback).Call(0, nullptr);
  248. }
  249. }
  250. #if NAPI_VERSION > 4
  251. template <typename CallbackType, typename TSFN>
  252. napi_value DefaultCallbackWrapper(napi_env /*env*/, std::nullptr_t /*cb*/) {
  253. return nullptr;
  254. }
  255. template <typename CallbackType, typename TSFN>
  256. napi_value DefaultCallbackWrapper(napi_env /*env*/, Napi::Function cb) {
  257. return cb;
  258. }
  259. #else
  260. template <typename CallbackType, typename TSFN>
  261. napi_value DefaultCallbackWrapper(napi_env env, Napi::Function cb) {
  262. if (cb.IsEmpty()) {
  263. return TSFN::EmptyFunctionFactory(env);
  264. }
  265. return cb;
  266. }
  267. #endif // NAPI_VERSION > 4
  268. #endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS
  269. template <typename Getter, typename Setter>
  270. struct AccessorCallbackData {
  271. static inline napi_value GetterWrapper(napi_env env,
  272. napi_callback_info info) {
  273. return details::WrapCallback([&] {
  274. CallbackInfo callbackInfo(env, info);
  275. AccessorCallbackData* callbackData =
  276. static_cast<AccessorCallbackData*>(callbackInfo.Data());
  277. callbackInfo.SetData(callbackData->data);
  278. return callbackData->getterCallback(callbackInfo);
  279. });
  280. }
  281. static inline napi_value SetterWrapper(napi_env env,
  282. napi_callback_info info) {
  283. return details::WrapCallback([&] {
  284. CallbackInfo callbackInfo(env, info);
  285. AccessorCallbackData* callbackData =
  286. static_cast<AccessorCallbackData*>(callbackInfo.Data());
  287. callbackInfo.SetData(callbackData->data);
  288. callbackData->setterCallback(callbackInfo);
  289. return nullptr;
  290. });
  291. }
  292. Getter getterCallback;
  293. Setter setterCallback;
  294. void* data;
  295. };
  296. } // namespace details
  297. #ifndef NODE_ADDON_API_DISABLE_DEPRECATED
  298. #include "napi-inl.deprecated.h"
  299. #endif // !NODE_ADDON_API_DISABLE_DEPRECATED
  300. ////////////////////////////////////////////////////////////////////////////////
  301. // Module registration
  302. ////////////////////////////////////////////////////////////////////////////////
  303. // Register an add-on based on an initializer function.
  304. #define NODE_API_MODULE(modname, regfunc) \
  305. static napi_value __napi_##regfunc(napi_env env, napi_value exports) { \
  306. return Napi::RegisterModule(env, exports, regfunc); \
  307. } \
  308. NAPI_MODULE(modname, __napi_##regfunc)
  309. // Register an add-on based on a subclass of `Addon<T>` with a custom Node.js
  310. // module name.
  311. #define NODE_API_NAMED_ADDON(modname, classname) \
  312. static napi_value __napi_##classname(napi_env env, napi_value exports) { \
  313. return Napi::RegisterModule(env, exports, &classname::Init); \
  314. } \
  315. NAPI_MODULE(modname, __napi_##classname)
  316. // Register an add-on based on a subclass of `Addon<T>` with the Node.js module
  317. // name given by node-gyp from the `target_name` in binding.gyp.
  318. #define NODE_API_ADDON(classname) \
  319. NODE_API_NAMED_ADDON(NODE_GYP_MODULE_NAME, classname)
  320. // Adapt the NAPI_MODULE registration function:
  321. // - Wrap the arguments in NAPI wrappers.
  322. // - Catch any NAPI errors and rethrow as JS exceptions.
  323. inline napi_value RegisterModule(napi_env env,
  324. napi_value exports,
  325. ModuleRegisterCallback registerCallback) {
  326. return details::WrapCallback([&] {
  327. return napi_value(
  328. registerCallback(Napi::Env(env), Napi::Object(env, exports)));
  329. });
  330. }
  331. ////////////////////////////////////////////////////////////////////////////////
  332. // Maybe class
  333. ////////////////////////////////////////////////////////////////////////////////
  334. template <class T>
  335. bool Maybe<T>::IsNothing() const {
  336. return !_has_value;
  337. }
  338. template <class T>
  339. bool Maybe<T>::IsJust() const {
  340. return _has_value;
  341. }
  342. template <class T>
  343. void Maybe<T>::Check() const {
  344. NAPI_CHECK(IsJust(), "Napi::Maybe::Check", "Maybe value is Nothing.");
  345. }
  346. template <class T>
  347. T Maybe<T>::Unwrap() const {
  348. NAPI_CHECK(IsJust(), "Napi::Maybe::Unwrap", "Maybe value is Nothing.");
  349. return _value;
  350. }
  351. template <class T>
  352. T Maybe<T>::UnwrapOr(const T& default_value) const {
  353. return _has_value ? _value : default_value;
  354. }
  355. template <class T>
  356. bool Maybe<T>::UnwrapTo(T* out) const {
  357. if (IsJust()) {
  358. *out = _value;
  359. return true;
  360. };
  361. return false;
  362. }
  363. template <class T>
  364. bool Maybe<T>::operator==(const Maybe& other) const {
  365. return (IsJust() == other.IsJust()) &&
  366. (!IsJust() || Unwrap() == other.Unwrap());
  367. }
  368. template <class T>
  369. bool Maybe<T>::operator!=(const Maybe& other) const {
  370. return !operator==(other);
  371. }
  372. template <class T>
  373. Maybe<T>::Maybe() : _has_value(false) {}
  374. template <class T>
  375. Maybe<T>::Maybe(const T& t) : _has_value(true), _value(t) {}
  376. template <class T>
  377. inline Maybe<T> Nothing() {
  378. return Maybe<T>();
  379. }
  380. template <class T>
  381. inline Maybe<T> Just(const T& t) {
  382. return Maybe<T>(t);
  383. }
  384. ////////////////////////////////////////////////////////////////////////////////
  385. // Env class
  386. ////////////////////////////////////////////////////////////////////////////////
  387. inline Env::Env(napi_env env) : _env(env) {}
  388. inline Env::operator napi_env() const {
  389. return _env;
  390. }
  391. inline Object Env::Global() const {
  392. napi_value value;
  393. napi_status status = napi_get_global(*this, &value);
  394. NAPI_THROW_IF_FAILED(*this, status, Object());
  395. return Object(*this, value);
  396. }
  397. inline Value Env::Undefined() const {
  398. napi_value value;
  399. napi_status status = napi_get_undefined(*this, &value);
  400. NAPI_THROW_IF_FAILED(*this, status, Value());
  401. return Value(*this, value);
  402. }
  403. inline Value Env::Null() const {
  404. napi_value value;
  405. napi_status status = napi_get_null(*this, &value);
  406. NAPI_THROW_IF_FAILED(*this, status, Value());
  407. return Value(*this, value);
  408. }
  409. inline bool Env::IsExceptionPending() const {
  410. bool result;
  411. napi_status status = napi_is_exception_pending(_env, &result);
  412. if (status != napi_ok)
  413. result = false; // Checking for a pending exception shouldn't throw.
  414. return result;
  415. }
  416. inline Error Env::GetAndClearPendingException() const {
  417. napi_value value;
  418. napi_status status = napi_get_and_clear_last_exception(_env, &value);
  419. if (status != napi_ok) {
  420. // Don't throw another exception when failing to get the exception!
  421. return Error();
  422. }
  423. return Error(_env, value);
  424. }
  425. inline MaybeOrValue<Value> Env::RunScript(const char* utf8script) const {
  426. String script = String::New(_env, utf8script);
  427. return RunScript(script);
  428. }
  429. inline MaybeOrValue<Value> Env::RunScript(const std::string& utf8script) const {
  430. return RunScript(utf8script.c_str());
  431. }
  432. inline MaybeOrValue<Value> Env::RunScript(String script) const {
  433. napi_value result;
  434. napi_status status = napi_run_script(_env, script, &result);
  435. NAPI_RETURN_OR_THROW_IF_FAILED(
  436. _env, status, Napi::Value(_env, result), Napi::Value);
  437. }
  438. #if NAPI_VERSION > 2
  439. template <typename Hook, typename Arg>
  440. void Env::CleanupHook<Hook, Arg>::Wrapper(void* data) NAPI_NOEXCEPT {
  441. auto* cleanupData =
  442. static_cast<typename Napi::Env::CleanupHook<Hook, Arg>::CleanupData*>(
  443. data);
  444. cleanupData->hook();
  445. delete cleanupData;
  446. }
  447. template <typename Hook, typename Arg>
  448. void Env::CleanupHook<Hook, Arg>::WrapperWithArg(void* data) NAPI_NOEXCEPT {
  449. auto* cleanupData =
  450. static_cast<typename Napi::Env::CleanupHook<Hook, Arg>::CleanupData*>(
  451. data);
  452. cleanupData->hook(static_cast<Arg*>(cleanupData->arg));
  453. delete cleanupData;
  454. }
  455. #endif // NAPI_VERSION > 2
  456. #if NAPI_VERSION > 5
  457. template <typename T, Env::Finalizer<T> fini>
  458. inline void Env::SetInstanceData(T* data) const {
  459. napi_status status = napi_set_instance_data(
  460. _env,
  461. data,
  462. [](napi_env env, void* data, void*) { fini(env, static_cast<T*>(data)); },
  463. nullptr);
  464. NAPI_THROW_IF_FAILED_VOID(_env, status);
  465. }
  466. template <typename DataType,
  467. typename HintType,
  468. Napi::Env::FinalizerWithHint<DataType, HintType> fini>
  469. inline void Env::SetInstanceData(DataType* data, HintType* hint) const {
  470. napi_status status = napi_set_instance_data(
  471. _env,
  472. data,
  473. [](napi_env env, void* data, void* hint) {
  474. fini(env, static_cast<DataType*>(data), static_cast<HintType*>(hint));
  475. },
  476. hint);
  477. NAPI_THROW_IF_FAILED_VOID(_env, status);
  478. }
  479. template <typename T>
  480. inline T* Env::GetInstanceData() const {
  481. void* data = nullptr;
  482. napi_status status = napi_get_instance_data(_env, &data);
  483. NAPI_THROW_IF_FAILED(_env, status, nullptr);
  484. return static_cast<T*>(data);
  485. }
  486. template <typename T>
  487. void Env::DefaultFini(Env, T* data) {
  488. delete data;
  489. }
  490. template <typename DataType, typename HintType>
  491. void Env::DefaultFiniWithHint(Env, DataType* data, HintType*) {
  492. delete data;
  493. }
  494. #endif // NAPI_VERSION > 5
  495. ////////////////////////////////////////////////////////////////////////////////
  496. // Value class
  497. ////////////////////////////////////////////////////////////////////////////////
  498. inline Value::Value() : _env(nullptr), _value(nullptr) {}
  499. inline Value::Value(napi_env env, napi_value value)
  500. : _env(env), _value(value) {}
  501. inline Value::operator napi_value() const {
  502. return _value;
  503. }
  504. inline bool Value::operator==(const Value& other) const {
  505. return StrictEquals(other);
  506. }
  507. inline bool Value::operator!=(const Value& other) const {
  508. return !this->operator==(other);
  509. }
  510. inline bool Value::StrictEquals(const Value& other) const {
  511. bool result;
  512. napi_status status = napi_strict_equals(_env, *this, other, &result);
  513. NAPI_THROW_IF_FAILED(_env, status, false);
  514. return result;
  515. }
  516. inline Napi::Env Value::Env() const {
  517. return Napi::Env(_env);
  518. }
  519. inline bool Value::IsEmpty() const {
  520. return _value == nullptr;
  521. }
  522. inline napi_valuetype Value::Type() const {
  523. if (IsEmpty()) {
  524. return napi_undefined;
  525. }
  526. napi_valuetype type;
  527. napi_status status = napi_typeof(_env, _value, &type);
  528. NAPI_THROW_IF_FAILED(_env, status, napi_undefined);
  529. return type;
  530. }
  531. inline bool Value::IsUndefined() const {
  532. return Type() == napi_undefined;
  533. }
  534. inline bool Value::IsNull() const {
  535. return Type() == napi_null;
  536. }
  537. inline bool Value::IsBoolean() const {
  538. return Type() == napi_boolean;
  539. }
  540. inline bool Value::IsNumber() const {
  541. return Type() == napi_number;
  542. }
  543. #if NAPI_VERSION > 5
  544. inline bool Value::IsBigInt() const {
  545. return Type() == napi_bigint;
  546. }
  547. #endif // NAPI_VERSION > 5
  548. #if (NAPI_VERSION > 4)
  549. inline bool Value::IsDate() const {
  550. if (IsEmpty()) {
  551. return false;
  552. }
  553. bool result;
  554. napi_status status = napi_is_date(_env, _value, &result);
  555. NAPI_THROW_IF_FAILED(_env, status, false);
  556. return result;
  557. }
  558. #endif
  559. inline bool Value::IsString() const {
  560. return Type() == napi_string;
  561. }
  562. inline bool Value::IsSymbol() const {
  563. return Type() == napi_symbol;
  564. }
  565. inline bool Value::IsArray() const {
  566. if (IsEmpty()) {
  567. return false;
  568. }
  569. bool result;
  570. napi_status status = napi_is_array(_env, _value, &result);
  571. NAPI_THROW_IF_FAILED(_env, status, false);
  572. return result;
  573. }
  574. inline bool Value::IsArrayBuffer() const {
  575. if (IsEmpty()) {
  576. return false;
  577. }
  578. bool result;
  579. napi_status status = napi_is_arraybuffer(_env, _value, &result);
  580. NAPI_THROW_IF_FAILED(_env, status, false);
  581. return result;
  582. }
  583. inline bool Value::IsTypedArray() const {
  584. if (IsEmpty()) {
  585. return false;
  586. }
  587. bool result;
  588. napi_status status = napi_is_typedarray(_env, _value, &result);
  589. NAPI_THROW_IF_FAILED(_env, status, false);
  590. return result;
  591. }
  592. inline bool Value::IsObject() const {
  593. return Type() == napi_object || IsFunction();
  594. }
  595. inline bool Value::IsFunction() const {
  596. return Type() == napi_function;
  597. }
  598. inline bool Value::IsPromise() const {
  599. if (IsEmpty()) {
  600. return false;
  601. }
  602. bool result;
  603. napi_status status = napi_is_promise(_env, _value, &result);
  604. NAPI_THROW_IF_FAILED(_env, status, false);
  605. return result;
  606. }
  607. inline bool Value::IsDataView() const {
  608. if (IsEmpty()) {
  609. return false;
  610. }
  611. bool result;
  612. napi_status status = napi_is_dataview(_env, _value, &result);
  613. NAPI_THROW_IF_FAILED(_env, status, false);
  614. return result;
  615. }
  616. inline bool Value::IsBuffer() const {
  617. if (IsEmpty()) {
  618. return false;
  619. }
  620. bool result;
  621. napi_status status = napi_is_buffer(_env, _value, &result);
  622. NAPI_THROW_IF_FAILED(_env, status, false);
  623. return result;
  624. }
  625. inline bool Value::IsExternal() const {
  626. return Type() == napi_external;
  627. }
  628. template <typename T>
  629. inline T Value::As() const {
  630. #ifdef NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS
  631. T::CheckCast(_env, _value);
  632. #endif
  633. return T(_env, _value);
  634. }
  635. inline MaybeOrValue<Boolean> Value::ToBoolean() const {
  636. napi_value result;
  637. napi_status status = napi_coerce_to_bool(_env, _value, &result);
  638. NAPI_RETURN_OR_THROW_IF_FAILED(
  639. _env, status, Napi::Boolean(_env, result), Napi::Boolean);
  640. }
  641. inline MaybeOrValue<Number> Value::ToNumber() const {
  642. napi_value result;
  643. napi_status status = napi_coerce_to_number(_env, _value, &result);
  644. NAPI_RETURN_OR_THROW_IF_FAILED(
  645. _env, status, Napi::Number(_env, result), Napi::Number);
  646. }
  647. inline MaybeOrValue<String> Value::ToString() const {
  648. napi_value result;
  649. napi_status status = napi_coerce_to_string(_env, _value, &result);
  650. NAPI_RETURN_OR_THROW_IF_FAILED(
  651. _env, status, Napi::String(_env, result), Napi::String);
  652. }
  653. inline MaybeOrValue<Object> Value::ToObject() const {
  654. napi_value result;
  655. napi_status status = napi_coerce_to_object(_env, _value, &result);
  656. NAPI_RETURN_OR_THROW_IF_FAILED(
  657. _env, status, Napi::Object(_env, result), Napi::Object);
  658. }
  659. ////////////////////////////////////////////////////////////////////////////////
  660. // Boolean class
  661. ////////////////////////////////////////////////////////////////////////////////
  662. inline Boolean Boolean::New(napi_env env, bool val) {
  663. napi_value value;
  664. napi_status status = napi_get_boolean(env, val, &value);
  665. NAPI_THROW_IF_FAILED(env, status, Boolean());
  666. return Boolean(env, value);
  667. }
  668. inline void Boolean::CheckCast(napi_env env, napi_value value) {
  669. NAPI_CHECK(value != nullptr, "Boolean::CheckCast", "empty value");
  670. napi_valuetype type;
  671. napi_status status = napi_typeof(env, value, &type);
  672. NAPI_CHECK(status == napi_ok, "Boolean::CheckCast", "napi_typeof failed");
  673. NAPI_CHECK(
  674. type == napi_boolean, "Boolean::CheckCast", "value is not napi_boolean");
  675. }
  676. inline Boolean::Boolean() : Napi::Value() {}
  677. inline Boolean::Boolean(napi_env env, napi_value value)
  678. : Napi::Value(env, value) {}
  679. inline Boolean::operator bool() const {
  680. return Value();
  681. }
  682. inline bool Boolean::Value() const {
  683. bool result;
  684. napi_status status = napi_get_value_bool(_env, _value, &result);
  685. NAPI_THROW_IF_FAILED(_env, status, false);
  686. return result;
  687. }
  688. ////////////////////////////////////////////////////////////////////////////////
  689. // Number class
  690. ////////////////////////////////////////////////////////////////////////////////
  691. inline Number Number::New(napi_env env, double val) {
  692. napi_value value;
  693. napi_status status = napi_create_double(env, val, &value);
  694. NAPI_THROW_IF_FAILED(env, status, Number());
  695. return Number(env, value);
  696. }
  697. inline void Number::CheckCast(napi_env env, napi_value value) {
  698. NAPI_CHECK(value != nullptr, "Number::CheckCast", "empty value");
  699. napi_valuetype type;
  700. napi_status status = napi_typeof(env, value, &type);
  701. NAPI_CHECK(status == napi_ok, "Number::CheckCast", "napi_typeof failed");
  702. NAPI_CHECK(
  703. type == napi_number, "Number::CheckCast", "value is not napi_number");
  704. }
  705. inline Number::Number() : Value() {}
  706. inline Number::Number(napi_env env, napi_value value) : Value(env, value) {}
  707. inline Number::operator int32_t() const {
  708. return Int32Value();
  709. }
  710. inline Number::operator uint32_t() const {
  711. return Uint32Value();
  712. }
  713. inline Number::operator int64_t() const {
  714. return Int64Value();
  715. }
  716. inline Number::operator float() const {
  717. return FloatValue();
  718. }
  719. inline Number::operator double() const {
  720. return DoubleValue();
  721. }
  722. inline int32_t Number::Int32Value() const {
  723. int32_t result;
  724. napi_status status = napi_get_value_int32(_env, _value, &result);
  725. NAPI_THROW_IF_FAILED(_env, status, 0);
  726. return result;
  727. }
  728. inline uint32_t Number::Uint32Value() const {
  729. uint32_t result;
  730. napi_status status = napi_get_value_uint32(_env, _value, &result);
  731. NAPI_THROW_IF_FAILED(_env, status, 0);
  732. return result;
  733. }
  734. inline int64_t Number::Int64Value() const {
  735. int64_t result;
  736. napi_status status = napi_get_value_int64(_env, _value, &result);
  737. NAPI_THROW_IF_FAILED(_env, status, 0);
  738. return result;
  739. }
  740. inline float Number::FloatValue() const {
  741. return static_cast<float>(DoubleValue());
  742. }
  743. inline double Number::DoubleValue() const {
  744. double result;
  745. napi_status status = napi_get_value_double(_env, _value, &result);
  746. NAPI_THROW_IF_FAILED(_env, status, 0);
  747. return result;
  748. }
  749. #if NAPI_VERSION > 5
  750. ////////////////////////////////////////////////////////////////////////////////
  751. // BigInt Class
  752. ////////////////////////////////////////////////////////////////////////////////
  753. inline BigInt BigInt::New(napi_env env, int64_t val) {
  754. napi_value value;
  755. napi_status status = napi_create_bigint_int64(env, val, &value);
  756. NAPI_THROW_IF_FAILED(env, status, BigInt());
  757. return BigInt(env, value);
  758. }
  759. inline BigInt BigInt::New(napi_env env, uint64_t val) {
  760. napi_value value;
  761. napi_status status = napi_create_bigint_uint64(env, val, &value);
  762. NAPI_THROW_IF_FAILED(env, status, BigInt());
  763. return BigInt(env, value);
  764. }
  765. inline BigInt BigInt::New(napi_env env,
  766. int sign_bit,
  767. size_t word_count,
  768. const uint64_t* words) {
  769. napi_value value;
  770. napi_status status =
  771. napi_create_bigint_words(env, sign_bit, word_count, words, &value);
  772. NAPI_THROW_IF_FAILED(env, status, BigInt());
  773. return BigInt(env, value);
  774. }
  775. inline void BigInt::CheckCast(napi_env env, napi_value value) {
  776. NAPI_CHECK(value != nullptr, "BigInt::CheckCast", "empty value");
  777. napi_valuetype type;
  778. napi_status status = napi_typeof(env, value, &type);
  779. NAPI_CHECK(status == napi_ok, "BigInt::CheckCast", "napi_typeof failed");
  780. NAPI_CHECK(
  781. type == napi_bigint, "BigInt::CheckCast", "value is not napi_bigint");
  782. }
  783. inline BigInt::BigInt() : Value() {}
  784. inline BigInt::BigInt(napi_env env, napi_value value) : Value(env, value) {}
  785. inline int64_t BigInt::Int64Value(bool* lossless) const {
  786. int64_t result;
  787. napi_status status =
  788. napi_get_value_bigint_int64(_env, _value, &result, lossless);
  789. NAPI_THROW_IF_FAILED(_env, status, 0);
  790. return result;
  791. }
  792. inline uint64_t BigInt::Uint64Value(bool* lossless) const {
  793. uint64_t result;
  794. napi_status status =
  795. napi_get_value_bigint_uint64(_env, _value, &result, lossless);
  796. NAPI_THROW_IF_FAILED(_env, status, 0);
  797. return result;
  798. }
  799. inline size_t BigInt::WordCount() const {
  800. size_t word_count;
  801. napi_status status =
  802. napi_get_value_bigint_words(_env, _value, nullptr, &word_count, nullptr);
  803. NAPI_THROW_IF_FAILED(_env, status, 0);
  804. return word_count;
  805. }
  806. inline void BigInt::ToWords(int* sign_bit,
  807. size_t* word_count,
  808. uint64_t* words) {
  809. napi_status status =
  810. napi_get_value_bigint_words(_env, _value, sign_bit, word_count, words);
  811. NAPI_THROW_IF_FAILED_VOID(_env, status);
  812. }
  813. #endif // NAPI_VERSION > 5
  814. #if (NAPI_VERSION > 4)
  815. ////////////////////////////////////////////////////////////////////////////////
  816. // Date Class
  817. ////////////////////////////////////////////////////////////////////////////////
  818. inline Date Date::New(napi_env env, double val) {
  819. napi_value value;
  820. napi_status status = napi_create_date(env, val, &value);
  821. NAPI_THROW_IF_FAILED(env, status, Date());
  822. return Date(env, value);
  823. }
  824. inline void Date::CheckCast(napi_env env, napi_value value) {
  825. NAPI_CHECK(value != nullptr, "Date::CheckCast", "empty value");
  826. bool result;
  827. napi_status status = napi_is_date(env, value, &result);
  828. NAPI_CHECK(status == napi_ok, "Date::CheckCast", "napi_is_date failed");
  829. NAPI_CHECK(result, "Date::CheckCast", "value is not date");
  830. }
  831. inline Date::Date() : Value() {}
  832. inline Date::Date(napi_env env, napi_value value) : Value(env, value) {}
  833. inline Date::operator double() const {
  834. return ValueOf();
  835. }
  836. inline double Date::ValueOf() const {
  837. double result;
  838. napi_status status = napi_get_date_value(_env, _value, &result);
  839. NAPI_THROW_IF_FAILED(_env, status, 0);
  840. return result;
  841. }
  842. #endif
  843. ////////////////////////////////////////////////////////////////////////////////
  844. // Name class
  845. ////////////////////////////////////////////////////////////////////////////////
  846. inline void Name::CheckCast(napi_env env, napi_value value) {
  847. NAPI_CHECK(value != nullptr, "Name::CheckCast", "empty value");
  848. napi_valuetype type;
  849. napi_status status = napi_typeof(env, value, &type);
  850. NAPI_CHECK(status == napi_ok, "Name::CheckCast", "napi_typeof failed");
  851. NAPI_CHECK(type == napi_string || type == napi_symbol,
  852. "Name::CheckCast",
  853. "value is not napi_string or napi_symbol");
  854. }
  855. inline Name::Name() : Value() {}
  856. inline Name::Name(napi_env env, napi_value value) : Value(env, value) {}
  857. ////////////////////////////////////////////////////////////////////////////////
  858. // String class
  859. ////////////////////////////////////////////////////////////////////////////////
  860. inline String String::New(napi_env env, const std::string& val) {
  861. return String::New(env, val.c_str(), val.size());
  862. }
  863. inline String String::New(napi_env env, const std::u16string& val) {
  864. return String::New(env, val.c_str(), val.size());
  865. }
  866. inline String String::New(napi_env env, const char* val) {
  867. // TODO(@gabrielschulhof) Remove if-statement when core's error handling is
  868. // available in all supported versions.
  869. if (val == nullptr) {
  870. // Throw an error that looks like it came from core.
  871. NAPI_THROW_IF_FAILED(env, napi_invalid_arg, String());
  872. }
  873. napi_value value;
  874. napi_status status =
  875. napi_create_string_utf8(env, val, std::strlen(val), &value);
  876. NAPI_THROW_IF_FAILED(env, status, String());
  877. return String(env, value);
  878. }
  879. inline String String::New(napi_env env, const char16_t* val) {
  880. napi_value value;
  881. // TODO(@gabrielschulhof) Remove if-statement when core's error handling is
  882. // available in all supported versions.
  883. if (val == nullptr) {
  884. // Throw an error that looks like it came from core.
  885. NAPI_THROW_IF_FAILED(env, napi_invalid_arg, String());
  886. }
  887. napi_status status =
  888. napi_create_string_utf16(env, val, std::u16string(val).size(), &value);
  889. NAPI_THROW_IF_FAILED(env, status, String());
  890. return String(env, value);
  891. }
  892. inline String String::New(napi_env env, const char* val, size_t length) {
  893. napi_value value;
  894. napi_status status = napi_create_string_utf8(env, val, length, &value);
  895. NAPI_THROW_IF_FAILED(env, status, String());
  896. return String(env, value);
  897. }
  898. inline String String::New(napi_env env, const char16_t* val, size_t length) {
  899. napi_value value;
  900. napi_status status = napi_create_string_utf16(env, val, length, &value);
  901. NAPI_THROW_IF_FAILED(env, status, String());
  902. return String(env, value);
  903. }
  904. inline void String::CheckCast(napi_env env, napi_value value) {
  905. NAPI_CHECK(value != nullptr, "String::CheckCast", "empty value");
  906. napi_valuetype type;
  907. napi_status status = napi_typeof(env, value, &type);
  908. NAPI_CHECK(status == napi_ok, "String::CheckCast", "napi_typeof failed");
  909. NAPI_CHECK(
  910. type == napi_string, "String::CheckCast", "value is not napi_string");
  911. }
  912. inline String::String() : Name() {}
  913. inline String::String(napi_env env, napi_value value) : Name(env, value) {}
  914. inline String::operator std::string() const {
  915. return Utf8Value();
  916. }
  917. inline String::operator std::u16string() const {
  918. return Utf16Value();
  919. }
  920. inline std::string String::Utf8Value() const {
  921. size_t length;
  922. napi_status status =
  923. napi_get_value_string_utf8(_env, _value, nullptr, 0, &length);
  924. NAPI_THROW_IF_FAILED(_env, status, "");
  925. std::string value;
  926. value.reserve(length + 1);
  927. value.resize(length);
  928. status = napi_get_value_string_utf8(
  929. _env, _value, &value[0], value.capacity(), nullptr);
  930. NAPI_THROW_IF_FAILED(_env, status, "");
  931. return value;
  932. }
  933. inline std::u16string String::Utf16Value() const {
  934. size_t length;
  935. napi_status status =
  936. napi_get_value_string_utf16(_env, _value, nullptr, 0, &length);
  937. NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT(""));
  938. std::u16string value;
  939. value.reserve(length + 1);
  940. value.resize(length);
  941. status = napi_get_value_string_utf16(
  942. _env, _value, &value[0], value.capacity(), nullptr);
  943. NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT(""));
  944. return value;
  945. }
  946. ////////////////////////////////////////////////////////////////////////////////
  947. // Symbol class
  948. ////////////////////////////////////////////////////////////////////////////////
  949. inline Symbol Symbol::New(napi_env env, const char* description) {
  950. napi_value descriptionValue = description != nullptr
  951. ? String::New(env, description)
  952. : static_cast<napi_value>(nullptr);
  953. return Symbol::New(env, descriptionValue);
  954. }
  955. inline Symbol Symbol::New(napi_env env, const std::string& description) {
  956. napi_value descriptionValue = String::New(env, description);
  957. return Symbol::New(env, descriptionValue);
  958. }
  959. inline Symbol Symbol::New(napi_env env, String description) {
  960. napi_value descriptionValue = description;
  961. return Symbol::New(env, descriptionValue);
  962. }
  963. inline Symbol Symbol::New(napi_env env, napi_value description) {
  964. napi_value value;
  965. napi_status status = napi_create_symbol(env, description, &value);
  966. NAPI_THROW_IF_FAILED(env, status, Symbol());
  967. return Symbol(env, value);
  968. }
  969. inline MaybeOrValue<Symbol> Symbol::WellKnown(napi_env env,
  970. const std::string& name) {
  971. #if defined(NODE_ADDON_API_ENABLE_MAYBE)
  972. Value symbol_obj;
  973. Value symbol_value;
  974. if (Napi::Env(env).Global().Get("Symbol").UnwrapTo(&symbol_obj) &&
  975. symbol_obj.As<Object>().Get(name).UnwrapTo(&symbol_value)) {
  976. return Just<Symbol>(symbol_value.As<Symbol>());
  977. }
  978. return Nothing<Symbol>();
  979. #else
  980. return Napi::Env(env)
  981. .Global()
  982. .Get("Symbol")
  983. .As<Object>()
  984. .Get(name)
  985. .As<Symbol>();
  986. #endif
  987. }
  988. inline MaybeOrValue<Symbol> Symbol::For(napi_env env,
  989. const std::string& description) {
  990. napi_value descriptionValue = String::New(env, description);
  991. return Symbol::For(env, descriptionValue);
  992. }
  993. inline MaybeOrValue<Symbol> Symbol::For(napi_env env, const char* description) {
  994. napi_value descriptionValue = String::New(env, description);
  995. return Symbol::For(env, descriptionValue);
  996. }
  997. inline MaybeOrValue<Symbol> Symbol::For(napi_env env, String description) {
  998. return Symbol::For(env, static_cast<napi_value>(description));
  999. }
  1000. inline MaybeOrValue<Symbol> Symbol::For(napi_env env, napi_value description) {
  1001. #if defined(NODE_ADDON_API_ENABLE_MAYBE)
  1002. Value symbol_obj;
  1003. Value symbol_for_value;
  1004. Value symbol_value;
  1005. if (Napi::Env(env).Global().Get("Symbol").UnwrapTo(&symbol_obj) &&
  1006. symbol_obj.As<Object>().Get("for").UnwrapTo(&symbol_for_value) &&
  1007. symbol_for_value.As<Function>()
  1008. .Call(symbol_obj, {description})
  1009. .UnwrapTo(&symbol_value)) {
  1010. return Just<Symbol>(symbol_value.As<Symbol>());
  1011. }
  1012. return Nothing<Symbol>();
  1013. #else
  1014. Object symbol_obj = Napi::Env(env).Global().Get("Symbol").As<Object>();
  1015. return symbol_obj.Get("for")
  1016. .As<Function>()
  1017. .Call(symbol_obj, {description})
  1018. .As<Symbol>();
  1019. #endif
  1020. }
  1021. inline void Symbol::CheckCast(napi_env env, napi_value value) {
  1022. NAPI_CHECK(value != nullptr, "Symbol::CheckCast", "empty value");
  1023. napi_valuetype type;
  1024. napi_status status = napi_typeof(env, value, &type);
  1025. NAPI_CHECK(status == napi_ok, "Symbol::CheckCast", "napi_typeof failed");
  1026. NAPI_CHECK(
  1027. type == napi_symbol, "Symbol::CheckCast", "value is not napi_symbol");
  1028. }
  1029. inline Symbol::Symbol() : Name() {}
  1030. inline Symbol::Symbol(napi_env env, napi_value value) : Name(env, value) {}
  1031. ////////////////////////////////////////////////////////////////////////////////
  1032. // Automagic value creation
  1033. ////////////////////////////////////////////////////////////////////////////////
  1034. namespace details {
  1035. template <typename T>
  1036. struct vf_number {
  1037. static Number From(napi_env env, T value) {
  1038. return Number::New(env, static_cast<double>(value));
  1039. }
  1040. };
  1041. template <>
  1042. struct vf_number<bool> {
  1043. static Boolean From(napi_env env, bool value) {
  1044. return Boolean::New(env, value);
  1045. }
  1046. };
  1047. struct vf_utf8_charp {
  1048. static String From(napi_env env, const char* value) {
  1049. return String::New(env, value);
  1050. }
  1051. };
  1052. struct vf_utf16_charp {
  1053. static String From(napi_env env, const char16_t* value) {
  1054. return String::New(env, value);
  1055. }
  1056. };
  1057. struct vf_utf8_string {
  1058. static String From(napi_env env, const std::string& value) {
  1059. return String::New(env, value);
  1060. }
  1061. };
  1062. struct vf_utf16_string {
  1063. static String From(napi_env env, const std::u16string& value) {
  1064. return String::New(env, value);
  1065. }
  1066. };
  1067. template <typename T>
  1068. struct vf_fallback {
  1069. static Value From(napi_env env, const T& value) { return Value(env, value); }
  1070. };
  1071. template <typename...>
  1072. struct disjunction : std::false_type {};
  1073. template <typename B>
  1074. struct disjunction<B> : B {};
  1075. template <typename B, typename... Bs>
  1076. struct disjunction<B, Bs...>
  1077. : std::conditional<bool(B::value), B, disjunction<Bs...>>::type {};
  1078. template <typename T>
  1079. struct can_make_string
  1080. : disjunction<typename std::is_convertible<T, const char*>::type,
  1081. typename std::is_convertible<T, const char16_t*>::type,
  1082. typename std::is_convertible<T, std::string>::type,
  1083. typename std::is_convertible<T, std::u16string>::type> {};
  1084. } // namespace details
  1085. template <typename T>
  1086. Value Value::From(napi_env env, const T& value) {
  1087. using Helper = typename std::conditional<
  1088. std::is_integral<T>::value || std::is_floating_point<T>::value,
  1089. details::vf_number<T>,
  1090. typename std::conditional<details::can_make_string<T>::value,
  1091. String,
  1092. details::vf_fallback<T>>::type>::type;
  1093. return Helper::From(env, value);
  1094. }
  1095. template <typename T>
  1096. String String::From(napi_env env, const T& value) {
  1097. struct Dummy {};
  1098. using Helper = typename std::conditional<
  1099. std::is_convertible<T, const char*>::value,
  1100. details::vf_utf8_charp,
  1101. typename std::conditional<
  1102. std::is_convertible<T, const char16_t*>::value,
  1103. details::vf_utf16_charp,
  1104. typename std::conditional<
  1105. std::is_convertible<T, std::string>::value,
  1106. details::vf_utf8_string,
  1107. typename std::conditional<
  1108. std::is_convertible<T, std::u16string>::value,
  1109. details::vf_utf16_string,
  1110. Dummy>::type>::type>::type>::type;
  1111. return Helper::From(env, value);
  1112. }
  1113. ////////////////////////////////////////////////////////////////////////////////
  1114. // TypeTaggable class
  1115. ////////////////////////////////////////////////////////////////////////////////
  1116. inline TypeTaggable::TypeTaggable() : Value() {}
  1117. inline TypeTaggable::TypeTaggable(napi_env _env, napi_value _value)
  1118. : Value(_env, _value) {}
  1119. #if NAPI_VERSION >= 8
  1120. inline void TypeTaggable::TypeTag(const napi_type_tag* type_tag) const {
  1121. napi_status status = napi_type_tag_object(_env, _value, type_tag);
  1122. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1123. }
  1124. inline bool TypeTaggable::CheckTypeTag(const napi_type_tag* type_tag) const {
  1125. bool result;
  1126. napi_status status =
  1127. napi_check_object_type_tag(_env, _value, type_tag, &result);
  1128. NAPI_THROW_IF_FAILED(_env, status, false);
  1129. return result;
  1130. }
  1131. #endif // NAPI_VERSION >= 8
  1132. ////////////////////////////////////////////////////////////////////////////////
  1133. // Object class
  1134. ////////////////////////////////////////////////////////////////////////////////
  1135. template <typename Key>
  1136. inline Object::PropertyLValue<Key>::operator Value() const {
  1137. MaybeOrValue<Value> val = Object(_env, _object).Get(_key);
  1138. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  1139. return val.Unwrap();
  1140. #else
  1141. return val;
  1142. #endif
  1143. }
  1144. template <typename Key>
  1145. template <typename ValueType>
  1146. inline Object::PropertyLValue<Key>& Object::PropertyLValue<Key>::operator=(
  1147. ValueType value) {
  1148. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  1149. MaybeOrValue<bool> result =
  1150. #endif
  1151. Object(_env, _object).Set(_key, value);
  1152. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  1153. result.Unwrap();
  1154. #endif
  1155. return *this;
  1156. }
  1157. template <typename Key>
  1158. inline Object::PropertyLValue<Key>::PropertyLValue(Object object, Key key)
  1159. : _env(object.Env()), _object(object), _key(key) {}
  1160. inline Object Object::New(napi_env env) {
  1161. napi_value value;
  1162. napi_status status = napi_create_object(env, &value);
  1163. NAPI_THROW_IF_FAILED(env, status, Object());
  1164. return Object(env, value);
  1165. }
  1166. inline void Object::CheckCast(napi_env env, napi_value value) {
  1167. NAPI_CHECK(value != nullptr, "Object::CheckCast", "empty value");
  1168. napi_valuetype type;
  1169. napi_status status = napi_typeof(env, value, &type);
  1170. NAPI_CHECK(status == napi_ok, "Object::CheckCast", "napi_typeof failed");
  1171. NAPI_CHECK(
  1172. type == napi_object, "Object::CheckCast", "value is not napi_object");
  1173. }
  1174. inline Object::Object() : TypeTaggable() {}
  1175. inline Object::Object(napi_env env, napi_value value)
  1176. : TypeTaggable(env, value) {}
  1177. inline Object::PropertyLValue<std::string> Object::operator[](
  1178. const char* utf8name) {
  1179. return PropertyLValue<std::string>(*this, utf8name);
  1180. }
  1181. inline Object::PropertyLValue<std::string> Object::operator[](
  1182. const std::string& utf8name) {
  1183. return PropertyLValue<std::string>(*this, utf8name);
  1184. }
  1185. inline Object::PropertyLValue<uint32_t> Object::operator[](uint32_t index) {
  1186. return PropertyLValue<uint32_t>(*this, index);
  1187. }
  1188. inline Object::PropertyLValue<Value> Object::operator[](Value index) const {
  1189. return PropertyLValue<Value>(*this, index);
  1190. }
  1191. inline MaybeOrValue<Value> Object::operator[](const char* utf8name) const {
  1192. return Get(utf8name);
  1193. }
  1194. inline MaybeOrValue<Value> Object::operator[](
  1195. const std::string& utf8name) const {
  1196. return Get(utf8name);
  1197. }
  1198. inline MaybeOrValue<Value> Object::operator[](uint32_t index) const {
  1199. return Get(index);
  1200. }
  1201. inline MaybeOrValue<bool> Object::Has(napi_value key) const {
  1202. bool result;
  1203. napi_status status = napi_has_property(_env, _value, key, &result);
  1204. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1205. }
  1206. inline MaybeOrValue<bool> Object::Has(Value key) const {
  1207. bool result;
  1208. napi_status status = napi_has_property(_env, _value, key, &result);
  1209. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1210. }
  1211. inline MaybeOrValue<bool> Object::Has(const char* utf8name) const {
  1212. bool result;
  1213. napi_status status = napi_has_named_property(_env, _value, utf8name, &result);
  1214. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1215. }
  1216. inline MaybeOrValue<bool> Object::Has(const std::string& utf8name) const {
  1217. return Has(utf8name.c_str());
  1218. }
  1219. inline MaybeOrValue<bool> Object::HasOwnProperty(napi_value key) const {
  1220. bool result;
  1221. napi_status status = napi_has_own_property(_env, _value, key, &result);
  1222. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1223. }
  1224. inline MaybeOrValue<bool> Object::HasOwnProperty(Value key) const {
  1225. bool result;
  1226. napi_status status = napi_has_own_property(_env, _value, key, &result);
  1227. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1228. }
  1229. inline MaybeOrValue<bool> Object::HasOwnProperty(const char* utf8name) const {
  1230. napi_value key;
  1231. napi_status status =
  1232. napi_create_string_utf8(_env, utf8name, std::strlen(utf8name), &key);
  1233. NAPI_MAYBE_THROW_IF_FAILED(_env, status, bool);
  1234. return HasOwnProperty(key);
  1235. }
  1236. inline MaybeOrValue<bool> Object::HasOwnProperty(
  1237. const std::string& utf8name) const {
  1238. return HasOwnProperty(utf8name.c_str());
  1239. }
  1240. inline MaybeOrValue<Value> Object::Get(napi_value key) const {
  1241. napi_value result;
  1242. napi_status status = napi_get_property(_env, _value, key, &result);
  1243. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value);
  1244. }
  1245. inline MaybeOrValue<Value> Object::Get(Value key) const {
  1246. napi_value result;
  1247. napi_status status = napi_get_property(_env, _value, key, &result);
  1248. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value);
  1249. }
  1250. inline MaybeOrValue<Value> Object::Get(const char* utf8name) const {
  1251. napi_value result;
  1252. napi_status status = napi_get_named_property(_env, _value, utf8name, &result);
  1253. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value);
  1254. }
  1255. inline MaybeOrValue<Value> Object::Get(const std::string& utf8name) const {
  1256. return Get(utf8name.c_str());
  1257. }
  1258. template <typename ValueType>
  1259. inline MaybeOrValue<bool> Object::Set(napi_value key,
  1260. const ValueType& value) const {
  1261. napi_status status =
  1262. napi_set_property(_env, _value, key, Value::From(_env, value));
  1263. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1264. }
  1265. template <typename ValueType>
  1266. inline MaybeOrValue<bool> Object::Set(Value key, const ValueType& value) const {
  1267. napi_status status =
  1268. napi_set_property(_env, _value, key, Value::From(_env, value));
  1269. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1270. }
  1271. template <typename ValueType>
  1272. inline MaybeOrValue<bool> Object::Set(const char* utf8name,
  1273. const ValueType& value) const {
  1274. napi_status status =
  1275. napi_set_named_property(_env, _value, utf8name, Value::From(_env, value));
  1276. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1277. }
  1278. template <typename ValueType>
  1279. inline MaybeOrValue<bool> Object::Set(const std::string& utf8name,
  1280. const ValueType& value) const {
  1281. return Set(utf8name.c_str(), value);
  1282. }
  1283. inline MaybeOrValue<bool> Object::Delete(napi_value key) const {
  1284. bool result;
  1285. napi_status status = napi_delete_property(_env, _value, key, &result);
  1286. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1287. }
  1288. inline MaybeOrValue<bool> Object::Delete(Value key) const {
  1289. bool result;
  1290. napi_status status = napi_delete_property(_env, _value, key, &result);
  1291. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1292. }
  1293. inline MaybeOrValue<bool> Object::Delete(const char* utf8name) const {
  1294. return Delete(String::New(_env, utf8name));
  1295. }
  1296. inline MaybeOrValue<bool> Object::Delete(const std::string& utf8name) const {
  1297. return Delete(String::New(_env, utf8name));
  1298. }
  1299. inline MaybeOrValue<bool> Object::Has(uint32_t index) const {
  1300. bool result;
  1301. napi_status status = napi_has_element(_env, _value, index, &result);
  1302. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1303. }
  1304. inline MaybeOrValue<Value> Object::Get(uint32_t index) const {
  1305. napi_value value;
  1306. napi_status status = napi_get_element(_env, _value, index, &value);
  1307. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, value), Value);
  1308. }
  1309. template <typename ValueType>
  1310. inline MaybeOrValue<bool> Object::Set(uint32_t index,
  1311. const ValueType& value) const {
  1312. napi_status status =
  1313. napi_set_element(_env, _value, index, Value::From(_env, value));
  1314. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1315. }
  1316. inline MaybeOrValue<bool> Object::Delete(uint32_t index) const {
  1317. bool result;
  1318. napi_status status = napi_delete_element(_env, _value, index, &result);
  1319. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1320. }
  1321. inline MaybeOrValue<Array> Object::GetPropertyNames() const {
  1322. napi_value result;
  1323. napi_status status = napi_get_property_names(_env, _value, &result);
  1324. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Array(_env, result), Array);
  1325. }
  1326. inline MaybeOrValue<bool> Object::DefineProperty(
  1327. const PropertyDescriptor& property) const {
  1328. napi_status status = napi_define_properties(
  1329. _env,
  1330. _value,
  1331. 1,
  1332. reinterpret_cast<const napi_property_descriptor*>(&property));
  1333. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1334. }
  1335. inline MaybeOrValue<bool> Object::DefineProperties(
  1336. const std::initializer_list<PropertyDescriptor>& properties) const {
  1337. napi_status status = napi_define_properties(
  1338. _env,
  1339. _value,
  1340. properties.size(),
  1341. reinterpret_cast<const napi_property_descriptor*>(properties.begin()));
  1342. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1343. }
  1344. inline MaybeOrValue<bool> Object::DefineProperties(
  1345. const std::vector<PropertyDescriptor>& properties) const {
  1346. napi_status status = napi_define_properties(
  1347. _env,
  1348. _value,
  1349. properties.size(),
  1350. reinterpret_cast<const napi_property_descriptor*>(properties.data()));
  1351. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1352. }
  1353. inline MaybeOrValue<bool> Object::InstanceOf(
  1354. const Function& constructor) const {
  1355. bool result;
  1356. napi_status status = napi_instanceof(_env, _value, constructor, &result);
  1357. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool);
  1358. }
  1359. template <typename Finalizer, typename T>
  1360. inline void Object::AddFinalizer(Finalizer finalizeCallback, T* data) const {
  1361. details::FinalizeData<T, Finalizer>* finalizeData =
  1362. new details::FinalizeData<T, Finalizer>(
  1363. {std::move(finalizeCallback), nullptr});
  1364. napi_status status =
  1365. details::AttachData(_env,
  1366. *this,
  1367. data,
  1368. details::FinalizeData<T, Finalizer>::Wrapper,
  1369. finalizeData);
  1370. if (status != napi_ok) {
  1371. delete finalizeData;
  1372. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1373. }
  1374. }
  1375. template <typename Finalizer, typename T, typename Hint>
  1376. inline void Object::AddFinalizer(Finalizer finalizeCallback,
  1377. T* data,
  1378. Hint* finalizeHint) const {
  1379. details::FinalizeData<T, Finalizer, Hint>* finalizeData =
  1380. new details::FinalizeData<T, Finalizer, Hint>(
  1381. {std::move(finalizeCallback), finalizeHint});
  1382. napi_status status = details::AttachData(
  1383. _env,
  1384. *this,
  1385. data,
  1386. details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint,
  1387. finalizeData);
  1388. if (status != napi_ok) {
  1389. delete finalizeData;
  1390. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1391. }
  1392. }
  1393. #ifdef NAPI_CPP_EXCEPTIONS
  1394. inline Object::const_iterator::const_iterator(const Object* object,
  1395. const Type type) {
  1396. _object = object;
  1397. _keys = object->GetPropertyNames();
  1398. _index = type == Type::BEGIN ? 0 : _keys.Length();
  1399. }
  1400. inline Object::const_iterator Napi::Object::begin() const {
  1401. const_iterator it(this, Object::const_iterator::Type::BEGIN);
  1402. return it;
  1403. }
  1404. inline Object::const_iterator Napi::Object::end() const {
  1405. const_iterator it(this, Object::const_iterator::Type::END);
  1406. return it;
  1407. }
  1408. inline Object::const_iterator& Object::const_iterator::operator++() {
  1409. ++_index;
  1410. return *this;
  1411. }
  1412. inline bool Object::const_iterator::operator==(
  1413. const const_iterator& other) const {
  1414. return _index == other._index;
  1415. }
  1416. inline bool Object::const_iterator::operator!=(
  1417. const const_iterator& other) const {
  1418. return _index != other._index;
  1419. }
  1420. inline const std::pair<Value, Object::PropertyLValue<Value>>
  1421. Object::const_iterator::operator*() const {
  1422. const Value key = _keys[_index];
  1423. const PropertyLValue<Value> value = (*_object)[key];
  1424. return {key, value};
  1425. }
  1426. inline Object::iterator::iterator(Object* object, const Type type) {
  1427. _object = object;
  1428. _keys = object->GetPropertyNames();
  1429. _index = type == Type::BEGIN ? 0 : _keys.Length();
  1430. }
  1431. inline Object::iterator Napi::Object::begin() {
  1432. iterator it(this, Object::iterator::Type::BEGIN);
  1433. return it;
  1434. }
  1435. inline Object::iterator Napi::Object::end() {
  1436. iterator it(this, Object::iterator::Type::END);
  1437. return it;
  1438. }
  1439. inline Object::iterator& Object::iterator::operator++() {
  1440. ++_index;
  1441. return *this;
  1442. }
  1443. inline bool Object::iterator::operator==(const iterator& other) const {
  1444. return _index == other._index;
  1445. }
  1446. inline bool Object::iterator::operator!=(const iterator& other) const {
  1447. return _index != other._index;
  1448. }
  1449. inline std::pair<Value, Object::PropertyLValue<Value>>
  1450. Object::iterator::operator*() {
  1451. Value key = _keys[_index];
  1452. PropertyLValue<Value> value = (*_object)[key];
  1453. return {key, value};
  1454. }
  1455. #endif // NAPI_CPP_EXCEPTIONS
  1456. #if NAPI_VERSION >= 8
  1457. inline MaybeOrValue<bool> Object::Freeze() const {
  1458. napi_status status = napi_object_freeze(_env, _value);
  1459. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1460. }
  1461. inline MaybeOrValue<bool> Object::Seal() const {
  1462. napi_status status = napi_object_seal(_env, _value);
  1463. NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool);
  1464. }
  1465. #endif // NAPI_VERSION >= 8
  1466. ////////////////////////////////////////////////////////////////////////////////
  1467. // External class
  1468. ////////////////////////////////////////////////////////////////////////////////
  1469. template <typename T>
  1470. inline External<T> External<T>::New(napi_env env, T* data) {
  1471. napi_value value;
  1472. napi_status status =
  1473. napi_create_external(env, data, nullptr, nullptr, &value);
  1474. NAPI_THROW_IF_FAILED(env, status, External());
  1475. return External(env, value);
  1476. }
  1477. template <typename T>
  1478. template <typename Finalizer>
  1479. inline External<T> External<T>::New(napi_env env,
  1480. T* data,
  1481. Finalizer finalizeCallback) {
  1482. napi_value value;
  1483. details::FinalizeData<T, Finalizer>* finalizeData =
  1484. new details::FinalizeData<T, Finalizer>(
  1485. {std::move(finalizeCallback), nullptr});
  1486. napi_status status =
  1487. napi_create_external(env,
  1488. data,
  1489. details::FinalizeData<T, Finalizer>::Wrapper,
  1490. finalizeData,
  1491. &value);
  1492. if (status != napi_ok) {
  1493. delete finalizeData;
  1494. NAPI_THROW_IF_FAILED(env, status, External());
  1495. }
  1496. return External(env, value);
  1497. }
  1498. template <typename T>
  1499. template <typename Finalizer, typename Hint>
  1500. inline External<T> External<T>::New(napi_env env,
  1501. T* data,
  1502. Finalizer finalizeCallback,
  1503. Hint* finalizeHint) {
  1504. napi_value value;
  1505. details::FinalizeData<T, Finalizer, Hint>* finalizeData =
  1506. new details::FinalizeData<T, Finalizer, Hint>(
  1507. {std::move(finalizeCallback), finalizeHint});
  1508. napi_status status = napi_create_external(
  1509. env,
  1510. data,
  1511. details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint,
  1512. finalizeData,
  1513. &value);
  1514. if (status != napi_ok) {
  1515. delete finalizeData;
  1516. NAPI_THROW_IF_FAILED(env, status, External());
  1517. }
  1518. return External(env, value);
  1519. }
  1520. template <typename T>
  1521. inline void External<T>::CheckCast(napi_env env, napi_value value) {
  1522. NAPI_CHECK(value != nullptr, "External::CheckCast", "empty value");
  1523. napi_valuetype type;
  1524. napi_status status = napi_typeof(env, value, &type);
  1525. NAPI_CHECK(status == napi_ok, "External::CheckCast", "napi_typeof failed");
  1526. NAPI_CHECK(type == napi_external,
  1527. "External::CheckCast",
  1528. "value is not napi_external");
  1529. }
  1530. template <typename T>
  1531. inline External<T>::External() : TypeTaggable() {}
  1532. template <typename T>
  1533. inline External<T>::External(napi_env env, napi_value value)
  1534. : TypeTaggable(env, value) {}
  1535. template <typename T>
  1536. inline T* External<T>::Data() const {
  1537. void* data;
  1538. napi_status status = napi_get_value_external(_env, _value, &data);
  1539. NAPI_THROW_IF_FAILED(_env, status, nullptr);
  1540. return reinterpret_cast<T*>(data);
  1541. }
  1542. ////////////////////////////////////////////////////////////////////////////////
  1543. // Array class
  1544. ////////////////////////////////////////////////////////////////////////////////
  1545. inline Array Array::New(napi_env env) {
  1546. napi_value value;
  1547. napi_status status = napi_create_array(env, &value);
  1548. NAPI_THROW_IF_FAILED(env, status, Array());
  1549. return Array(env, value);
  1550. }
  1551. inline Array Array::New(napi_env env, size_t length) {
  1552. napi_value value;
  1553. napi_status status = napi_create_array_with_length(env, length, &value);
  1554. NAPI_THROW_IF_FAILED(env, status, Array());
  1555. return Array(env, value);
  1556. }
  1557. inline void Array::CheckCast(napi_env env, napi_value value) {
  1558. NAPI_CHECK(value != nullptr, "Array::CheckCast", "empty value");
  1559. bool result;
  1560. napi_status status = napi_is_array(env, value, &result);
  1561. NAPI_CHECK(status == napi_ok, "Array::CheckCast", "napi_is_array failed");
  1562. NAPI_CHECK(result, "Array::CheckCast", "value is not array");
  1563. }
  1564. inline Array::Array() : Object() {}
  1565. inline Array::Array(napi_env env, napi_value value) : Object(env, value) {}
  1566. inline uint32_t Array::Length() const {
  1567. uint32_t result;
  1568. napi_status status = napi_get_array_length(_env, _value, &result);
  1569. NAPI_THROW_IF_FAILED(_env, status, 0);
  1570. return result;
  1571. }
  1572. ////////////////////////////////////////////////////////////////////////////////
  1573. // ArrayBuffer class
  1574. ////////////////////////////////////////////////////////////////////////////////
  1575. inline ArrayBuffer ArrayBuffer::New(napi_env env, size_t byteLength) {
  1576. napi_value value;
  1577. void* data;
  1578. napi_status status = napi_create_arraybuffer(env, byteLength, &data, &value);
  1579. NAPI_THROW_IF_FAILED(env, status, ArrayBuffer());
  1580. return ArrayBuffer(env, value);
  1581. }
  1582. #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  1583. inline ArrayBuffer ArrayBuffer::New(napi_env env,
  1584. void* externalData,
  1585. size_t byteLength) {
  1586. napi_value value;
  1587. napi_status status = napi_create_external_arraybuffer(
  1588. env, externalData, byteLength, nullptr, nullptr, &value);
  1589. NAPI_THROW_IF_FAILED(env, status, ArrayBuffer());
  1590. return ArrayBuffer(env, value);
  1591. }
  1592. template <typename Finalizer>
  1593. inline ArrayBuffer ArrayBuffer::New(napi_env env,
  1594. void* externalData,
  1595. size_t byteLength,
  1596. Finalizer finalizeCallback) {
  1597. napi_value value;
  1598. details::FinalizeData<void, Finalizer>* finalizeData =
  1599. new details::FinalizeData<void, Finalizer>(
  1600. {std::move(finalizeCallback), nullptr});
  1601. napi_status status = napi_create_external_arraybuffer(
  1602. env,
  1603. externalData,
  1604. byteLength,
  1605. details::FinalizeData<void, Finalizer>::Wrapper,
  1606. finalizeData,
  1607. &value);
  1608. if (status != napi_ok) {
  1609. delete finalizeData;
  1610. NAPI_THROW_IF_FAILED(env, status, ArrayBuffer());
  1611. }
  1612. return ArrayBuffer(env, value);
  1613. }
  1614. template <typename Finalizer, typename Hint>
  1615. inline ArrayBuffer ArrayBuffer::New(napi_env env,
  1616. void* externalData,
  1617. size_t byteLength,
  1618. Finalizer finalizeCallback,
  1619. Hint* finalizeHint) {
  1620. napi_value value;
  1621. details::FinalizeData<void, Finalizer, Hint>* finalizeData =
  1622. new details::FinalizeData<void, Finalizer, Hint>(
  1623. {std::move(finalizeCallback), finalizeHint});
  1624. napi_status status = napi_create_external_arraybuffer(
  1625. env,
  1626. externalData,
  1627. byteLength,
  1628. details::FinalizeData<void, Finalizer, Hint>::WrapperWithHint,
  1629. finalizeData,
  1630. &value);
  1631. if (status != napi_ok) {
  1632. delete finalizeData;
  1633. NAPI_THROW_IF_FAILED(env, status, ArrayBuffer());
  1634. }
  1635. return ArrayBuffer(env, value);
  1636. }
  1637. #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  1638. inline void ArrayBuffer::CheckCast(napi_env env, napi_value value) {
  1639. NAPI_CHECK(value != nullptr, "ArrayBuffer::CheckCast", "empty value");
  1640. bool result;
  1641. napi_status status = napi_is_arraybuffer(env, value, &result);
  1642. NAPI_CHECK(status == napi_ok,
  1643. "ArrayBuffer::CheckCast",
  1644. "napi_is_arraybuffer failed");
  1645. NAPI_CHECK(result, "ArrayBuffer::CheckCast", "value is not arraybuffer");
  1646. }
  1647. inline ArrayBuffer::ArrayBuffer() : Object() {}
  1648. inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value)
  1649. : Object(env, value) {}
  1650. inline void* ArrayBuffer::Data() {
  1651. void* data;
  1652. napi_status status = napi_get_arraybuffer_info(_env, _value, &data, nullptr);
  1653. NAPI_THROW_IF_FAILED(_env, status, nullptr);
  1654. return data;
  1655. }
  1656. inline size_t ArrayBuffer::ByteLength() {
  1657. size_t length;
  1658. napi_status status =
  1659. napi_get_arraybuffer_info(_env, _value, nullptr, &length);
  1660. NAPI_THROW_IF_FAILED(_env, status, 0);
  1661. return length;
  1662. }
  1663. #if NAPI_VERSION >= 7
  1664. inline bool ArrayBuffer::IsDetached() const {
  1665. bool detached;
  1666. napi_status status = napi_is_detached_arraybuffer(_env, _value, &detached);
  1667. NAPI_THROW_IF_FAILED(_env, status, false);
  1668. return detached;
  1669. }
  1670. inline void ArrayBuffer::Detach() {
  1671. napi_status status = napi_detach_arraybuffer(_env, _value);
  1672. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1673. }
  1674. #endif // NAPI_VERSION >= 7
  1675. ////////////////////////////////////////////////////////////////////////////////
  1676. // DataView class
  1677. ////////////////////////////////////////////////////////////////////////////////
  1678. inline DataView DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer) {
  1679. return New(env, arrayBuffer, 0, arrayBuffer.ByteLength());
  1680. }
  1681. inline DataView DataView::New(napi_env env,
  1682. Napi::ArrayBuffer arrayBuffer,
  1683. size_t byteOffset) {
  1684. if (byteOffset > arrayBuffer.ByteLength()) {
  1685. NAPI_THROW(RangeError::New(
  1686. env, "Start offset is outside the bounds of the buffer"),
  1687. DataView());
  1688. }
  1689. return New(
  1690. env, arrayBuffer, byteOffset, arrayBuffer.ByteLength() - byteOffset);
  1691. }
  1692. inline DataView DataView::New(napi_env env,
  1693. Napi::ArrayBuffer arrayBuffer,
  1694. size_t byteOffset,
  1695. size_t byteLength) {
  1696. if (byteOffset + byteLength > arrayBuffer.ByteLength()) {
  1697. NAPI_THROW(RangeError::New(env, "Invalid DataView length"), DataView());
  1698. }
  1699. napi_value value;
  1700. napi_status status =
  1701. napi_create_dataview(env, byteLength, arrayBuffer, byteOffset, &value);
  1702. NAPI_THROW_IF_FAILED(env, status, DataView());
  1703. return DataView(env, value);
  1704. }
  1705. inline void DataView::CheckCast(napi_env env, napi_value value) {
  1706. NAPI_CHECK(value != nullptr, "DataView::CheckCast", "empty value");
  1707. bool result;
  1708. napi_status status = napi_is_dataview(env, value, &result);
  1709. NAPI_CHECK(
  1710. status == napi_ok, "DataView::CheckCast", "napi_is_dataview failed");
  1711. NAPI_CHECK(result, "DataView::CheckCast", "value is not dataview");
  1712. }
  1713. inline DataView::DataView() : Object() {}
  1714. inline DataView::DataView(napi_env env, napi_value value) : Object(env, value) {
  1715. napi_status status = napi_get_dataview_info(_env,
  1716. _value /* dataView */,
  1717. &_length /* byteLength */,
  1718. &_data /* data */,
  1719. nullptr /* arrayBuffer */,
  1720. nullptr /* byteOffset */);
  1721. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1722. }
  1723. inline Napi::ArrayBuffer DataView::ArrayBuffer() const {
  1724. napi_value arrayBuffer;
  1725. napi_status status = napi_get_dataview_info(_env,
  1726. _value /* dataView */,
  1727. nullptr /* byteLength */,
  1728. nullptr /* data */,
  1729. &arrayBuffer /* arrayBuffer */,
  1730. nullptr /* byteOffset */);
  1731. NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer());
  1732. return Napi::ArrayBuffer(_env, arrayBuffer);
  1733. }
  1734. inline size_t DataView::ByteOffset() const {
  1735. size_t byteOffset;
  1736. napi_status status = napi_get_dataview_info(_env,
  1737. _value /* dataView */,
  1738. nullptr /* byteLength */,
  1739. nullptr /* data */,
  1740. nullptr /* arrayBuffer */,
  1741. &byteOffset /* byteOffset */);
  1742. NAPI_THROW_IF_FAILED(_env, status, 0);
  1743. return byteOffset;
  1744. }
  1745. inline size_t DataView::ByteLength() const {
  1746. return _length;
  1747. }
  1748. inline void* DataView::Data() const {
  1749. return _data;
  1750. }
  1751. inline float DataView::GetFloat32(size_t byteOffset) const {
  1752. return ReadData<float>(byteOffset);
  1753. }
  1754. inline double DataView::GetFloat64(size_t byteOffset) const {
  1755. return ReadData<double>(byteOffset);
  1756. }
  1757. inline int8_t DataView::GetInt8(size_t byteOffset) const {
  1758. return ReadData<int8_t>(byteOffset);
  1759. }
  1760. inline int16_t DataView::GetInt16(size_t byteOffset) const {
  1761. return ReadData<int16_t>(byteOffset);
  1762. }
  1763. inline int32_t DataView::GetInt32(size_t byteOffset) const {
  1764. return ReadData<int32_t>(byteOffset);
  1765. }
  1766. inline uint8_t DataView::GetUint8(size_t byteOffset) const {
  1767. return ReadData<uint8_t>(byteOffset);
  1768. }
  1769. inline uint16_t DataView::GetUint16(size_t byteOffset) const {
  1770. return ReadData<uint16_t>(byteOffset);
  1771. }
  1772. inline uint32_t DataView::GetUint32(size_t byteOffset) const {
  1773. return ReadData<uint32_t>(byteOffset);
  1774. }
  1775. inline void DataView::SetFloat32(size_t byteOffset, float value) const {
  1776. WriteData<float>(byteOffset, value);
  1777. }
  1778. inline void DataView::SetFloat64(size_t byteOffset, double value) const {
  1779. WriteData<double>(byteOffset, value);
  1780. }
  1781. inline void DataView::SetInt8(size_t byteOffset, int8_t value) const {
  1782. WriteData<int8_t>(byteOffset, value);
  1783. }
  1784. inline void DataView::SetInt16(size_t byteOffset, int16_t value) const {
  1785. WriteData<int16_t>(byteOffset, value);
  1786. }
  1787. inline void DataView::SetInt32(size_t byteOffset, int32_t value) const {
  1788. WriteData<int32_t>(byteOffset, value);
  1789. }
  1790. inline void DataView::SetUint8(size_t byteOffset, uint8_t value) const {
  1791. WriteData<uint8_t>(byteOffset, value);
  1792. }
  1793. inline void DataView::SetUint16(size_t byteOffset, uint16_t value) const {
  1794. WriteData<uint16_t>(byteOffset, value);
  1795. }
  1796. inline void DataView::SetUint32(size_t byteOffset, uint32_t value) const {
  1797. WriteData<uint32_t>(byteOffset, value);
  1798. }
  1799. template <typename T>
  1800. inline T DataView::ReadData(size_t byteOffset) const {
  1801. if (byteOffset + sizeof(T) > _length ||
  1802. byteOffset + sizeof(T) < byteOffset) { // overflow
  1803. NAPI_THROW(
  1804. RangeError::New(_env, "Offset is outside the bounds of the DataView"),
  1805. 0);
  1806. }
  1807. return *reinterpret_cast<T*>(static_cast<uint8_t*>(_data) + byteOffset);
  1808. }
  1809. template <typename T>
  1810. inline void DataView::WriteData(size_t byteOffset, T value) const {
  1811. if (byteOffset + sizeof(T) > _length ||
  1812. byteOffset + sizeof(T) < byteOffset) { // overflow
  1813. NAPI_THROW_VOID(
  1814. RangeError::New(_env, "Offset is outside the bounds of the DataView"));
  1815. }
  1816. *reinterpret_cast<T*>(static_cast<uint8_t*>(_data) + byteOffset) = value;
  1817. }
  1818. ////////////////////////////////////////////////////////////////////////////////
  1819. // TypedArray class
  1820. ////////////////////////////////////////////////////////////////////////////////
  1821. inline void TypedArray::CheckCast(napi_env env, napi_value value) {
  1822. NAPI_CHECK(value != nullptr, "TypedArray::CheckCast", "empty value");
  1823. bool result;
  1824. napi_status status = napi_is_typedarray(env, value, &result);
  1825. NAPI_CHECK(
  1826. status == napi_ok, "TypedArray::CheckCast", "napi_is_typedarray failed");
  1827. NAPI_CHECK(result, "TypedArray::CheckCast", "value is not typedarray");
  1828. }
  1829. inline TypedArray::TypedArray()
  1830. : Object(), _type(napi_typedarray_type::napi_int8_array), _length(0) {}
  1831. inline TypedArray::TypedArray(napi_env env, napi_value value)
  1832. : Object(env, value),
  1833. _type(napi_typedarray_type::napi_int8_array),
  1834. _length(0) {
  1835. if (value != nullptr) {
  1836. napi_status status =
  1837. napi_get_typedarray_info(_env,
  1838. _value,
  1839. &const_cast<TypedArray*>(this)->_type,
  1840. &const_cast<TypedArray*>(this)->_length,
  1841. nullptr,
  1842. nullptr,
  1843. nullptr);
  1844. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1845. }
  1846. }
  1847. inline TypedArray::TypedArray(napi_env env,
  1848. napi_value value,
  1849. napi_typedarray_type type,
  1850. size_t length)
  1851. : Object(env, value), _type(type), _length(length) {}
  1852. inline napi_typedarray_type TypedArray::TypedArrayType() const {
  1853. return _type;
  1854. }
  1855. inline uint8_t TypedArray::ElementSize() const {
  1856. switch (_type) {
  1857. case napi_int8_array:
  1858. case napi_uint8_array:
  1859. case napi_uint8_clamped_array:
  1860. return 1;
  1861. case napi_int16_array:
  1862. case napi_uint16_array:
  1863. return 2;
  1864. case napi_int32_array:
  1865. case napi_uint32_array:
  1866. case napi_float32_array:
  1867. return 4;
  1868. case napi_float64_array:
  1869. #if (NAPI_VERSION > 5)
  1870. case napi_bigint64_array:
  1871. case napi_biguint64_array:
  1872. #endif // (NAPI_VERSION > 5)
  1873. return 8;
  1874. default:
  1875. return 0;
  1876. }
  1877. }
  1878. inline size_t TypedArray::ElementLength() const {
  1879. return _length;
  1880. }
  1881. inline size_t TypedArray::ByteOffset() const {
  1882. size_t byteOffset;
  1883. napi_status status = napi_get_typedarray_info(
  1884. _env, _value, nullptr, nullptr, nullptr, nullptr, &byteOffset);
  1885. NAPI_THROW_IF_FAILED(_env, status, 0);
  1886. return byteOffset;
  1887. }
  1888. inline size_t TypedArray::ByteLength() const {
  1889. return ElementSize() * ElementLength();
  1890. }
  1891. inline Napi::ArrayBuffer TypedArray::ArrayBuffer() const {
  1892. napi_value arrayBuffer;
  1893. napi_status status = napi_get_typedarray_info(
  1894. _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr);
  1895. NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer());
  1896. return Napi::ArrayBuffer(_env, arrayBuffer);
  1897. }
  1898. ////////////////////////////////////////////////////////////////////////////////
  1899. // TypedArrayOf<T> class
  1900. ////////////////////////////////////////////////////////////////////////////////
  1901. template <typename T>
  1902. inline void TypedArrayOf<T>::CheckCast(napi_env env, napi_value value) {
  1903. TypedArray::CheckCast(env, value);
  1904. napi_typedarray_type type;
  1905. napi_status status = napi_get_typedarray_info(
  1906. env, value, &type, nullptr, nullptr, nullptr, nullptr);
  1907. NAPI_CHECK(status == napi_ok,
  1908. "TypedArrayOf::CheckCast",
  1909. "napi_is_typedarray failed");
  1910. NAPI_CHECK(
  1911. (type == TypedArrayTypeForPrimitiveType<T>() ||
  1912. (type == napi_uint8_clamped_array && std::is_same<T, uint8_t>::value)),
  1913. "TypedArrayOf::CheckCast",
  1914. "Array type must match the template parameter. (Uint8 arrays may "
  1915. "optionally have the \"clamped\" array type.)");
  1916. }
  1917. template <typename T>
  1918. inline TypedArrayOf<T> TypedArrayOf<T>::New(napi_env env,
  1919. size_t elementLength,
  1920. napi_typedarray_type type) {
  1921. Napi::ArrayBuffer arrayBuffer =
  1922. Napi::ArrayBuffer::New(env, elementLength * sizeof(T));
  1923. return New(env, elementLength, arrayBuffer, 0, type);
  1924. }
  1925. template <typename T>
  1926. inline TypedArrayOf<T> TypedArrayOf<T>::New(napi_env env,
  1927. size_t elementLength,
  1928. Napi::ArrayBuffer arrayBuffer,
  1929. size_t bufferOffset,
  1930. napi_typedarray_type type) {
  1931. napi_value value;
  1932. napi_status status = napi_create_typedarray(
  1933. env, type, elementLength, arrayBuffer, bufferOffset, &value);
  1934. NAPI_THROW_IF_FAILED(env, status, TypedArrayOf<T>());
  1935. return TypedArrayOf<T>(
  1936. env,
  1937. value,
  1938. type,
  1939. elementLength,
  1940. reinterpret_cast<T*>(reinterpret_cast<uint8_t*>(arrayBuffer.Data()) +
  1941. bufferOffset));
  1942. }
  1943. template <typename T>
  1944. inline TypedArrayOf<T>::TypedArrayOf() : TypedArray(), _data(nullptr) {}
  1945. template <typename T>
  1946. inline TypedArrayOf<T>::TypedArrayOf(napi_env env, napi_value value)
  1947. : TypedArray(env, value), _data(nullptr) {
  1948. napi_status status = napi_ok;
  1949. if (value != nullptr) {
  1950. void* data = nullptr;
  1951. status = napi_get_typedarray_info(
  1952. _env, _value, &_type, &_length, &data, nullptr, nullptr);
  1953. _data = static_cast<T*>(data);
  1954. } else {
  1955. _type = TypedArrayTypeForPrimitiveType<T>();
  1956. _length = 0;
  1957. }
  1958. NAPI_THROW_IF_FAILED_VOID(_env, status);
  1959. }
  1960. template <typename T>
  1961. inline TypedArrayOf<T>::TypedArrayOf(napi_env env,
  1962. napi_value value,
  1963. napi_typedarray_type type,
  1964. size_t length,
  1965. T* data)
  1966. : TypedArray(env, value, type, length), _data(data) {
  1967. if (!(type == TypedArrayTypeForPrimitiveType<T>() ||
  1968. (type == napi_uint8_clamped_array &&
  1969. std::is_same<T, uint8_t>::value))) {
  1970. NAPI_THROW_VOID(TypeError::New(
  1971. env,
  1972. "Array type must match the template parameter. "
  1973. "(Uint8 arrays may optionally have the \"clamped\" array type.)"));
  1974. }
  1975. }
  1976. template <typename T>
  1977. inline T& TypedArrayOf<T>::operator[](size_t index) {
  1978. return _data[index];
  1979. }
  1980. template <typename T>
  1981. inline const T& TypedArrayOf<T>::operator[](size_t index) const {
  1982. return _data[index];
  1983. }
  1984. template <typename T>
  1985. inline T* TypedArrayOf<T>::Data() {
  1986. return _data;
  1987. }
  1988. template <typename T>
  1989. inline const T* TypedArrayOf<T>::Data() const {
  1990. return _data;
  1991. }
  1992. ////////////////////////////////////////////////////////////////////////////////
  1993. // Function class
  1994. ////////////////////////////////////////////////////////////////////////////////
  1995. template <typename CbData>
  1996. inline napi_status CreateFunction(napi_env env,
  1997. const char* utf8name,
  1998. napi_callback cb,
  1999. CbData* data,
  2000. napi_value* result) {
  2001. napi_status status =
  2002. napi_create_function(env, utf8name, NAPI_AUTO_LENGTH, cb, data, result);
  2003. if (status == napi_ok) {
  2004. status = Napi::details::AttachData(env, *result, data);
  2005. }
  2006. return status;
  2007. }
  2008. template <Function::VoidCallback cb>
  2009. inline Function Function::New(napi_env env, const char* utf8name, void* data) {
  2010. napi_value result = nullptr;
  2011. napi_status status = napi_create_function(env,
  2012. utf8name,
  2013. NAPI_AUTO_LENGTH,
  2014. details::TemplatedVoidCallback<cb>,
  2015. data,
  2016. &result);
  2017. NAPI_THROW_IF_FAILED(env, status, Function());
  2018. return Function(env, result);
  2019. }
  2020. template <Function::Callback cb>
  2021. inline Function Function::New(napi_env env, const char* utf8name, void* data) {
  2022. napi_value result = nullptr;
  2023. napi_status status = napi_create_function(env,
  2024. utf8name,
  2025. NAPI_AUTO_LENGTH,
  2026. details::TemplatedCallback<cb>,
  2027. data,
  2028. &result);
  2029. NAPI_THROW_IF_FAILED(env, status, Function());
  2030. return Function(env, result);
  2031. }
  2032. template <Function::VoidCallback cb>
  2033. inline Function Function::New(napi_env env,
  2034. const std::string& utf8name,
  2035. void* data) {
  2036. return Function::New<cb>(env, utf8name.c_str(), data);
  2037. }
  2038. template <Function::Callback cb>
  2039. inline Function Function::New(napi_env env,
  2040. const std::string& utf8name,
  2041. void* data) {
  2042. return Function::New<cb>(env, utf8name.c_str(), data);
  2043. }
  2044. template <typename Callable>
  2045. inline Function Function::New(napi_env env,
  2046. Callable cb,
  2047. const char* utf8name,
  2048. void* data) {
  2049. using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr)));
  2050. using CbData = details::CallbackData<Callable, ReturnType>;
  2051. auto callbackData = new CbData{std::move(cb), data};
  2052. napi_value value;
  2053. napi_status status =
  2054. CreateFunction(env, utf8name, CbData::Wrapper, callbackData, &value);
  2055. if (status != napi_ok) {
  2056. delete callbackData;
  2057. NAPI_THROW_IF_FAILED(env, status, Function());
  2058. }
  2059. return Function(env, value);
  2060. }
  2061. template <typename Callable>
  2062. inline Function Function::New(napi_env env,
  2063. Callable cb,
  2064. const std::string& utf8name,
  2065. void* data) {
  2066. return New(env, cb, utf8name.c_str(), data);
  2067. }
  2068. inline void Function::CheckCast(napi_env env, napi_value value) {
  2069. NAPI_CHECK(value != nullptr, "Function::CheckCast", "empty value");
  2070. napi_valuetype type;
  2071. napi_status status = napi_typeof(env, value, &type);
  2072. NAPI_CHECK(status == napi_ok, "Function::CheckCast", "napi_typeof failed");
  2073. NAPI_CHECK(type == napi_function,
  2074. "Function::CheckCast",
  2075. "value is not napi_function");
  2076. }
  2077. inline Function::Function() : Object() {}
  2078. inline Function::Function(napi_env env, napi_value value)
  2079. : Object(env, value) {}
  2080. inline MaybeOrValue<Value> Function::operator()(
  2081. const std::initializer_list<napi_value>& args) const {
  2082. return Call(Env().Undefined(), args);
  2083. }
  2084. inline MaybeOrValue<Value> Function::Call(
  2085. const std::initializer_list<napi_value>& args) const {
  2086. return Call(Env().Undefined(), args);
  2087. }
  2088. inline MaybeOrValue<Value> Function::Call(
  2089. const std::vector<napi_value>& args) const {
  2090. return Call(Env().Undefined(), args);
  2091. }
  2092. inline MaybeOrValue<Value> Function::Call(
  2093. const std::vector<Value>& args) const {
  2094. return Call(Env().Undefined(), args);
  2095. }
  2096. inline MaybeOrValue<Value> Function::Call(size_t argc,
  2097. const napi_value* args) const {
  2098. return Call(Env().Undefined(), argc, args);
  2099. }
  2100. inline MaybeOrValue<Value> Function::Call(
  2101. napi_value recv, const std::initializer_list<napi_value>& args) const {
  2102. return Call(recv, args.size(), args.begin());
  2103. }
  2104. inline MaybeOrValue<Value> Function::Call(
  2105. napi_value recv, const std::vector<napi_value>& args) const {
  2106. return Call(recv, args.size(), args.data());
  2107. }
  2108. inline MaybeOrValue<Value> Function::Call(
  2109. napi_value recv, const std::vector<Value>& args) const {
  2110. const size_t argc = args.size();
  2111. const size_t stackArgsCount = 6;
  2112. napi_value stackArgs[stackArgsCount];
  2113. std::vector<napi_value> heapArgs;
  2114. napi_value* argv;
  2115. if (argc <= stackArgsCount) {
  2116. argv = stackArgs;
  2117. } else {
  2118. heapArgs.resize(argc);
  2119. argv = heapArgs.data();
  2120. }
  2121. for (size_t index = 0; index < argc; index++) {
  2122. argv[index] = static_cast<napi_value>(args[index]);
  2123. }
  2124. return Call(recv, argc, argv);
  2125. }
  2126. inline MaybeOrValue<Value> Function::Call(napi_value recv,
  2127. size_t argc,
  2128. const napi_value* args) const {
  2129. napi_value result;
  2130. napi_status status =
  2131. napi_call_function(_env, recv, _value, argc, args, &result);
  2132. NAPI_RETURN_OR_THROW_IF_FAILED(
  2133. _env, status, Napi::Value(_env, result), Napi::Value);
  2134. }
  2135. inline MaybeOrValue<Value> Function::MakeCallback(
  2136. napi_value recv,
  2137. const std::initializer_list<napi_value>& args,
  2138. napi_async_context context) const {
  2139. return MakeCallback(recv, args.size(), args.begin(), context);
  2140. }
  2141. inline MaybeOrValue<Value> Function::MakeCallback(
  2142. napi_value recv,
  2143. const std::vector<napi_value>& args,
  2144. napi_async_context context) const {
  2145. return MakeCallback(recv, args.size(), args.data(), context);
  2146. }
  2147. inline MaybeOrValue<Value> Function::MakeCallback(
  2148. napi_value recv,
  2149. size_t argc,
  2150. const napi_value* args,
  2151. napi_async_context context) const {
  2152. napi_value result;
  2153. napi_status status =
  2154. napi_make_callback(_env, context, recv, _value, argc, args, &result);
  2155. NAPI_RETURN_OR_THROW_IF_FAILED(
  2156. _env, status, Napi::Value(_env, result), Napi::Value);
  2157. }
  2158. inline MaybeOrValue<Object> Function::New(
  2159. const std::initializer_list<napi_value>& args) const {
  2160. return New(args.size(), args.begin());
  2161. }
  2162. inline MaybeOrValue<Object> Function::New(
  2163. const std::vector<napi_value>& args) const {
  2164. return New(args.size(), args.data());
  2165. }
  2166. inline MaybeOrValue<Object> Function::New(size_t argc,
  2167. const napi_value* args) const {
  2168. napi_value result;
  2169. napi_status status = napi_new_instance(_env, _value, argc, args, &result);
  2170. NAPI_RETURN_OR_THROW_IF_FAILED(
  2171. _env, status, Napi::Object(_env, result), Napi::Object);
  2172. }
  2173. ////////////////////////////////////////////////////////////////////////////////
  2174. // Promise class
  2175. ////////////////////////////////////////////////////////////////////////////////
  2176. inline Promise::Deferred Promise::Deferred::New(napi_env env) {
  2177. return Promise::Deferred(env);
  2178. }
  2179. inline Promise::Deferred::Deferred(napi_env env) : _env(env) {
  2180. napi_status status = napi_create_promise(_env, &_deferred, &_promise);
  2181. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2182. }
  2183. inline Promise Promise::Deferred::Promise() const {
  2184. return Napi::Promise(_env, _promise);
  2185. }
  2186. inline Napi::Env Promise::Deferred::Env() const {
  2187. return Napi::Env(_env);
  2188. }
  2189. inline void Promise::Deferred::Resolve(napi_value value) const {
  2190. napi_status status = napi_resolve_deferred(_env, _deferred, value);
  2191. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2192. }
  2193. inline void Promise::Deferred::Reject(napi_value value) const {
  2194. napi_status status = napi_reject_deferred(_env, _deferred, value);
  2195. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2196. }
  2197. inline void Promise::CheckCast(napi_env env, napi_value value) {
  2198. NAPI_CHECK(value != nullptr, "Promise::CheckCast", "empty value");
  2199. bool result;
  2200. napi_status status = napi_is_promise(env, value, &result);
  2201. NAPI_CHECK(status == napi_ok, "Promise::CheckCast", "napi_is_promise failed");
  2202. NAPI_CHECK(result, "Promise::CheckCast", "value is not promise");
  2203. }
  2204. inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) {}
  2205. ////////////////////////////////////////////////////////////////////////////////
  2206. // Buffer<T> class
  2207. ////////////////////////////////////////////////////////////////////////////////
  2208. template <typename T>
  2209. inline Buffer<T> Buffer<T>::New(napi_env env, size_t length) {
  2210. napi_value value;
  2211. void* data;
  2212. napi_status status =
  2213. napi_create_buffer(env, length * sizeof(T), &data, &value);
  2214. NAPI_THROW_IF_FAILED(env, status, Buffer<T>());
  2215. return Buffer(env, value, length, static_cast<T*>(data));
  2216. }
  2217. #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  2218. template <typename T>
  2219. inline Buffer<T> Buffer<T>::New(napi_env env, T* data, size_t length) {
  2220. napi_value value;
  2221. napi_status status = napi_create_external_buffer(
  2222. env, length * sizeof(T), data, nullptr, nullptr, &value);
  2223. NAPI_THROW_IF_FAILED(env, status, Buffer<T>());
  2224. return Buffer(env, value, length, data);
  2225. }
  2226. template <typename T>
  2227. template <typename Finalizer>
  2228. inline Buffer<T> Buffer<T>::New(napi_env env,
  2229. T* data,
  2230. size_t length,
  2231. Finalizer finalizeCallback) {
  2232. napi_value value;
  2233. details::FinalizeData<T, Finalizer>* finalizeData =
  2234. new details::FinalizeData<T, Finalizer>(
  2235. {std::move(finalizeCallback), nullptr});
  2236. napi_status status =
  2237. napi_create_external_buffer(env,
  2238. length * sizeof(T),
  2239. data,
  2240. details::FinalizeData<T, Finalizer>::Wrapper,
  2241. finalizeData,
  2242. &value);
  2243. if (status != napi_ok) {
  2244. delete finalizeData;
  2245. NAPI_THROW_IF_FAILED(env, status, Buffer());
  2246. }
  2247. return Buffer(env, value, length, data);
  2248. }
  2249. template <typename T>
  2250. template <typename Finalizer, typename Hint>
  2251. inline Buffer<T> Buffer<T>::New(napi_env env,
  2252. T* data,
  2253. size_t length,
  2254. Finalizer finalizeCallback,
  2255. Hint* finalizeHint) {
  2256. napi_value value;
  2257. details::FinalizeData<T, Finalizer, Hint>* finalizeData =
  2258. new details::FinalizeData<T, Finalizer, Hint>(
  2259. {std::move(finalizeCallback), finalizeHint});
  2260. napi_status status = napi_create_external_buffer(
  2261. env,
  2262. length * sizeof(T),
  2263. data,
  2264. details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint,
  2265. finalizeData,
  2266. &value);
  2267. if (status != napi_ok) {
  2268. delete finalizeData;
  2269. NAPI_THROW_IF_FAILED(env, status, Buffer());
  2270. }
  2271. return Buffer(env, value, length, data);
  2272. }
  2273. #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  2274. template <typename T>
  2275. inline Buffer<T> Buffer<T>::NewOrCopy(napi_env env, T* data, size_t length) {
  2276. #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  2277. napi_value value;
  2278. napi_status status = napi_create_external_buffer(
  2279. env, length * sizeof(T), data, nullptr, nullptr, &value);
  2280. if (status == details::napi_no_external_buffers_allowed) {
  2281. #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  2282. // If we can't create an external buffer, we'll just copy the data.
  2283. return Buffer<T>::Copy(env, data, length);
  2284. #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  2285. }
  2286. NAPI_THROW_IF_FAILED(env, status, Buffer<T>());
  2287. return Buffer(env, value, length, data);
  2288. #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  2289. }
  2290. template <typename T>
  2291. template <typename Finalizer>
  2292. inline Buffer<T> Buffer<T>::NewOrCopy(napi_env env,
  2293. T* data,
  2294. size_t length,
  2295. Finalizer finalizeCallback) {
  2296. details::FinalizeData<T, Finalizer>* finalizeData =
  2297. new details::FinalizeData<T, Finalizer>(
  2298. {std::move(finalizeCallback), nullptr});
  2299. #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  2300. napi_value value;
  2301. napi_status status =
  2302. napi_create_external_buffer(env,
  2303. length * sizeof(T),
  2304. data,
  2305. details::FinalizeData<T, Finalizer>::Wrapper,
  2306. finalizeData,
  2307. &value);
  2308. if (status == details::napi_no_external_buffers_allowed) {
  2309. #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  2310. // If we can't create an external buffer, we'll just copy the data.
  2311. Buffer<T> ret = Buffer<T>::Copy(env, data, length);
  2312. details::FinalizeData<T, Finalizer>::Wrapper(env, data, finalizeData);
  2313. return ret;
  2314. #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  2315. }
  2316. if (status != napi_ok) {
  2317. delete finalizeData;
  2318. NAPI_THROW_IF_FAILED(env, status, Buffer());
  2319. }
  2320. return Buffer(env, value, length, data);
  2321. #endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  2322. }
  2323. template <typename T>
  2324. template <typename Finalizer, typename Hint>
  2325. inline Buffer<T> Buffer<T>::NewOrCopy(napi_env env,
  2326. T* data,
  2327. size_t length,
  2328. Finalizer finalizeCallback,
  2329. Hint* finalizeHint) {
  2330. details::FinalizeData<T, Finalizer, Hint>* finalizeData =
  2331. new details::FinalizeData<T, Finalizer, Hint>(
  2332. {std::move(finalizeCallback), finalizeHint});
  2333. #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  2334. napi_value value;
  2335. napi_status status = napi_create_external_buffer(
  2336. env,
  2337. length * sizeof(T),
  2338. data,
  2339. details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint,
  2340. finalizeData,
  2341. &value);
  2342. if (status == details::napi_no_external_buffers_allowed) {
  2343. #endif
  2344. // If we can't create an external buffer, we'll just copy the data.
  2345. Buffer<T> ret = Buffer<T>::Copy(env, data, length);
  2346. details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint(
  2347. env, data, finalizeData);
  2348. return ret;
  2349. #ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED
  2350. }
  2351. if (status != napi_ok) {
  2352. delete finalizeData;
  2353. NAPI_THROW_IF_FAILED(env, status, Buffer());
  2354. }
  2355. return Buffer(env, value, length, data);
  2356. #endif
  2357. }
  2358. template <typename T>
  2359. inline Buffer<T> Buffer<T>::Copy(napi_env env, const T* data, size_t length) {
  2360. napi_value value;
  2361. napi_status status =
  2362. napi_create_buffer_copy(env, length * sizeof(T), data, nullptr, &value);
  2363. NAPI_THROW_IF_FAILED(env, status, Buffer<T>());
  2364. return Buffer<T>(env, value);
  2365. }
  2366. template <typename T>
  2367. inline void Buffer<T>::CheckCast(napi_env env, napi_value value) {
  2368. NAPI_CHECK(value != nullptr, "Buffer::CheckCast", "empty value");
  2369. bool result;
  2370. napi_status status = napi_is_buffer(env, value, &result);
  2371. NAPI_CHECK(status == napi_ok, "Buffer::CheckCast", "napi_is_buffer failed");
  2372. NAPI_CHECK(result, "Buffer::CheckCast", "value is not buffer");
  2373. }
  2374. template <typename T>
  2375. inline Buffer<T>::Buffer() : Uint8Array(), _length(0), _data(nullptr) {}
  2376. template <typename T>
  2377. inline Buffer<T>::Buffer(napi_env env, napi_value value)
  2378. : Uint8Array(env, value), _length(0), _data(nullptr) {}
  2379. template <typename T>
  2380. inline Buffer<T>::Buffer(napi_env env, napi_value value, size_t length, T* data)
  2381. : Uint8Array(env, value), _length(length), _data(data) {}
  2382. template <typename T>
  2383. inline size_t Buffer<T>::Length() const {
  2384. EnsureInfo();
  2385. return _length;
  2386. }
  2387. template <typename T>
  2388. inline T* Buffer<T>::Data() const {
  2389. EnsureInfo();
  2390. return _data;
  2391. }
  2392. template <typename T>
  2393. inline void Buffer<T>::EnsureInfo() const {
  2394. // The Buffer instance may have been constructed from a napi_value whose
  2395. // length/data are not yet known. Fetch and cache these values just once,
  2396. // since they can never change during the lifetime of the Buffer.
  2397. if (_data == nullptr) {
  2398. size_t byteLength;
  2399. void* voidData;
  2400. napi_status status =
  2401. napi_get_buffer_info(_env, _value, &voidData, &byteLength);
  2402. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2403. _length = byteLength / sizeof(T);
  2404. _data = static_cast<T*>(voidData);
  2405. }
  2406. }
  2407. ////////////////////////////////////////////////////////////////////////////////
  2408. // Error class
  2409. ////////////////////////////////////////////////////////////////////////////////
  2410. inline Error Error::New(napi_env env) {
  2411. napi_status status;
  2412. napi_value error = nullptr;
  2413. bool is_exception_pending;
  2414. napi_extended_error_info last_error_info_copy;
  2415. {
  2416. // We must retrieve the last error info before doing anything else because
  2417. // doing anything else will replace the last error info.
  2418. const napi_extended_error_info* last_error_info;
  2419. status = napi_get_last_error_info(env, &last_error_info);
  2420. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_last_error_info");
  2421. // All fields of the `napi_extended_error_info` structure gets reset in
  2422. // subsequent Node-API function calls on the same `env`. This includes a
  2423. // call to `napi_is_exception_pending()`. So here it is necessary to make a
  2424. // copy of the information as the `error_code` field is used later on.
  2425. memcpy(&last_error_info_copy,
  2426. last_error_info,
  2427. sizeof(napi_extended_error_info));
  2428. }
  2429. status = napi_is_exception_pending(env, &is_exception_pending);
  2430. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_is_exception_pending");
  2431. // A pending exception takes precedence over any internal error status.
  2432. if (is_exception_pending) {
  2433. status = napi_get_and_clear_last_exception(env, &error);
  2434. NAPI_FATAL_IF_FAILED(
  2435. status, "Error::New", "napi_get_and_clear_last_exception");
  2436. } else {
  2437. const char* error_message = last_error_info_copy.error_message != nullptr
  2438. ? last_error_info_copy.error_message
  2439. : "Error in native callback";
  2440. napi_value message;
  2441. status = napi_create_string_utf8(
  2442. env, error_message, std::strlen(error_message), &message);
  2443. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_string_utf8");
  2444. switch (last_error_info_copy.error_code) {
  2445. case napi_object_expected:
  2446. case napi_string_expected:
  2447. case napi_boolean_expected:
  2448. case napi_number_expected:
  2449. status = napi_create_type_error(env, nullptr, message, &error);
  2450. break;
  2451. default:
  2452. status = napi_create_error(env, nullptr, message, &error);
  2453. break;
  2454. }
  2455. NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_error");
  2456. }
  2457. return Error(env, error);
  2458. }
  2459. inline Error Error::New(napi_env env, const char* message) {
  2460. return Error::New<Error>(
  2461. env, message, std::strlen(message), napi_create_error);
  2462. }
  2463. inline Error Error::New(napi_env env, const std::string& message) {
  2464. return Error::New<Error>(
  2465. env, message.c_str(), message.size(), napi_create_error);
  2466. }
  2467. inline NAPI_NO_RETURN void Error::Fatal(const char* location,
  2468. const char* message) {
  2469. napi_fatal_error(location, NAPI_AUTO_LENGTH, message, NAPI_AUTO_LENGTH);
  2470. }
  2471. inline Error::Error() : ObjectReference() {}
  2472. inline Error::Error(napi_env env, napi_value value)
  2473. : ObjectReference(env, nullptr) {
  2474. if (value != nullptr) {
  2475. // Attempting to create a reference on the error object.
  2476. // If it's not a Object/Function/Symbol, this call will return an error
  2477. // status.
  2478. napi_status status = napi_create_reference(env, value, 1, &_ref);
  2479. if (status != napi_ok) {
  2480. napi_value wrappedErrorObj;
  2481. // Create an error object
  2482. status = napi_create_object(env, &wrappedErrorObj);
  2483. NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_object");
  2484. // property flag that we attach to show the error object is wrapped
  2485. napi_property_descriptor wrapObjFlag = {
  2486. ERROR_WRAP_VALUE(), // Unique GUID identifier since Symbol isn't a
  2487. // viable option
  2488. nullptr,
  2489. nullptr,
  2490. nullptr,
  2491. nullptr,
  2492. Value::From(env, value),
  2493. napi_enumerable,
  2494. nullptr};
  2495. status = napi_define_properties(env, wrappedErrorObj, 1, &wrapObjFlag);
  2496. NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_define_properties");
  2497. // Create a reference on the newly wrapped object
  2498. status = napi_create_reference(env, wrappedErrorObj, 1, &_ref);
  2499. }
  2500. // Avoid infinite recursion in the failure case.
  2501. NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_reference");
  2502. }
  2503. }
  2504. inline Object Error::Value() const {
  2505. if (_ref == nullptr) {
  2506. return Object(_env, nullptr);
  2507. }
  2508. napi_value refValue;
  2509. napi_status status = napi_get_reference_value(_env, _ref, &refValue);
  2510. NAPI_THROW_IF_FAILED(_env, status, Object());
  2511. napi_valuetype type;
  2512. status = napi_typeof(_env, refValue, &type);
  2513. NAPI_THROW_IF_FAILED(_env, status, Object());
  2514. // If refValue isn't a symbol, then we proceed to whether the refValue has the
  2515. // wrapped error flag
  2516. if (type != napi_symbol) {
  2517. // We are checking if the object is wrapped
  2518. bool isWrappedObject = false;
  2519. status = napi_has_property(_env,
  2520. refValue,
  2521. String::From(_env, ERROR_WRAP_VALUE()),
  2522. &isWrappedObject);
  2523. // Don't care about status
  2524. if (isWrappedObject) {
  2525. napi_value unwrappedValue;
  2526. status = napi_get_property(_env,
  2527. refValue,
  2528. String::From(_env, ERROR_WRAP_VALUE()),
  2529. &unwrappedValue);
  2530. NAPI_THROW_IF_FAILED(_env, status, Object());
  2531. return Object(_env, unwrappedValue);
  2532. }
  2533. }
  2534. return Object(_env, refValue);
  2535. }
  2536. inline Error::Error(Error&& other) : ObjectReference(std::move(other)) {}
  2537. inline Error& Error::operator=(Error&& other) {
  2538. static_cast<Reference<Object>*>(this)->operator=(std::move(other));
  2539. return *this;
  2540. }
  2541. inline Error::Error(const Error& other) : ObjectReference(other) {}
  2542. inline Error& Error::operator=(const Error& other) {
  2543. Reset();
  2544. _env = other.Env();
  2545. HandleScope scope(_env);
  2546. napi_value value = other.Value();
  2547. if (value != nullptr) {
  2548. napi_status status = napi_create_reference(_env, value, 1, &_ref);
  2549. NAPI_THROW_IF_FAILED(_env, status, *this);
  2550. }
  2551. return *this;
  2552. }
  2553. inline const std::string& Error::Message() const NAPI_NOEXCEPT {
  2554. if (_message.size() == 0 && _env != nullptr) {
  2555. #ifdef NAPI_CPP_EXCEPTIONS
  2556. try {
  2557. _message = Get("message").As<String>();
  2558. } catch (...) {
  2559. // Catch all errors here, to include e.g. a std::bad_alloc from
  2560. // the std::string::operator=, because this method may not throw.
  2561. }
  2562. #else // NAPI_CPP_EXCEPTIONS
  2563. #if defined(NODE_ADDON_API_ENABLE_MAYBE)
  2564. Napi::Value message_val;
  2565. if (Get("message").UnwrapTo(&message_val)) {
  2566. _message = message_val.As<String>();
  2567. }
  2568. #else
  2569. _message = Get("message").As<String>();
  2570. #endif
  2571. #endif // NAPI_CPP_EXCEPTIONS
  2572. }
  2573. return _message;
  2574. }
  2575. // we created an object on the &_ref
  2576. inline void Error::ThrowAsJavaScriptException() const {
  2577. HandleScope scope(_env);
  2578. if (!IsEmpty()) {
  2579. #ifdef NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS
  2580. bool pendingException = false;
  2581. // check if there is already a pending exception. If so don't try to throw a
  2582. // new one as that is not allowed/possible
  2583. napi_status status = napi_is_exception_pending(_env, &pendingException);
  2584. if ((status != napi_ok) ||
  2585. ((status == napi_ok) && (pendingException == false))) {
  2586. // We intentionally don't use `NAPI_THROW_*` macros here to ensure
  2587. // that there is no possible recursion as `ThrowAsJavaScriptException`
  2588. // is part of `NAPI_THROW_*` macro definition for noexcept.
  2589. status = napi_throw(_env, Value());
  2590. if (status == napi_pending_exception) {
  2591. // The environment must be terminating as we checked earlier and there
  2592. // was no pending exception. In this case continuing will result
  2593. // in a fatal error and there is nothing the author has done incorrectly
  2594. // in their code that is worth flagging through a fatal error
  2595. return;
  2596. }
  2597. } else {
  2598. status = napi_pending_exception;
  2599. }
  2600. #else
  2601. // We intentionally don't use `NAPI_THROW_*` macros here to ensure
  2602. // that there is no possible recursion as `ThrowAsJavaScriptException`
  2603. // is part of `NAPI_THROW_*` macro definition for noexcept.
  2604. napi_status status = napi_throw(_env, Value());
  2605. #endif
  2606. #ifdef NAPI_CPP_EXCEPTIONS
  2607. if (status != napi_ok) {
  2608. throw Error::New(_env);
  2609. }
  2610. #else // NAPI_CPP_EXCEPTIONS
  2611. NAPI_FATAL_IF_FAILED(
  2612. status, "Error::ThrowAsJavaScriptException", "napi_throw");
  2613. #endif // NAPI_CPP_EXCEPTIONS
  2614. }
  2615. }
  2616. #ifdef NAPI_CPP_EXCEPTIONS
  2617. inline const char* Error::what() const NAPI_NOEXCEPT {
  2618. return Message().c_str();
  2619. }
  2620. #endif // NAPI_CPP_EXCEPTIONS
  2621. inline const char* Error::ERROR_WRAP_VALUE() NAPI_NOEXCEPT {
  2622. return "4bda9e7e-4913-4dbc-95de-891cbf66598e-errorVal";
  2623. }
  2624. template <typename TError>
  2625. inline TError Error::New(napi_env env,
  2626. const char* message,
  2627. size_t length,
  2628. create_error_fn create_error) {
  2629. napi_value str;
  2630. napi_status status = napi_create_string_utf8(env, message, length, &str);
  2631. NAPI_THROW_IF_FAILED(env, status, TError());
  2632. napi_value error;
  2633. status = create_error(env, nullptr, str, &error);
  2634. NAPI_THROW_IF_FAILED(env, status, TError());
  2635. return TError(env, error);
  2636. }
  2637. inline TypeError TypeError::New(napi_env env, const char* message) {
  2638. return Error::New<TypeError>(
  2639. env, message, std::strlen(message), napi_create_type_error);
  2640. }
  2641. inline TypeError TypeError::New(napi_env env, const std::string& message) {
  2642. return Error::New<TypeError>(
  2643. env, message.c_str(), message.size(), napi_create_type_error);
  2644. }
  2645. inline TypeError::TypeError() : Error() {}
  2646. inline TypeError::TypeError(napi_env env, napi_value value)
  2647. : Error(env, value) {}
  2648. inline RangeError RangeError::New(napi_env env, const char* message) {
  2649. return Error::New<RangeError>(
  2650. env, message, std::strlen(message), napi_create_range_error);
  2651. }
  2652. inline RangeError RangeError::New(napi_env env, const std::string& message) {
  2653. return Error::New<RangeError>(
  2654. env, message.c_str(), message.size(), napi_create_range_error);
  2655. }
  2656. inline RangeError::RangeError() : Error() {}
  2657. inline RangeError::RangeError(napi_env env, napi_value value)
  2658. : Error(env, value) {}
  2659. ////////////////////////////////////////////////////////////////////////////////
  2660. // Reference<T> class
  2661. ////////////////////////////////////////////////////////////////////////////////
  2662. template <typename T>
  2663. inline Reference<T> Reference<T>::New(const T& value,
  2664. uint32_t initialRefcount) {
  2665. napi_env env = value.Env();
  2666. napi_value val = value;
  2667. if (val == nullptr) {
  2668. return Reference<T>(env, nullptr);
  2669. }
  2670. napi_ref ref;
  2671. napi_status status = napi_create_reference(env, value, initialRefcount, &ref);
  2672. NAPI_THROW_IF_FAILED(env, status, Reference<T>());
  2673. return Reference<T>(env, ref);
  2674. }
  2675. template <typename T>
  2676. inline Reference<T>::Reference()
  2677. : _env(nullptr), _ref(nullptr), _suppressDestruct(false) {}
  2678. template <typename T>
  2679. inline Reference<T>::Reference(napi_env env, napi_ref ref)
  2680. : _env(env), _ref(ref), _suppressDestruct(false) {}
  2681. template <typename T>
  2682. inline Reference<T>::~Reference() {
  2683. if (_ref != nullptr) {
  2684. if (!_suppressDestruct) {
  2685. napi_delete_reference(_env, _ref);
  2686. }
  2687. _ref = nullptr;
  2688. }
  2689. }
  2690. template <typename T>
  2691. inline Reference<T>::Reference(Reference<T>&& other)
  2692. : _env(other._env),
  2693. _ref(other._ref),
  2694. _suppressDestruct(other._suppressDestruct) {
  2695. other._env = nullptr;
  2696. other._ref = nullptr;
  2697. other._suppressDestruct = false;
  2698. }
  2699. template <typename T>
  2700. inline Reference<T>& Reference<T>::operator=(Reference<T>&& other) {
  2701. Reset();
  2702. _env = other._env;
  2703. _ref = other._ref;
  2704. _suppressDestruct = other._suppressDestruct;
  2705. other._env = nullptr;
  2706. other._ref = nullptr;
  2707. other._suppressDestruct = false;
  2708. return *this;
  2709. }
  2710. template <typename T>
  2711. inline Reference<T>::Reference(const Reference<T>& other)
  2712. : _env(other._env), _ref(nullptr), _suppressDestruct(false) {
  2713. HandleScope scope(_env);
  2714. napi_value value = other.Value();
  2715. if (value != nullptr) {
  2716. // Copying is a limited scenario (currently only used for Error object) and
  2717. // always creates a strong reference to the given value even if the incoming
  2718. // reference is weak.
  2719. napi_status status = napi_create_reference(_env, value, 1, &_ref);
  2720. NAPI_FATAL_IF_FAILED(
  2721. status, "Reference<T>::Reference", "napi_create_reference");
  2722. }
  2723. }
  2724. template <typename T>
  2725. inline Reference<T>::operator napi_ref() const {
  2726. return _ref;
  2727. }
  2728. template <typename T>
  2729. inline bool Reference<T>::operator==(const Reference<T>& other) const {
  2730. HandleScope scope(_env);
  2731. return this->Value().StrictEquals(other.Value());
  2732. }
  2733. template <typename T>
  2734. inline bool Reference<T>::operator!=(const Reference<T>& other) const {
  2735. return !this->operator==(other);
  2736. }
  2737. template <typename T>
  2738. inline Napi::Env Reference<T>::Env() const {
  2739. return Napi::Env(_env);
  2740. }
  2741. template <typename T>
  2742. inline bool Reference<T>::IsEmpty() const {
  2743. return _ref == nullptr;
  2744. }
  2745. template <typename T>
  2746. inline T Reference<T>::Value() const {
  2747. if (_ref == nullptr) {
  2748. return T(_env, nullptr);
  2749. }
  2750. napi_value value;
  2751. napi_status status = napi_get_reference_value(_env, _ref, &value);
  2752. NAPI_THROW_IF_FAILED(_env, status, T());
  2753. return T(_env, value);
  2754. }
  2755. template <typename T>
  2756. inline uint32_t Reference<T>::Ref() const {
  2757. uint32_t result;
  2758. napi_status status = napi_reference_ref(_env, _ref, &result);
  2759. NAPI_THROW_IF_FAILED(_env, status, 0);
  2760. return result;
  2761. }
  2762. template <typename T>
  2763. inline uint32_t Reference<T>::Unref() const {
  2764. uint32_t result;
  2765. napi_status status = napi_reference_unref(_env, _ref, &result);
  2766. NAPI_THROW_IF_FAILED(_env, status, 0);
  2767. return result;
  2768. }
  2769. template <typename T>
  2770. inline void Reference<T>::Reset() {
  2771. if (_ref != nullptr) {
  2772. napi_status status = napi_delete_reference(_env, _ref);
  2773. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2774. _ref = nullptr;
  2775. }
  2776. }
  2777. template <typename T>
  2778. inline void Reference<T>::Reset(const T& value, uint32_t refcount) {
  2779. Reset();
  2780. _env = value.Env();
  2781. napi_value val = value;
  2782. if (val != nullptr) {
  2783. napi_status status = napi_create_reference(_env, value, refcount, &_ref);
  2784. NAPI_THROW_IF_FAILED_VOID(_env, status);
  2785. }
  2786. }
  2787. template <typename T>
  2788. inline void Reference<T>::SuppressDestruct() {
  2789. _suppressDestruct = true;
  2790. }
  2791. template <typename T>
  2792. inline Reference<T> Weak(T value) {
  2793. return Reference<T>::New(value, 0);
  2794. }
  2795. inline ObjectReference Weak(Object value) {
  2796. return Reference<Object>::New(value, 0);
  2797. }
  2798. inline FunctionReference Weak(Function value) {
  2799. return Reference<Function>::New(value, 0);
  2800. }
  2801. template <typename T>
  2802. inline Reference<T> Persistent(T value) {
  2803. return Reference<T>::New(value, 1);
  2804. }
  2805. inline ObjectReference Persistent(Object value) {
  2806. return Reference<Object>::New(value, 1);
  2807. }
  2808. inline FunctionReference Persistent(Function value) {
  2809. return Reference<Function>::New(value, 1);
  2810. }
  2811. ////////////////////////////////////////////////////////////////////////////////
  2812. // ObjectReference class
  2813. ////////////////////////////////////////////////////////////////////////////////
  2814. inline ObjectReference::ObjectReference() : Reference<Object>() {}
  2815. inline ObjectReference::ObjectReference(napi_env env, napi_ref ref)
  2816. : Reference<Object>(env, ref) {}
  2817. inline ObjectReference::ObjectReference(Reference<Object>&& other)
  2818. : Reference<Object>(std::move(other)) {}
  2819. inline ObjectReference& ObjectReference::operator=(Reference<Object>&& other) {
  2820. static_cast<Reference<Object>*>(this)->operator=(std::move(other));
  2821. return *this;
  2822. }
  2823. inline ObjectReference::ObjectReference(ObjectReference&& other)
  2824. : Reference<Object>(std::move(other)) {}
  2825. inline ObjectReference& ObjectReference::operator=(ObjectReference&& other) {
  2826. static_cast<Reference<Object>*>(this)->operator=(std::move(other));
  2827. return *this;
  2828. }
  2829. inline ObjectReference::ObjectReference(const ObjectReference& other)
  2830. : Reference<Object>(other) {}
  2831. inline MaybeOrValue<Napi::Value> ObjectReference::Get(
  2832. const char* utf8name) const {
  2833. EscapableHandleScope scope(_env);
  2834. MaybeOrValue<Napi::Value> result = Value().Get(utf8name);
  2835. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2836. if (result.IsJust()) {
  2837. return Just(scope.Escape(result.Unwrap()));
  2838. }
  2839. return result;
  2840. #else
  2841. if (scope.Env().IsExceptionPending()) {
  2842. return Value();
  2843. }
  2844. return scope.Escape(result);
  2845. #endif
  2846. }
  2847. inline MaybeOrValue<Napi::Value> ObjectReference::Get(
  2848. const std::string& utf8name) const {
  2849. EscapableHandleScope scope(_env);
  2850. MaybeOrValue<Napi::Value> result = Value().Get(utf8name);
  2851. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2852. if (result.IsJust()) {
  2853. return Just(scope.Escape(result.Unwrap()));
  2854. }
  2855. return result;
  2856. #else
  2857. if (scope.Env().IsExceptionPending()) {
  2858. return Value();
  2859. }
  2860. return scope.Escape(result);
  2861. #endif
  2862. }
  2863. inline MaybeOrValue<bool> ObjectReference::Set(const char* utf8name,
  2864. napi_value value) const {
  2865. HandleScope scope(_env);
  2866. return Value().Set(utf8name, value);
  2867. }
  2868. inline MaybeOrValue<bool> ObjectReference::Set(const char* utf8name,
  2869. Napi::Value value) const {
  2870. HandleScope scope(_env);
  2871. return Value().Set(utf8name, value);
  2872. }
  2873. inline MaybeOrValue<bool> ObjectReference::Set(const char* utf8name,
  2874. const char* utf8value) const {
  2875. HandleScope scope(_env);
  2876. return Value().Set(utf8name, utf8value);
  2877. }
  2878. inline MaybeOrValue<bool> ObjectReference::Set(const char* utf8name,
  2879. bool boolValue) const {
  2880. HandleScope scope(_env);
  2881. return Value().Set(utf8name, boolValue);
  2882. }
  2883. inline MaybeOrValue<bool> ObjectReference::Set(const char* utf8name,
  2884. double numberValue) const {
  2885. HandleScope scope(_env);
  2886. return Value().Set(utf8name, numberValue);
  2887. }
  2888. inline MaybeOrValue<bool> ObjectReference::Set(const std::string& utf8name,
  2889. napi_value value) const {
  2890. HandleScope scope(_env);
  2891. return Value().Set(utf8name, value);
  2892. }
  2893. inline MaybeOrValue<bool> ObjectReference::Set(const std::string& utf8name,
  2894. Napi::Value value) const {
  2895. HandleScope scope(_env);
  2896. return Value().Set(utf8name, value);
  2897. }
  2898. inline MaybeOrValue<bool> ObjectReference::Set(const std::string& utf8name,
  2899. std::string& utf8value) const {
  2900. HandleScope scope(_env);
  2901. return Value().Set(utf8name, utf8value);
  2902. }
  2903. inline MaybeOrValue<bool> ObjectReference::Set(const std::string& utf8name,
  2904. bool boolValue) const {
  2905. HandleScope scope(_env);
  2906. return Value().Set(utf8name, boolValue);
  2907. }
  2908. inline MaybeOrValue<bool> ObjectReference::Set(const std::string& utf8name,
  2909. double numberValue) const {
  2910. HandleScope scope(_env);
  2911. return Value().Set(utf8name, numberValue);
  2912. }
  2913. inline MaybeOrValue<Napi::Value> ObjectReference::Get(uint32_t index) const {
  2914. EscapableHandleScope scope(_env);
  2915. MaybeOrValue<Napi::Value> result = Value().Get(index);
  2916. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2917. if (result.IsJust()) {
  2918. return Just(scope.Escape(result.Unwrap()));
  2919. }
  2920. return result;
  2921. #else
  2922. if (scope.Env().IsExceptionPending()) {
  2923. return Value();
  2924. }
  2925. return scope.Escape(result);
  2926. #endif
  2927. }
  2928. inline MaybeOrValue<bool> ObjectReference::Set(uint32_t index,
  2929. napi_value value) const {
  2930. HandleScope scope(_env);
  2931. return Value().Set(index, value);
  2932. }
  2933. inline MaybeOrValue<bool> ObjectReference::Set(uint32_t index,
  2934. Napi::Value value) const {
  2935. HandleScope scope(_env);
  2936. return Value().Set(index, value);
  2937. }
  2938. inline MaybeOrValue<bool> ObjectReference::Set(uint32_t index,
  2939. const char* utf8value) const {
  2940. HandleScope scope(_env);
  2941. return Value().Set(index, utf8value);
  2942. }
  2943. inline MaybeOrValue<bool> ObjectReference::Set(
  2944. uint32_t index, const std::string& utf8value) const {
  2945. HandleScope scope(_env);
  2946. return Value().Set(index, utf8value);
  2947. }
  2948. inline MaybeOrValue<bool> ObjectReference::Set(uint32_t index,
  2949. bool boolValue) const {
  2950. HandleScope scope(_env);
  2951. return Value().Set(index, boolValue);
  2952. }
  2953. inline MaybeOrValue<bool> ObjectReference::Set(uint32_t index,
  2954. double numberValue) const {
  2955. HandleScope scope(_env);
  2956. return Value().Set(index, numberValue);
  2957. }
  2958. ////////////////////////////////////////////////////////////////////////////////
  2959. // FunctionReference class
  2960. ////////////////////////////////////////////////////////////////////////////////
  2961. inline FunctionReference::FunctionReference() : Reference<Function>() {}
  2962. inline FunctionReference::FunctionReference(napi_env env, napi_ref ref)
  2963. : Reference<Function>(env, ref) {}
  2964. inline FunctionReference::FunctionReference(Reference<Function>&& other)
  2965. : Reference<Function>(std::move(other)) {}
  2966. inline FunctionReference& FunctionReference::operator=(
  2967. Reference<Function>&& other) {
  2968. static_cast<Reference<Function>*>(this)->operator=(std::move(other));
  2969. return *this;
  2970. }
  2971. inline FunctionReference::FunctionReference(FunctionReference&& other)
  2972. : Reference<Function>(std::move(other)) {}
  2973. inline FunctionReference& FunctionReference::operator=(
  2974. FunctionReference&& other) {
  2975. static_cast<Reference<Function>*>(this)->operator=(std::move(other));
  2976. return *this;
  2977. }
  2978. inline MaybeOrValue<Napi::Value> FunctionReference::operator()(
  2979. const std::initializer_list<napi_value>& args) const {
  2980. EscapableHandleScope scope(_env);
  2981. MaybeOrValue<Napi::Value> result = Value()(args);
  2982. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2983. if (result.IsJust()) {
  2984. return Just(scope.Escape(result.Unwrap()));
  2985. }
  2986. return result;
  2987. #else
  2988. if (scope.Env().IsExceptionPending()) {
  2989. return Value();
  2990. }
  2991. return scope.Escape(result);
  2992. #endif
  2993. }
  2994. inline MaybeOrValue<Napi::Value> FunctionReference::Call(
  2995. const std::initializer_list<napi_value>& args) const {
  2996. EscapableHandleScope scope(_env);
  2997. MaybeOrValue<Napi::Value> result = Value().Call(args);
  2998. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  2999. if (result.IsJust()) {
  3000. return Just(scope.Escape(result.Unwrap()));
  3001. }
  3002. return result;
  3003. #else
  3004. if (scope.Env().IsExceptionPending()) {
  3005. return Value();
  3006. }
  3007. return scope.Escape(result);
  3008. #endif
  3009. }
  3010. inline MaybeOrValue<Napi::Value> FunctionReference::Call(
  3011. const std::vector<napi_value>& args) const {
  3012. EscapableHandleScope scope(_env);
  3013. MaybeOrValue<Napi::Value> result = Value().Call(args);
  3014. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  3015. if (result.IsJust()) {
  3016. return Just(scope.Escape(result.Unwrap()));
  3017. }
  3018. return result;
  3019. #else
  3020. if (scope.Env().IsExceptionPending()) {
  3021. return Value();
  3022. }
  3023. return scope.Escape(result);
  3024. #endif
  3025. }
  3026. inline MaybeOrValue<Napi::Value> FunctionReference::Call(
  3027. napi_value recv, const std::initializer_list<napi_value>& args) const {
  3028. EscapableHandleScope scope(_env);
  3029. MaybeOrValue<Napi::Value> result = Value().Call(recv, args);
  3030. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  3031. if (result.IsJust()) {
  3032. return Just(scope.Escape(result.Unwrap()));
  3033. }
  3034. return result;
  3035. #else
  3036. if (scope.Env().IsExceptionPending()) {
  3037. return Value();
  3038. }
  3039. return scope.Escape(result);
  3040. #endif
  3041. }
  3042. inline MaybeOrValue<Napi::Value> FunctionReference::Call(
  3043. napi_value recv, const std::vector<napi_value>& args) const {
  3044. EscapableHandleScope scope(_env);
  3045. MaybeOrValue<Napi::Value> result = Value().Call(recv, args);
  3046. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  3047. if (result.IsJust()) {
  3048. return Just(scope.Escape(result.Unwrap()));
  3049. }
  3050. return result;
  3051. #else
  3052. if (scope.Env().IsExceptionPending()) {
  3053. return Value();
  3054. }
  3055. return scope.Escape(result);
  3056. #endif
  3057. }
  3058. inline MaybeOrValue<Napi::Value> FunctionReference::Call(
  3059. napi_value recv, size_t argc, const napi_value* args) const {
  3060. EscapableHandleScope scope(_env);
  3061. MaybeOrValue<Napi::Value> result = Value().Call(recv, argc, args);
  3062. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  3063. if (result.IsJust()) {
  3064. return Just(scope.Escape(result.Unwrap()));
  3065. }
  3066. return result;
  3067. #else
  3068. if (scope.Env().IsExceptionPending()) {
  3069. return Value();
  3070. }
  3071. return scope.Escape(result);
  3072. #endif
  3073. }
  3074. inline MaybeOrValue<Napi::Value> FunctionReference::MakeCallback(
  3075. napi_value recv,
  3076. const std::initializer_list<napi_value>& args,
  3077. napi_async_context context) const {
  3078. EscapableHandleScope scope(_env);
  3079. MaybeOrValue<Napi::Value> result = Value().MakeCallback(recv, args, context);
  3080. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  3081. if (result.IsJust()) {
  3082. return Just(scope.Escape(result.Unwrap()));
  3083. }
  3084. return result;
  3085. #else
  3086. if (scope.Env().IsExceptionPending()) {
  3087. return Value();
  3088. }
  3089. return scope.Escape(result);
  3090. #endif
  3091. }
  3092. inline MaybeOrValue<Napi::Value> FunctionReference::MakeCallback(
  3093. napi_value recv,
  3094. const std::vector<napi_value>& args,
  3095. napi_async_context context) const {
  3096. EscapableHandleScope scope(_env);
  3097. MaybeOrValue<Napi::Value> result = Value().MakeCallback(recv, args, context);
  3098. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  3099. if (result.IsJust()) {
  3100. return Just(scope.Escape(result.Unwrap()));
  3101. }
  3102. return result;
  3103. #else
  3104. if (scope.Env().IsExceptionPending()) {
  3105. return Value();
  3106. }
  3107. return scope.Escape(result);
  3108. #endif
  3109. }
  3110. inline MaybeOrValue<Napi::Value> FunctionReference::MakeCallback(
  3111. napi_value recv,
  3112. size_t argc,
  3113. const napi_value* args,
  3114. napi_async_context context) const {
  3115. EscapableHandleScope scope(_env);
  3116. MaybeOrValue<Napi::Value> result =
  3117. Value().MakeCallback(recv, argc, args, context);
  3118. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  3119. if (result.IsJust()) {
  3120. return Just(scope.Escape(result.Unwrap()));
  3121. }
  3122. return result;
  3123. #else
  3124. if (scope.Env().IsExceptionPending()) {
  3125. return Value();
  3126. }
  3127. return scope.Escape(result);
  3128. #endif
  3129. }
  3130. inline MaybeOrValue<Object> FunctionReference::New(
  3131. const std::initializer_list<napi_value>& args) const {
  3132. EscapableHandleScope scope(_env);
  3133. MaybeOrValue<Object> result = Value().New(args);
  3134. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  3135. if (result.IsJust()) {
  3136. return Just(scope.Escape(result.Unwrap()).As<Object>());
  3137. }
  3138. return result;
  3139. #else
  3140. if (scope.Env().IsExceptionPending()) {
  3141. return Object();
  3142. }
  3143. return scope.Escape(result).As<Object>();
  3144. #endif
  3145. }
  3146. inline MaybeOrValue<Object> FunctionReference::New(
  3147. const std::vector<napi_value>& args) const {
  3148. EscapableHandleScope scope(_env);
  3149. MaybeOrValue<Object> result = Value().New(args);
  3150. #ifdef NODE_ADDON_API_ENABLE_MAYBE
  3151. if (result.IsJust()) {
  3152. return Just(scope.Escape(result.Unwrap()).As<Object>());
  3153. }
  3154. return result;
  3155. #else
  3156. if (scope.Env().IsExceptionPending()) {
  3157. return Object();
  3158. }
  3159. return scope.Escape(result).As<Object>();
  3160. #endif
  3161. }
  3162. ////////////////////////////////////////////////////////////////////////////////
  3163. // CallbackInfo class
  3164. ////////////////////////////////////////////////////////////////////////////////
  3165. inline CallbackInfo::CallbackInfo(napi_env env, napi_callback_info info)
  3166. : _env(env),
  3167. _info(info),
  3168. _this(nullptr),
  3169. _dynamicArgs(nullptr),
  3170. _data(nullptr) {
  3171. _argc = _staticArgCount;
  3172. _argv = _staticArgs;
  3173. napi_status status =
  3174. napi_get_cb_info(env, info, &_argc, _argv, &_this, &_data);
  3175. NAPI_THROW_IF_FAILED_VOID(_env, status);
  3176. if (_argc > _staticArgCount) {
  3177. // Use either a fixed-size array (on the stack) or a dynamically-allocated
  3178. // array (on the heap) depending on the number of args.
  3179. _dynamicArgs = new napi_value[_argc];
  3180. _argv = _dynamicArgs;
  3181. status = napi_get_cb_info(env, info, &_argc, _argv, nullptr, nullptr);
  3182. NAPI_THROW_IF_FAILED_VOID(_env, status);
  3183. }
  3184. }
  3185. inline CallbackInfo::~CallbackInfo() {
  3186. if (_dynamicArgs != nullptr) {
  3187. delete[] _dynamicArgs;
  3188. }
  3189. }
  3190. inline CallbackInfo::operator napi_callback_info() const {
  3191. return _info;
  3192. }
  3193. inline Value CallbackInfo::NewTarget() const {
  3194. napi_value newTarget;
  3195. napi_status status = napi_get_new_target(_env, _info, &newTarget);
  3196. NAPI_THROW_IF_FAILED(_env, status, Value());
  3197. return Value(_env, newTarget);
  3198. }
  3199. inline bool CallbackInfo::IsConstructCall() const {
  3200. return !NewTarget().IsEmpty();
  3201. }
  3202. inline Napi::Env CallbackInfo::Env() const {
  3203. return Napi::Env(_env);
  3204. }
  3205. inline size_t CallbackInfo::Length() const {
  3206. return _argc;
  3207. }
  3208. inline const Value CallbackInfo::operator[](size_t index) const {
  3209. return index < _argc ? Value(_env, _argv[index]) : Env().Undefined();
  3210. }
  3211. inline Value CallbackInfo::This() const {
  3212. if (_this == nullptr) {
  3213. return Env().Undefined();
  3214. }
  3215. return Object(_env, _this);
  3216. }
  3217. inline void* CallbackInfo::Data() const {
  3218. return _data;
  3219. }
  3220. inline void CallbackInfo::SetData(void* data) {
  3221. _data = data;
  3222. }
  3223. ////////////////////////////////////////////////////////////////////////////////
  3224. // PropertyDescriptor class
  3225. ////////////////////////////////////////////////////////////////////////////////
  3226. template <typename PropertyDescriptor::GetterCallback Getter>
  3227. PropertyDescriptor PropertyDescriptor::Accessor(
  3228. const char* utf8name, napi_property_attributes attributes, void* data) {
  3229. napi_property_descriptor desc = napi_property_descriptor();
  3230. desc.utf8name = utf8name;
  3231. desc.getter = details::TemplatedCallback<Getter>;
  3232. desc.attributes = attributes;
  3233. desc.data = data;
  3234. return desc;
  3235. }
  3236. template <typename PropertyDescriptor::GetterCallback Getter>
  3237. PropertyDescriptor PropertyDescriptor::Accessor(
  3238. const std::string& utf8name,
  3239. napi_property_attributes attributes,
  3240. void* data) {
  3241. return Accessor<Getter>(utf8name.c_str(), attributes, data);
  3242. }
  3243. template <typename PropertyDescriptor::GetterCallback Getter>
  3244. PropertyDescriptor PropertyDescriptor::Accessor(
  3245. Name name, napi_property_attributes attributes, void* data) {
  3246. napi_property_descriptor desc = napi_property_descriptor();
  3247. desc.name = name;
  3248. desc.getter = details::TemplatedCallback<Getter>;
  3249. desc.attributes = attributes;
  3250. desc.data = data;
  3251. return desc;
  3252. }
  3253. template <typename PropertyDescriptor::GetterCallback Getter,
  3254. typename PropertyDescriptor::SetterCallback Setter>
  3255. PropertyDescriptor PropertyDescriptor::Accessor(
  3256. const char* utf8name, napi_property_attributes attributes, void* data) {
  3257. napi_property_descriptor desc = napi_property_descriptor();
  3258. desc.utf8name = utf8name;
  3259. desc.getter = details::TemplatedCallback<Getter>;
  3260. desc.setter = details::TemplatedVoidCallback<Setter>;
  3261. desc.attributes = attributes;
  3262. desc.data = data;
  3263. return desc;
  3264. }
  3265. template <typename PropertyDescriptor::GetterCallback Getter,
  3266. typename PropertyDescriptor::SetterCallback Setter>
  3267. PropertyDescriptor PropertyDescriptor::Accessor(
  3268. const std::string& utf8name,
  3269. napi_property_attributes attributes,
  3270. void* data) {
  3271. return Accessor<Getter, Setter>(utf8name.c_str(), attributes, data);
  3272. }
  3273. template <typename PropertyDescriptor::GetterCallback Getter,
  3274. typename PropertyDescriptor::SetterCallback Setter>
  3275. PropertyDescriptor PropertyDescriptor::Accessor(
  3276. Name name, napi_property_attributes attributes, void* data) {
  3277. napi_property_descriptor desc = napi_property_descriptor();
  3278. desc.name = name;
  3279. desc.getter = details::TemplatedCallback<Getter>;
  3280. desc.setter = details::TemplatedVoidCallback<Setter>;
  3281. desc.attributes = attributes;
  3282. desc.data = data;
  3283. return desc;
  3284. }
  3285. template <typename Getter>
  3286. inline PropertyDescriptor PropertyDescriptor::Accessor(
  3287. Napi::Env env,
  3288. Napi::Object object,
  3289. const char* utf8name,
  3290. Getter getter,
  3291. napi_property_attributes attributes,
  3292. void* data) {
  3293. using CbData = details::CallbackData<Getter, Napi::Value>;
  3294. auto callbackData = new CbData({getter, data});
  3295. napi_status status = AttachData(env, object, callbackData);
  3296. if (status != napi_ok) {
  3297. delete callbackData;
  3298. NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  3299. }
  3300. return PropertyDescriptor({utf8name,
  3301. nullptr,
  3302. nullptr,
  3303. CbData::Wrapper,
  3304. nullptr,
  3305. nullptr,
  3306. attributes,
  3307. callbackData});
  3308. }
  3309. template <typename Getter>
  3310. inline PropertyDescriptor PropertyDescriptor::Accessor(
  3311. Napi::Env env,
  3312. Napi::Object object,
  3313. const std::string& utf8name,
  3314. Getter getter,
  3315. napi_property_attributes attributes,
  3316. void* data) {
  3317. return Accessor(env, object, utf8name.c_str(), getter, attributes, data);
  3318. }
  3319. template <typename Getter>
  3320. inline PropertyDescriptor PropertyDescriptor::Accessor(
  3321. Napi::Env env,
  3322. Napi::Object object,
  3323. Name name,
  3324. Getter getter,
  3325. napi_property_attributes attributes,
  3326. void* data) {
  3327. using CbData = details::CallbackData<Getter, Napi::Value>;
  3328. auto callbackData = new CbData({getter, data});
  3329. napi_status status = AttachData(env, object, callbackData);
  3330. if (status != napi_ok) {
  3331. delete callbackData;
  3332. NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  3333. }
  3334. return PropertyDescriptor({nullptr,
  3335. name,
  3336. nullptr,
  3337. CbData::Wrapper,
  3338. nullptr,
  3339. nullptr,
  3340. attributes,
  3341. callbackData});
  3342. }
  3343. template <typename Getter, typename Setter>
  3344. inline PropertyDescriptor PropertyDescriptor::Accessor(
  3345. Napi::Env env,
  3346. Napi::Object object,
  3347. const char* utf8name,
  3348. Getter getter,
  3349. Setter setter,
  3350. napi_property_attributes attributes,
  3351. void* data) {
  3352. using CbData = details::AccessorCallbackData<Getter, Setter>;
  3353. auto callbackData = new CbData({getter, setter, data});
  3354. napi_status status = AttachData(env, object, callbackData);
  3355. if (status != napi_ok) {
  3356. delete callbackData;
  3357. NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  3358. }
  3359. return PropertyDescriptor({utf8name,
  3360. nullptr,
  3361. nullptr,
  3362. CbData::GetterWrapper,
  3363. CbData::SetterWrapper,
  3364. nullptr,
  3365. attributes,
  3366. callbackData});
  3367. }
  3368. template <typename Getter, typename Setter>
  3369. inline PropertyDescriptor PropertyDescriptor::Accessor(
  3370. Napi::Env env,
  3371. Napi::Object object,
  3372. const std::string& utf8name,
  3373. Getter getter,
  3374. Setter setter,
  3375. napi_property_attributes attributes,
  3376. void* data) {
  3377. return Accessor(
  3378. env, object, utf8name.c_str(), getter, setter, attributes, data);
  3379. }
  3380. template <typename Getter, typename Setter>
  3381. inline PropertyDescriptor PropertyDescriptor::Accessor(
  3382. Napi::Env env,
  3383. Napi::Object object,
  3384. Name name,
  3385. Getter getter,
  3386. Setter setter,
  3387. napi_property_attributes attributes,
  3388. void* data) {
  3389. using CbData = details::AccessorCallbackData<Getter, Setter>;
  3390. auto callbackData = new CbData({getter, setter, data});
  3391. napi_status status = AttachData(env, object, callbackData);
  3392. if (status != napi_ok) {
  3393. delete callbackData;
  3394. NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  3395. }
  3396. return PropertyDescriptor({nullptr,
  3397. name,
  3398. nullptr,
  3399. CbData::GetterWrapper,
  3400. CbData::SetterWrapper,
  3401. nullptr,
  3402. attributes,
  3403. callbackData});
  3404. }
  3405. template <typename Callable>
  3406. inline PropertyDescriptor PropertyDescriptor::Function(
  3407. Napi::Env env,
  3408. Napi::Object /*object*/,
  3409. const char* utf8name,
  3410. Callable cb,
  3411. napi_property_attributes attributes,
  3412. void* data) {
  3413. return PropertyDescriptor({utf8name,
  3414. nullptr,
  3415. nullptr,
  3416. nullptr,
  3417. nullptr,
  3418. Napi::Function::New(env, cb, utf8name, data),
  3419. attributes,
  3420. nullptr});
  3421. }
  3422. template <typename Callable>
  3423. inline PropertyDescriptor PropertyDescriptor::Function(
  3424. Napi::Env env,
  3425. Napi::Object object,
  3426. const std::string& utf8name,
  3427. Callable cb,
  3428. napi_property_attributes attributes,
  3429. void* data) {
  3430. return Function(env, object, utf8name.c_str(), cb, attributes, data);
  3431. }
  3432. template <typename Callable>
  3433. inline PropertyDescriptor PropertyDescriptor::Function(
  3434. Napi::Env env,
  3435. Napi::Object /*object*/,
  3436. Name name,
  3437. Callable cb,
  3438. napi_property_attributes attributes,
  3439. void* data) {
  3440. return PropertyDescriptor({nullptr,
  3441. name,
  3442. nullptr,
  3443. nullptr,
  3444. nullptr,
  3445. Napi::Function::New(env, cb, nullptr, data),
  3446. attributes,
  3447. nullptr});
  3448. }
  3449. inline PropertyDescriptor PropertyDescriptor::Value(
  3450. const char* utf8name,
  3451. napi_value value,
  3452. napi_property_attributes attributes) {
  3453. return PropertyDescriptor({utf8name,
  3454. nullptr,
  3455. nullptr,
  3456. nullptr,
  3457. nullptr,
  3458. value,
  3459. attributes,
  3460. nullptr});
  3461. }
  3462. inline PropertyDescriptor PropertyDescriptor::Value(
  3463. const std::string& utf8name,
  3464. napi_value value,
  3465. napi_property_attributes attributes) {
  3466. return Value(utf8name.c_str(), value, attributes);
  3467. }
  3468. inline PropertyDescriptor PropertyDescriptor::Value(
  3469. napi_value name, napi_value value, napi_property_attributes attributes) {
  3470. return PropertyDescriptor(
  3471. {nullptr, name, nullptr, nullptr, nullptr, value, attributes, nullptr});
  3472. }
  3473. inline PropertyDescriptor PropertyDescriptor::Value(
  3474. Name name, Napi::Value value, napi_property_attributes attributes) {
  3475. napi_value nameValue = name;
  3476. napi_value valueValue = value;
  3477. return PropertyDescriptor::Value(nameValue, valueValue, attributes);
  3478. }
  3479. inline PropertyDescriptor::PropertyDescriptor(napi_property_descriptor desc)
  3480. : _desc(desc) {}
  3481. inline PropertyDescriptor::operator napi_property_descriptor&() {
  3482. return _desc;
  3483. }
  3484. inline PropertyDescriptor::operator const napi_property_descriptor&() const {
  3485. return _desc;
  3486. }
  3487. ////////////////////////////////////////////////////////////////////////////////
  3488. // InstanceWrap<T> class
  3489. ////////////////////////////////////////////////////////////////////////////////
  3490. template <typename T>
  3491. inline void InstanceWrap<T>::AttachPropData(
  3492. napi_env env, napi_value value, const napi_property_descriptor* prop) {
  3493. napi_status status;
  3494. if (!(prop->attributes & napi_static)) {
  3495. if (prop->method == T::InstanceVoidMethodCallbackWrapper) {
  3496. status = Napi::details::AttachData(
  3497. env, value, static_cast<InstanceVoidMethodCallbackData*>(prop->data));
  3498. NAPI_THROW_IF_FAILED_VOID(env, status);
  3499. } else if (prop->method == T::InstanceMethodCallbackWrapper) {
  3500. status = Napi::details::AttachData(
  3501. env, value, static_cast<InstanceMethodCallbackData*>(prop->data));
  3502. NAPI_THROW_IF_FAILED_VOID(env, status);
  3503. } else if (prop->getter == T::InstanceGetterCallbackWrapper ||
  3504. prop->setter == T::InstanceSetterCallbackWrapper) {
  3505. status = Napi::details::AttachData(
  3506. env, value, static_cast<InstanceAccessorCallbackData*>(prop->data));
  3507. NAPI_THROW_IF_FAILED_VOID(env, status);
  3508. }
  3509. }
  3510. }
  3511. template <typename T>
  3512. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3513. const char* utf8name,
  3514. InstanceVoidMethodCallback method,
  3515. napi_property_attributes attributes,
  3516. void* data) {
  3517. InstanceVoidMethodCallbackData* callbackData =
  3518. new InstanceVoidMethodCallbackData({method, data});
  3519. napi_property_descriptor desc = napi_property_descriptor();
  3520. desc.utf8name = utf8name;
  3521. desc.method = T::InstanceVoidMethodCallbackWrapper;
  3522. desc.data = callbackData;
  3523. desc.attributes = attributes;
  3524. return desc;
  3525. }
  3526. template <typename T>
  3527. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3528. const char* utf8name,
  3529. InstanceMethodCallback method,
  3530. napi_property_attributes attributes,
  3531. void* data) {
  3532. InstanceMethodCallbackData* callbackData =
  3533. new InstanceMethodCallbackData({method, data});
  3534. napi_property_descriptor desc = napi_property_descriptor();
  3535. desc.utf8name = utf8name;
  3536. desc.method = T::InstanceMethodCallbackWrapper;
  3537. desc.data = callbackData;
  3538. desc.attributes = attributes;
  3539. return desc;
  3540. }
  3541. template <typename T>
  3542. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3543. Symbol name,
  3544. InstanceVoidMethodCallback method,
  3545. napi_property_attributes attributes,
  3546. void* data) {
  3547. InstanceVoidMethodCallbackData* callbackData =
  3548. new InstanceVoidMethodCallbackData({method, data});
  3549. napi_property_descriptor desc = napi_property_descriptor();
  3550. desc.name = name;
  3551. desc.method = T::InstanceVoidMethodCallbackWrapper;
  3552. desc.data = callbackData;
  3553. desc.attributes = attributes;
  3554. return desc;
  3555. }
  3556. template <typename T>
  3557. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3558. Symbol name,
  3559. InstanceMethodCallback method,
  3560. napi_property_attributes attributes,
  3561. void* data) {
  3562. InstanceMethodCallbackData* callbackData =
  3563. new InstanceMethodCallbackData({method, data});
  3564. napi_property_descriptor desc = napi_property_descriptor();
  3565. desc.name = name;
  3566. desc.method = T::InstanceMethodCallbackWrapper;
  3567. desc.data = callbackData;
  3568. desc.attributes = attributes;
  3569. return desc;
  3570. }
  3571. template <typename T>
  3572. template <typename InstanceWrap<T>::InstanceVoidMethodCallback method>
  3573. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3574. const char* utf8name, napi_property_attributes attributes, void* data) {
  3575. napi_property_descriptor desc = napi_property_descriptor();
  3576. desc.utf8name = utf8name;
  3577. desc.method = details::TemplatedInstanceVoidCallback<T, method>;
  3578. desc.data = data;
  3579. desc.attributes = attributes;
  3580. return desc;
  3581. }
  3582. template <typename T>
  3583. template <typename InstanceWrap<T>::InstanceMethodCallback method>
  3584. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3585. const char* utf8name, napi_property_attributes attributes, void* data) {
  3586. napi_property_descriptor desc = napi_property_descriptor();
  3587. desc.utf8name = utf8name;
  3588. desc.method = details::TemplatedInstanceCallback<T, method>;
  3589. desc.data = data;
  3590. desc.attributes = attributes;
  3591. return desc;
  3592. }
  3593. template <typename T>
  3594. template <typename InstanceWrap<T>::InstanceVoidMethodCallback method>
  3595. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3596. Symbol name, napi_property_attributes attributes, void* data) {
  3597. napi_property_descriptor desc = napi_property_descriptor();
  3598. desc.name = name;
  3599. desc.method = details::TemplatedInstanceVoidCallback<T, method>;
  3600. desc.data = data;
  3601. desc.attributes = attributes;
  3602. return desc;
  3603. }
  3604. template <typename T>
  3605. template <typename InstanceWrap<T>::InstanceMethodCallback method>
  3606. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceMethod(
  3607. Symbol name, napi_property_attributes attributes, void* data) {
  3608. napi_property_descriptor desc = napi_property_descriptor();
  3609. desc.name = name;
  3610. desc.method = details::TemplatedInstanceCallback<T, method>;
  3611. desc.data = data;
  3612. desc.attributes = attributes;
  3613. return desc;
  3614. }
  3615. template <typename T>
  3616. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceAccessor(
  3617. const char* utf8name,
  3618. InstanceGetterCallback getter,
  3619. InstanceSetterCallback setter,
  3620. napi_property_attributes attributes,
  3621. void* data) {
  3622. InstanceAccessorCallbackData* callbackData =
  3623. new InstanceAccessorCallbackData({getter, setter, data});
  3624. napi_property_descriptor desc = napi_property_descriptor();
  3625. desc.utf8name = utf8name;
  3626. desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr;
  3627. desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr;
  3628. desc.data = callbackData;
  3629. desc.attributes = attributes;
  3630. return desc;
  3631. }
  3632. template <typename T>
  3633. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceAccessor(
  3634. Symbol name,
  3635. InstanceGetterCallback getter,
  3636. InstanceSetterCallback setter,
  3637. napi_property_attributes attributes,
  3638. void* data) {
  3639. InstanceAccessorCallbackData* callbackData =
  3640. new InstanceAccessorCallbackData({getter, setter, data});
  3641. napi_property_descriptor desc = napi_property_descriptor();
  3642. desc.name = name;
  3643. desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr;
  3644. desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr;
  3645. desc.data = callbackData;
  3646. desc.attributes = attributes;
  3647. return desc;
  3648. }
  3649. template <typename T>
  3650. template <typename InstanceWrap<T>::InstanceGetterCallback getter,
  3651. typename InstanceWrap<T>::InstanceSetterCallback setter>
  3652. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceAccessor(
  3653. const char* utf8name, napi_property_attributes attributes, void* data) {
  3654. napi_property_descriptor desc = napi_property_descriptor();
  3655. desc.utf8name = utf8name;
  3656. desc.getter = details::TemplatedInstanceCallback<T, getter>;
  3657. desc.setter = This::WrapSetter(This::SetterTag<setter>());
  3658. desc.data = data;
  3659. desc.attributes = attributes;
  3660. return desc;
  3661. }
  3662. template <typename T>
  3663. template <typename InstanceWrap<T>::InstanceGetterCallback getter,
  3664. typename InstanceWrap<T>::InstanceSetterCallback setter>
  3665. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceAccessor(
  3666. Symbol name, napi_property_attributes attributes, void* data) {
  3667. napi_property_descriptor desc = napi_property_descriptor();
  3668. desc.name = name;
  3669. desc.getter = details::TemplatedInstanceCallback<T, getter>;
  3670. desc.setter = This::WrapSetter(This::SetterTag<setter>());
  3671. desc.data = data;
  3672. desc.attributes = attributes;
  3673. return desc;
  3674. }
  3675. template <typename T>
  3676. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceValue(
  3677. const char* utf8name,
  3678. Napi::Value value,
  3679. napi_property_attributes attributes) {
  3680. napi_property_descriptor desc = napi_property_descriptor();
  3681. desc.utf8name = utf8name;
  3682. desc.value = value;
  3683. desc.attributes = attributes;
  3684. return desc;
  3685. }
  3686. template <typename T>
  3687. inline ClassPropertyDescriptor<T> InstanceWrap<T>::InstanceValue(
  3688. Symbol name, Napi::Value value, napi_property_attributes attributes) {
  3689. napi_property_descriptor desc = napi_property_descriptor();
  3690. desc.name = name;
  3691. desc.value = value;
  3692. desc.attributes = attributes;
  3693. return desc;
  3694. }
  3695. template <typename T>
  3696. inline napi_value InstanceWrap<T>::InstanceVoidMethodCallbackWrapper(
  3697. napi_env env, napi_callback_info info) {
  3698. return details::WrapCallback([&] {
  3699. CallbackInfo callbackInfo(env, info);
  3700. InstanceVoidMethodCallbackData* callbackData =
  3701. reinterpret_cast<InstanceVoidMethodCallbackData*>(callbackInfo.Data());
  3702. callbackInfo.SetData(callbackData->data);
  3703. T* instance = T::Unwrap(callbackInfo.This().As<Object>());
  3704. auto cb = callbackData->callback;
  3705. (instance->*cb)(callbackInfo);
  3706. return nullptr;
  3707. });
  3708. }
  3709. template <typename T>
  3710. inline napi_value InstanceWrap<T>::InstanceMethodCallbackWrapper(
  3711. napi_env env, napi_callback_info info) {
  3712. return details::WrapCallback([&] {
  3713. CallbackInfo callbackInfo(env, info);
  3714. InstanceMethodCallbackData* callbackData =
  3715. reinterpret_cast<InstanceMethodCallbackData*>(callbackInfo.Data());
  3716. callbackInfo.SetData(callbackData->data);
  3717. T* instance = T::Unwrap(callbackInfo.This().As<Object>());
  3718. auto cb = callbackData->callback;
  3719. return (instance->*cb)(callbackInfo);
  3720. });
  3721. }
  3722. template <typename T>
  3723. inline napi_value InstanceWrap<T>::InstanceGetterCallbackWrapper(
  3724. napi_env env, napi_callback_info info) {
  3725. return details::WrapCallback([&] {
  3726. CallbackInfo callbackInfo(env, info);
  3727. InstanceAccessorCallbackData* callbackData =
  3728. reinterpret_cast<InstanceAccessorCallbackData*>(callbackInfo.Data());
  3729. callbackInfo.SetData(callbackData->data);
  3730. T* instance = T::Unwrap(callbackInfo.This().As<Object>());
  3731. auto cb = callbackData->getterCallback;
  3732. return (instance->*cb)(callbackInfo);
  3733. });
  3734. }
  3735. template <typename T>
  3736. inline napi_value InstanceWrap<T>::InstanceSetterCallbackWrapper(
  3737. napi_env env, napi_callback_info info) {
  3738. return details::WrapCallback([&] {
  3739. CallbackInfo callbackInfo(env, info);
  3740. InstanceAccessorCallbackData* callbackData =
  3741. reinterpret_cast<InstanceAccessorCallbackData*>(callbackInfo.Data());
  3742. callbackInfo.SetData(callbackData->data);
  3743. T* instance = T::Unwrap(callbackInfo.This().As<Object>());
  3744. auto cb = callbackData->setterCallback;
  3745. (instance->*cb)(callbackInfo, callbackInfo[0]);
  3746. return nullptr;
  3747. });
  3748. }
  3749. template <typename T>
  3750. template <typename InstanceWrap<T>::InstanceSetterCallback method>
  3751. inline napi_value InstanceWrap<T>::WrappedMethod(
  3752. napi_env env, napi_callback_info info) NAPI_NOEXCEPT {
  3753. return details::WrapCallback([&] {
  3754. const CallbackInfo cbInfo(env, info);
  3755. T* instance = T::Unwrap(cbInfo.This().As<Object>());
  3756. (instance->*method)(cbInfo, cbInfo[0]);
  3757. return nullptr;
  3758. });
  3759. }
  3760. ////////////////////////////////////////////////////////////////////////////////
  3761. // ObjectWrap<T> class
  3762. ////////////////////////////////////////////////////////////////////////////////
  3763. template <typename T>
  3764. inline ObjectWrap<T>::ObjectWrap(const Napi::CallbackInfo& callbackInfo) {
  3765. napi_env env = callbackInfo.Env();
  3766. napi_value wrapper = callbackInfo.This();
  3767. napi_status status;
  3768. napi_ref ref;
  3769. T* instance = static_cast<T*>(this);
  3770. status = napi_wrap(env, wrapper, instance, FinalizeCallback, nullptr, &ref);
  3771. NAPI_THROW_IF_FAILED_VOID(env, status);
  3772. Reference<Object>* instanceRef = instance;
  3773. *instanceRef = Reference<Object>(env, ref);
  3774. }
  3775. template <typename T>
  3776. inline ObjectWrap<T>::~ObjectWrap() {
  3777. // If the JS object still exists at this point, remove the finalizer added
  3778. // through `napi_wrap()`.
  3779. if (!IsEmpty()) {
  3780. Object object = Value();
  3781. // It is not valid to call `napi_remove_wrap()` with an empty `object`.
  3782. // This happens e.g. during garbage collection.
  3783. if (!object.IsEmpty() && _construction_failed) {
  3784. napi_remove_wrap(Env(), object, nullptr);
  3785. }
  3786. }
  3787. }
  3788. template <typename T>
  3789. inline T* ObjectWrap<T>::Unwrap(Object wrapper) {
  3790. void* unwrapped;
  3791. napi_status status = napi_unwrap(wrapper.Env(), wrapper, &unwrapped);
  3792. NAPI_THROW_IF_FAILED(wrapper.Env(), status, nullptr);
  3793. return static_cast<T*>(unwrapped);
  3794. }
  3795. template <typename T>
  3796. inline Function ObjectWrap<T>::DefineClass(
  3797. Napi::Env env,
  3798. const char* utf8name,
  3799. const size_t props_count,
  3800. const napi_property_descriptor* descriptors,
  3801. void* data) {
  3802. napi_status status;
  3803. std::vector<napi_property_descriptor> props(props_count);
  3804. // We copy the descriptors to a local array because before defining the class
  3805. // we must replace static method property descriptors with value property
  3806. // descriptors such that the value is a function-valued `napi_value` created
  3807. // with `CreateFunction()`.
  3808. //
  3809. // This replacement could be made for instance methods as well, but V8 aborts
  3810. // if we do that, because it expects methods defined on the prototype template
  3811. // to have `FunctionTemplate`s.
  3812. for (size_t index = 0; index < props_count; index++) {
  3813. props[index] = descriptors[index];
  3814. napi_property_descriptor* prop = &props[index];
  3815. if (prop->method == T::StaticMethodCallbackWrapper) {
  3816. status =
  3817. CreateFunction(env,
  3818. utf8name,
  3819. prop->method,
  3820. static_cast<StaticMethodCallbackData*>(prop->data),
  3821. &(prop->value));
  3822. NAPI_THROW_IF_FAILED(env, status, Function());
  3823. prop->method = nullptr;
  3824. prop->data = nullptr;
  3825. } else if (prop->method == T::StaticVoidMethodCallbackWrapper) {
  3826. status =
  3827. CreateFunction(env,
  3828. utf8name,
  3829. prop->method,
  3830. static_cast<StaticVoidMethodCallbackData*>(prop->data),
  3831. &(prop->value));
  3832. NAPI_THROW_IF_FAILED(env, status, Function());
  3833. prop->method = nullptr;
  3834. prop->data = nullptr;
  3835. }
  3836. }
  3837. napi_value value;
  3838. status = napi_define_class(env,
  3839. utf8name,
  3840. NAPI_AUTO_LENGTH,
  3841. T::ConstructorCallbackWrapper,
  3842. data,
  3843. props_count,
  3844. props.data(),
  3845. &value);
  3846. NAPI_THROW_IF_FAILED(env, status, Function());
  3847. // After defining the class we iterate once more over the property descriptors
  3848. // and attach the data associated with accessors and instance methods to the
  3849. // newly created JavaScript class.
  3850. for (size_t idx = 0; idx < props_count; idx++) {
  3851. const napi_property_descriptor* prop = &props[idx];
  3852. if (prop->getter == T::StaticGetterCallbackWrapper ||
  3853. prop->setter == T::StaticSetterCallbackWrapper) {
  3854. status = Napi::details::AttachData(
  3855. env, value, static_cast<StaticAccessorCallbackData*>(prop->data));
  3856. NAPI_THROW_IF_FAILED(env, status, Function());
  3857. } else {
  3858. // InstanceWrap<T>::AttachPropData is responsible for attaching the data
  3859. // of instance methods and accessors.
  3860. T::AttachPropData(env, value, prop);
  3861. }
  3862. }
  3863. return Function(env, value);
  3864. }
  3865. template <typename T>
  3866. inline Function ObjectWrap<T>::DefineClass(
  3867. Napi::Env env,
  3868. const char* utf8name,
  3869. const std::initializer_list<ClassPropertyDescriptor<T>>& properties,
  3870. void* data) {
  3871. return DefineClass(
  3872. env,
  3873. utf8name,
  3874. properties.size(),
  3875. reinterpret_cast<const napi_property_descriptor*>(properties.begin()),
  3876. data);
  3877. }
  3878. template <typename T>
  3879. inline Function ObjectWrap<T>::DefineClass(
  3880. Napi::Env env,
  3881. const char* utf8name,
  3882. const std::vector<ClassPropertyDescriptor<T>>& properties,
  3883. void* data) {
  3884. return DefineClass(
  3885. env,
  3886. utf8name,
  3887. properties.size(),
  3888. reinterpret_cast<const napi_property_descriptor*>(properties.data()),
  3889. data);
  3890. }
  3891. template <typename T>
  3892. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3893. const char* utf8name,
  3894. StaticVoidMethodCallback method,
  3895. napi_property_attributes attributes,
  3896. void* data) {
  3897. StaticVoidMethodCallbackData* callbackData =
  3898. new StaticVoidMethodCallbackData({method, data});
  3899. napi_property_descriptor desc = napi_property_descriptor();
  3900. desc.utf8name = utf8name;
  3901. desc.method = T::StaticVoidMethodCallbackWrapper;
  3902. desc.data = callbackData;
  3903. desc.attributes =
  3904. static_cast<napi_property_attributes>(attributes | napi_static);
  3905. return desc;
  3906. }
  3907. template <typename T>
  3908. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3909. const char* utf8name,
  3910. StaticMethodCallback method,
  3911. napi_property_attributes attributes,
  3912. void* data) {
  3913. StaticMethodCallbackData* callbackData =
  3914. new StaticMethodCallbackData({method, data});
  3915. napi_property_descriptor desc = napi_property_descriptor();
  3916. desc.utf8name = utf8name;
  3917. desc.method = T::StaticMethodCallbackWrapper;
  3918. desc.data = callbackData;
  3919. desc.attributes =
  3920. static_cast<napi_property_attributes>(attributes | napi_static);
  3921. return desc;
  3922. }
  3923. template <typename T>
  3924. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3925. Symbol name,
  3926. StaticVoidMethodCallback method,
  3927. napi_property_attributes attributes,
  3928. void* data) {
  3929. StaticVoidMethodCallbackData* callbackData =
  3930. new StaticVoidMethodCallbackData({method, data});
  3931. napi_property_descriptor desc = napi_property_descriptor();
  3932. desc.name = name;
  3933. desc.method = T::StaticVoidMethodCallbackWrapper;
  3934. desc.data = callbackData;
  3935. desc.attributes =
  3936. static_cast<napi_property_attributes>(attributes | napi_static);
  3937. return desc;
  3938. }
  3939. template <typename T>
  3940. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3941. Symbol name,
  3942. StaticMethodCallback method,
  3943. napi_property_attributes attributes,
  3944. void* data) {
  3945. StaticMethodCallbackData* callbackData =
  3946. new StaticMethodCallbackData({method, data});
  3947. napi_property_descriptor desc = napi_property_descriptor();
  3948. desc.name = name;
  3949. desc.method = T::StaticMethodCallbackWrapper;
  3950. desc.data = callbackData;
  3951. desc.attributes =
  3952. static_cast<napi_property_attributes>(attributes | napi_static);
  3953. return desc;
  3954. }
  3955. template <typename T>
  3956. template <typename ObjectWrap<T>::StaticVoidMethodCallback method>
  3957. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3958. const char* utf8name, napi_property_attributes attributes, void* data) {
  3959. napi_property_descriptor desc = napi_property_descriptor();
  3960. desc.utf8name = utf8name;
  3961. desc.method = details::TemplatedVoidCallback<method>;
  3962. desc.data = data;
  3963. desc.attributes =
  3964. static_cast<napi_property_attributes>(attributes | napi_static);
  3965. return desc;
  3966. }
  3967. template <typename T>
  3968. template <typename ObjectWrap<T>::StaticVoidMethodCallback method>
  3969. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3970. Symbol name, napi_property_attributes attributes, void* data) {
  3971. napi_property_descriptor desc = napi_property_descriptor();
  3972. desc.name = name;
  3973. desc.method = details::TemplatedVoidCallback<method>;
  3974. desc.data = data;
  3975. desc.attributes =
  3976. static_cast<napi_property_attributes>(attributes | napi_static);
  3977. return desc;
  3978. }
  3979. template <typename T>
  3980. template <typename ObjectWrap<T>::StaticMethodCallback method>
  3981. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3982. const char* utf8name, napi_property_attributes attributes, void* data) {
  3983. napi_property_descriptor desc = napi_property_descriptor();
  3984. desc.utf8name = utf8name;
  3985. desc.method = details::TemplatedCallback<method>;
  3986. desc.data = data;
  3987. desc.attributes =
  3988. static_cast<napi_property_attributes>(attributes | napi_static);
  3989. return desc;
  3990. }
  3991. template <typename T>
  3992. template <typename ObjectWrap<T>::StaticMethodCallback method>
  3993. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticMethod(
  3994. Symbol name, napi_property_attributes attributes, void* data) {
  3995. napi_property_descriptor desc = napi_property_descriptor();
  3996. desc.name = name;
  3997. desc.method = details::TemplatedCallback<method>;
  3998. desc.data = data;
  3999. desc.attributes =
  4000. static_cast<napi_property_attributes>(attributes | napi_static);
  4001. return desc;
  4002. }
  4003. template <typename T>
  4004. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticAccessor(
  4005. const char* utf8name,
  4006. StaticGetterCallback getter,
  4007. StaticSetterCallback setter,
  4008. napi_property_attributes attributes,
  4009. void* data) {
  4010. StaticAccessorCallbackData* callbackData =
  4011. new StaticAccessorCallbackData({getter, setter, data});
  4012. napi_property_descriptor desc = napi_property_descriptor();
  4013. desc.utf8name = utf8name;
  4014. desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr;
  4015. desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr;
  4016. desc.data = callbackData;
  4017. desc.attributes =
  4018. static_cast<napi_property_attributes>(attributes | napi_static);
  4019. return desc;
  4020. }
  4021. template <typename T>
  4022. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticAccessor(
  4023. Symbol name,
  4024. StaticGetterCallback getter,
  4025. StaticSetterCallback setter,
  4026. napi_property_attributes attributes,
  4027. void* data) {
  4028. StaticAccessorCallbackData* callbackData =
  4029. new StaticAccessorCallbackData({getter, setter, data});
  4030. napi_property_descriptor desc = napi_property_descriptor();
  4031. desc.name = name;
  4032. desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr;
  4033. desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr;
  4034. desc.data = callbackData;
  4035. desc.attributes =
  4036. static_cast<napi_property_attributes>(attributes | napi_static);
  4037. return desc;
  4038. }
  4039. template <typename T>
  4040. template <typename ObjectWrap<T>::StaticGetterCallback getter,
  4041. typename ObjectWrap<T>::StaticSetterCallback setter>
  4042. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticAccessor(
  4043. const char* utf8name, napi_property_attributes attributes, void* data) {
  4044. napi_property_descriptor desc = napi_property_descriptor();
  4045. desc.utf8name = utf8name;
  4046. desc.getter = details::TemplatedCallback<getter>;
  4047. desc.setter = This::WrapStaticSetter(This::StaticSetterTag<setter>());
  4048. desc.data = data;
  4049. desc.attributes =
  4050. static_cast<napi_property_attributes>(attributes | napi_static);
  4051. return desc;
  4052. }
  4053. template <typename T>
  4054. template <typename ObjectWrap<T>::StaticGetterCallback getter,
  4055. typename ObjectWrap<T>::StaticSetterCallback setter>
  4056. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticAccessor(
  4057. Symbol name, napi_property_attributes attributes, void* data) {
  4058. napi_property_descriptor desc = napi_property_descriptor();
  4059. desc.name = name;
  4060. desc.getter = details::TemplatedCallback<getter>;
  4061. desc.setter = This::WrapStaticSetter(This::StaticSetterTag<setter>());
  4062. desc.data = data;
  4063. desc.attributes =
  4064. static_cast<napi_property_attributes>(attributes | napi_static);
  4065. return desc;
  4066. }
  4067. template <typename T>
  4068. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticValue(
  4069. const char* utf8name,
  4070. Napi::Value value,
  4071. napi_property_attributes attributes) {
  4072. napi_property_descriptor desc = napi_property_descriptor();
  4073. desc.utf8name = utf8name;
  4074. desc.value = value;
  4075. desc.attributes =
  4076. static_cast<napi_property_attributes>(attributes | napi_static);
  4077. return desc;
  4078. }
  4079. template <typename T>
  4080. inline ClassPropertyDescriptor<T> ObjectWrap<T>::StaticValue(
  4081. Symbol name, Napi::Value value, napi_property_attributes attributes) {
  4082. napi_property_descriptor desc = napi_property_descriptor();
  4083. desc.name = name;
  4084. desc.value = value;
  4085. desc.attributes =
  4086. static_cast<napi_property_attributes>(attributes | napi_static);
  4087. return desc;
  4088. }
  4089. template <typename T>
  4090. inline Value ObjectWrap<T>::OnCalledAsFunction(
  4091. const Napi::CallbackInfo& callbackInfo) {
  4092. NAPI_THROW(
  4093. TypeError::New(callbackInfo.Env(),
  4094. "Class constructors cannot be invoked without 'new'"),
  4095. Napi::Value());
  4096. }
  4097. template <typename T>
  4098. inline void ObjectWrap<T>::Finalize(Napi::Env /*env*/) {}
  4099. template <typename T>
  4100. inline napi_value ObjectWrap<T>::ConstructorCallbackWrapper(
  4101. napi_env env, napi_callback_info info) {
  4102. napi_value new_target;
  4103. napi_status status = napi_get_new_target(env, info, &new_target);
  4104. if (status != napi_ok) return nullptr;
  4105. bool isConstructCall = (new_target != nullptr);
  4106. if (!isConstructCall) {
  4107. return details::WrapCallback(
  4108. [&] { return T::OnCalledAsFunction(CallbackInfo(env, info)); });
  4109. }
  4110. napi_value wrapper = details::WrapCallback([&] {
  4111. CallbackInfo callbackInfo(env, info);
  4112. T* instance = new T(callbackInfo);
  4113. #ifdef NAPI_CPP_EXCEPTIONS
  4114. instance->_construction_failed = false;
  4115. #else
  4116. if (callbackInfo.Env().IsExceptionPending()) {
  4117. // We need to clear the exception so that removing the wrap might work.
  4118. Error e = callbackInfo.Env().GetAndClearPendingException();
  4119. delete instance;
  4120. e.ThrowAsJavaScriptException();
  4121. } else {
  4122. instance->_construction_failed = false;
  4123. }
  4124. #endif // NAPI_CPP_EXCEPTIONS
  4125. return callbackInfo.This();
  4126. });
  4127. return wrapper;
  4128. }
  4129. template <typename T>
  4130. inline napi_value ObjectWrap<T>::StaticVoidMethodCallbackWrapper(
  4131. napi_env env, napi_callback_info info) {
  4132. return details::WrapCallback([&] {
  4133. CallbackInfo callbackInfo(env, info);
  4134. StaticVoidMethodCallbackData* callbackData =
  4135. reinterpret_cast<StaticVoidMethodCallbackData*>(callbackInfo.Data());
  4136. callbackInfo.SetData(callbackData->data);
  4137. callbackData->callback(callbackInfo);
  4138. return nullptr;
  4139. });
  4140. }
  4141. template <typename T>
  4142. inline napi_value ObjectWrap<T>::StaticMethodCallbackWrapper(
  4143. napi_env env, napi_callback_info info) {
  4144. return details::WrapCallback([&] {
  4145. CallbackInfo callbackInfo(env, info);
  4146. StaticMethodCallbackData* callbackData =
  4147. reinterpret_cast<StaticMethodCallbackData*>(callbackInfo.Data());
  4148. callbackInfo.SetData(callbackData->data);
  4149. return callbackData->callback(callbackInfo);
  4150. });
  4151. }
  4152. template <typename T>
  4153. inline napi_value ObjectWrap<T>::StaticGetterCallbackWrapper(
  4154. napi_env env, napi_callback_info info) {
  4155. return details::WrapCallback([&] {
  4156. CallbackInfo callbackInfo(env, info);
  4157. StaticAccessorCallbackData* callbackData =
  4158. reinterpret_cast<StaticAccessorCallbackData*>(callbackInfo.Data());
  4159. callbackInfo.SetData(callbackData->data);
  4160. return callbackData->getterCallback(callbackInfo);
  4161. });
  4162. }
  4163. template <typename T>
  4164. inline napi_value ObjectWrap<T>::StaticSetterCallbackWrapper(
  4165. napi_env env, napi_callback_info info) {
  4166. return details::WrapCallback([&] {
  4167. CallbackInfo callbackInfo(env, info);
  4168. StaticAccessorCallbackData* callbackData =
  4169. reinterpret_cast<StaticAccessorCallbackData*>(callbackInfo.Data());
  4170. callbackInfo.SetData(callbackData->data);
  4171. callbackData->setterCallback(callbackInfo, callbackInfo[0]);
  4172. return nullptr;
  4173. });
  4174. }
  4175. template <typename T>
  4176. inline void ObjectWrap<T>::FinalizeCallback(napi_env env,
  4177. void* data,
  4178. void* /*hint*/) {
  4179. HandleScope scope(env);
  4180. T* instance = static_cast<T*>(data);
  4181. instance->Finalize(Napi::Env(env));
  4182. delete instance;
  4183. }
  4184. template <typename T>
  4185. template <typename ObjectWrap<T>::StaticSetterCallback method>
  4186. inline napi_value ObjectWrap<T>::WrappedMethod(
  4187. napi_env env, napi_callback_info info) NAPI_NOEXCEPT {
  4188. return details::WrapCallback([&] {
  4189. const CallbackInfo cbInfo(env, info);
  4190. method(cbInfo, cbInfo[0]);
  4191. return nullptr;
  4192. });
  4193. }
  4194. ////////////////////////////////////////////////////////////////////////////////
  4195. // HandleScope class
  4196. ////////////////////////////////////////////////////////////////////////////////
  4197. inline HandleScope::HandleScope(napi_env env, napi_handle_scope scope)
  4198. : _env(env), _scope(scope) {}
  4199. inline HandleScope::HandleScope(Napi::Env env) : _env(env) {
  4200. napi_status status = napi_open_handle_scope(_env, &_scope);
  4201. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4202. }
  4203. inline HandleScope::~HandleScope() {
  4204. napi_status status = napi_close_handle_scope(_env, _scope);
  4205. NAPI_FATAL_IF_FAILED(
  4206. status, "HandleScope::~HandleScope", "napi_close_handle_scope");
  4207. }
  4208. inline HandleScope::operator napi_handle_scope() const {
  4209. return _scope;
  4210. }
  4211. inline Napi::Env HandleScope::Env() const {
  4212. return Napi::Env(_env);
  4213. }
  4214. ////////////////////////////////////////////////////////////////////////////////
  4215. // EscapableHandleScope class
  4216. ////////////////////////////////////////////////////////////////////////////////
  4217. inline EscapableHandleScope::EscapableHandleScope(
  4218. napi_env env, napi_escapable_handle_scope scope)
  4219. : _env(env), _scope(scope) {}
  4220. inline EscapableHandleScope::EscapableHandleScope(Napi::Env env) : _env(env) {
  4221. napi_status status = napi_open_escapable_handle_scope(_env, &_scope);
  4222. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4223. }
  4224. inline EscapableHandleScope::~EscapableHandleScope() {
  4225. napi_status status = napi_close_escapable_handle_scope(_env, _scope);
  4226. NAPI_FATAL_IF_FAILED(status,
  4227. "EscapableHandleScope::~EscapableHandleScope",
  4228. "napi_close_escapable_handle_scope");
  4229. }
  4230. inline EscapableHandleScope::operator napi_escapable_handle_scope() const {
  4231. return _scope;
  4232. }
  4233. inline Napi::Env EscapableHandleScope::Env() const {
  4234. return Napi::Env(_env);
  4235. }
  4236. inline Value EscapableHandleScope::Escape(napi_value escapee) {
  4237. napi_value result;
  4238. napi_status status = napi_escape_handle(_env, _scope, escapee, &result);
  4239. NAPI_THROW_IF_FAILED(_env, status, Value());
  4240. return Value(_env, result);
  4241. }
  4242. #if (NAPI_VERSION > 2)
  4243. ////////////////////////////////////////////////////////////////////////////////
  4244. // CallbackScope class
  4245. ////////////////////////////////////////////////////////////////////////////////
  4246. inline CallbackScope::CallbackScope(napi_env env, napi_callback_scope scope)
  4247. : _env(env), _scope(scope) {}
  4248. inline CallbackScope::CallbackScope(napi_env env, napi_async_context context)
  4249. : _env(env) {
  4250. napi_status status =
  4251. napi_open_callback_scope(_env, Object::New(env), context, &_scope);
  4252. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4253. }
  4254. inline CallbackScope::~CallbackScope() {
  4255. napi_status status = napi_close_callback_scope(_env, _scope);
  4256. NAPI_FATAL_IF_FAILED(
  4257. status, "CallbackScope::~CallbackScope", "napi_close_callback_scope");
  4258. }
  4259. inline CallbackScope::operator napi_callback_scope() const {
  4260. return _scope;
  4261. }
  4262. inline Napi::Env CallbackScope::Env() const {
  4263. return Napi::Env(_env);
  4264. }
  4265. #endif
  4266. ////////////////////////////////////////////////////////////////////////////////
  4267. // AsyncContext class
  4268. ////////////////////////////////////////////////////////////////////////////////
  4269. inline AsyncContext::AsyncContext(napi_env env, const char* resource_name)
  4270. : AsyncContext(env, resource_name, Object::New(env)) {}
  4271. inline AsyncContext::AsyncContext(napi_env env,
  4272. const char* resource_name,
  4273. const Object& resource)
  4274. : _env(env), _context(nullptr) {
  4275. napi_value resource_id;
  4276. napi_status status = napi_create_string_utf8(
  4277. _env, resource_name, NAPI_AUTO_LENGTH, &resource_id);
  4278. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4279. status = napi_async_init(_env, resource, resource_id, &_context);
  4280. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4281. }
  4282. inline AsyncContext::~AsyncContext() {
  4283. if (_context != nullptr) {
  4284. napi_async_destroy(_env, _context);
  4285. _context = nullptr;
  4286. }
  4287. }
  4288. inline AsyncContext::AsyncContext(AsyncContext&& other) {
  4289. _env = other._env;
  4290. other._env = nullptr;
  4291. _context = other._context;
  4292. other._context = nullptr;
  4293. }
  4294. inline AsyncContext& AsyncContext::operator=(AsyncContext&& other) {
  4295. _env = other._env;
  4296. other._env = nullptr;
  4297. _context = other._context;
  4298. other._context = nullptr;
  4299. return *this;
  4300. }
  4301. inline AsyncContext::operator napi_async_context() const {
  4302. return _context;
  4303. }
  4304. inline Napi::Env AsyncContext::Env() const {
  4305. return Napi::Env(_env);
  4306. }
  4307. ////////////////////////////////////////////////////////////////////////////////
  4308. // AsyncWorker class
  4309. ////////////////////////////////////////////////////////////////////////////////
  4310. #if NAPI_HAS_THREADS
  4311. inline AsyncWorker::AsyncWorker(const Function& callback)
  4312. : AsyncWorker(callback, "generic") {}
  4313. inline AsyncWorker::AsyncWorker(const Function& callback,
  4314. const char* resource_name)
  4315. : AsyncWorker(callback, resource_name, Object::New(callback.Env())) {}
  4316. inline AsyncWorker::AsyncWorker(const Function& callback,
  4317. const char* resource_name,
  4318. const Object& resource)
  4319. : AsyncWorker(
  4320. Object::New(callback.Env()), callback, resource_name, resource) {}
  4321. inline AsyncWorker::AsyncWorker(const Object& receiver,
  4322. const Function& callback)
  4323. : AsyncWorker(receiver, callback, "generic") {}
  4324. inline AsyncWorker::AsyncWorker(const Object& receiver,
  4325. const Function& callback,
  4326. const char* resource_name)
  4327. : AsyncWorker(
  4328. receiver, callback, resource_name, Object::New(callback.Env())) {}
  4329. inline AsyncWorker::AsyncWorker(const Object& receiver,
  4330. const Function& callback,
  4331. const char* resource_name,
  4332. const Object& resource)
  4333. : _env(callback.Env()),
  4334. _receiver(Napi::Persistent(receiver)),
  4335. _callback(Napi::Persistent(callback)),
  4336. _suppress_destruct(false) {
  4337. napi_value resource_id;
  4338. napi_status status = napi_create_string_latin1(
  4339. _env, resource_name, NAPI_AUTO_LENGTH, &resource_id);
  4340. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4341. status = napi_create_async_work(_env,
  4342. resource,
  4343. resource_id,
  4344. OnAsyncWorkExecute,
  4345. OnAsyncWorkComplete,
  4346. this,
  4347. &_work);
  4348. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4349. }
  4350. inline AsyncWorker::AsyncWorker(Napi::Env env) : AsyncWorker(env, "generic") {}
  4351. inline AsyncWorker::AsyncWorker(Napi::Env env, const char* resource_name)
  4352. : AsyncWorker(env, resource_name, Object::New(env)) {}
  4353. inline AsyncWorker::AsyncWorker(Napi::Env env,
  4354. const char* resource_name,
  4355. const Object& resource)
  4356. : _env(env), _receiver(), _callback(), _suppress_destruct(false) {
  4357. napi_value resource_id;
  4358. napi_status status = napi_create_string_latin1(
  4359. _env, resource_name, NAPI_AUTO_LENGTH, &resource_id);
  4360. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4361. status = napi_create_async_work(_env,
  4362. resource,
  4363. resource_id,
  4364. OnAsyncWorkExecute,
  4365. OnAsyncWorkComplete,
  4366. this,
  4367. &_work);
  4368. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4369. }
  4370. inline AsyncWorker::~AsyncWorker() {
  4371. if (_work != nullptr) {
  4372. napi_delete_async_work(_env, _work);
  4373. _work = nullptr;
  4374. }
  4375. }
  4376. inline void AsyncWorker::Destroy() {
  4377. delete this;
  4378. }
  4379. inline AsyncWorker::operator napi_async_work() const {
  4380. return _work;
  4381. }
  4382. inline Napi::Env AsyncWorker::Env() const {
  4383. return Napi::Env(_env);
  4384. }
  4385. inline void AsyncWorker::Queue() {
  4386. napi_status status = napi_queue_async_work(_env, _work);
  4387. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4388. }
  4389. inline void AsyncWorker::Cancel() {
  4390. napi_status status = napi_cancel_async_work(_env, _work);
  4391. NAPI_THROW_IF_FAILED_VOID(_env, status);
  4392. }
  4393. inline ObjectReference& AsyncWorker::Receiver() {
  4394. return _receiver;
  4395. }
  4396. inline FunctionReference& AsyncWorker::Callback() {
  4397. return _callback;
  4398. }
  4399. inline void AsyncWorker::SuppressDestruct() {
  4400. _suppress_destruct = true;
  4401. }
  4402. inline void AsyncWorker::OnOK() {
  4403. if (!_callback.IsEmpty()) {
  4404. _callback.Call(_receiver.Value(), GetResult(_callback.Env()));
  4405. }
  4406. }
  4407. inline void AsyncWorker::OnError(const Error& e) {
  4408. if (!_callback.IsEmpty()) {
  4409. _callback.Call(_receiver.Value(),
  4410. std::initializer_list<napi_value>{e.Value()});
  4411. }
  4412. }
  4413. inline void AsyncWorker::SetError(const std::string& error) {
  4414. _error = error;
  4415. }
  4416. inline std::vector<napi_value> AsyncWorker::GetResult(Napi::Env /*env*/) {
  4417. return {};
  4418. }
  4419. // The OnAsyncWorkExecute method receives an napi_env argument. However, do NOT
  4420. // use it within this method, as it does not run on the JavaScript thread and
  4421. // must not run any method that would cause JavaScript to run. In practice,
  4422. // this means that almost any use of napi_env will be incorrect.
  4423. inline void AsyncWorker::OnAsyncWorkExecute(napi_env env, void* asyncworker) {
  4424. AsyncWorker* self = static_cast<AsyncWorker*>(asyncworker);
  4425. self->OnExecute(env);
  4426. }
  4427. // The OnExecute method receives an napi_env argument. However, do NOT
  4428. // use it within this method, as it does not run on the JavaScript thread and
  4429. // must not run any method that would cause JavaScript to run. In practice,
  4430. // this means that almost any use of napi_env will be incorrect.
  4431. inline void AsyncWorker::OnExecute(Napi::Env /*DO_NOT_USE*/) {
  4432. #ifdef NAPI_CPP_EXCEPTIONS
  4433. try {
  4434. Execute();
  4435. } catch (const std::exception& e) {
  4436. SetError(e.what());
  4437. }
  4438. #else // NAPI_CPP_EXCEPTIONS
  4439. Execute();
  4440. #endif // NAPI_CPP_EXCEPTIONS
  4441. }
  4442. inline void AsyncWorker::OnAsyncWorkComplete(napi_env env,
  4443. napi_status status,
  4444. void* asyncworker) {
  4445. AsyncWorker* self = static_cast<AsyncWorker*>(asyncworker);
  4446. self->OnWorkComplete(env, status);
  4447. }
  4448. inline void AsyncWorker::OnWorkComplete(Napi::Env /*env*/, napi_status status) {
  4449. if (status != napi_cancelled) {
  4450. HandleScope scope(_env);
  4451. details::WrapCallback([&] {
  4452. if (_error.size() == 0) {
  4453. OnOK();
  4454. } else {
  4455. OnError(Error::New(_env, _error));
  4456. }
  4457. return nullptr;
  4458. });
  4459. }
  4460. if (!_suppress_destruct) {
  4461. Destroy();
  4462. }
  4463. }
  4464. #endif // NAPI_HAS_THREADS
  4465. #if (NAPI_VERSION > 3 && NAPI_HAS_THREADS)
  4466. ////////////////////////////////////////////////////////////////////////////////
  4467. // TypedThreadSafeFunction<ContextType,DataType,CallJs> class
  4468. ////////////////////////////////////////////////////////////////////////////////
  4469. // Starting with NAPI 5, the JavaScript function `func` parameter of
  4470. // `napi_create_threadsafe_function` is optional.
  4471. #if NAPI_VERSION > 4
  4472. // static, with Callback [missing] Resource [missing] Finalizer [missing]
  4473. template <typename ContextType,
  4474. typename DataType,
  4475. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4476. template <typename ResourceString>
  4477. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4478. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4479. napi_env env,
  4480. ResourceString resourceName,
  4481. size_t maxQueueSize,
  4482. size_t initialThreadCount,
  4483. ContextType* context) {
  4484. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4485. napi_status status =
  4486. napi_create_threadsafe_function(env,
  4487. nullptr,
  4488. nullptr,
  4489. String::From(env, resourceName),
  4490. maxQueueSize,
  4491. initialThreadCount,
  4492. nullptr,
  4493. nullptr,
  4494. context,
  4495. CallJsInternal,
  4496. &tsfn._tsfn);
  4497. if (status != napi_ok) {
  4498. NAPI_THROW_IF_FAILED(
  4499. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4500. }
  4501. return tsfn;
  4502. }
  4503. // static, with Callback [missing] Resource [passed] Finalizer [missing]
  4504. template <typename ContextType,
  4505. typename DataType,
  4506. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4507. template <typename ResourceString>
  4508. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4509. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4510. napi_env env,
  4511. const Object& resource,
  4512. ResourceString resourceName,
  4513. size_t maxQueueSize,
  4514. size_t initialThreadCount,
  4515. ContextType* context) {
  4516. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4517. napi_status status =
  4518. napi_create_threadsafe_function(env,
  4519. nullptr,
  4520. resource,
  4521. String::From(env, resourceName),
  4522. maxQueueSize,
  4523. initialThreadCount,
  4524. nullptr,
  4525. nullptr,
  4526. context,
  4527. CallJsInternal,
  4528. &tsfn._tsfn);
  4529. if (status != napi_ok) {
  4530. NAPI_THROW_IF_FAILED(
  4531. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4532. }
  4533. return tsfn;
  4534. }
  4535. // static, with Callback [missing] Resource [missing] Finalizer [passed]
  4536. template <typename ContextType,
  4537. typename DataType,
  4538. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4539. template <typename ResourceString,
  4540. typename Finalizer,
  4541. typename FinalizerDataType>
  4542. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4543. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4544. napi_env env,
  4545. ResourceString resourceName,
  4546. size_t maxQueueSize,
  4547. size_t initialThreadCount,
  4548. ContextType* context,
  4549. Finalizer finalizeCallback,
  4550. FinalizerDataType* data) {
  4551. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4552. auto* finalizeData = new details::
  4553. ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>(
  4554. {data, finalizeCallback});
  4555. napi_status status = napi_create_threadsafe_function(
  4556. env,
  4557. nullptr,
  4558. nullptr,
  4559. String::From(env, resourceName),
  4560. maxQueueSize,
  4561. initialThreadCount,
  4562. finalizeData,
  4563. details::ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>::
  4564. FinalizeFinalizeWrapperWithDataAndContext,
  4565. context,
  4566. CallJsInternal,
  4567. &tsfn._tsfn);
  4568. if (status != napi_ok) {
  4569. delete finalizeData;
  4570. NAPI_THROW_IF_FAILED(
  4571. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4572. }
  4573. return tsfn;
  4574. }
  4575. // static, with Callback [missing] Resource [passed] Finalizer [passed]
  4576. template <typename ContextType,
  4577. typename DataType,
  4578. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4579. template <typename ResourceString,
  4580. typename Finalizer,
  4581. typename FinalizerDataType>
  4582. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4583. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4584. napi_env env,
  4585. const Object& resource,
  4586. ResourceString resourceName,
  4587. size_t maxQueueSize,
  4588. size_t initialThreadCount,
  4589. ContextType* context,
  4590. Finalizer finalizeCallback,
  4591. FinalizerDataType* data) {
  4592. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4593. auto* finalizeData = new details::
  4594. ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>(
  4595. {data, finalizeCallback});
  4596. napi_status status = napi_create_threadsafe_function(
  4597. env,
  4598. nullptr,
  4599. resource,
  4600. String::From(env, resourceName),
  4601. maxQueueSize,
  4602. initialThreadCount,
  4603. finalizeData,
  4604. details::ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>::
  4605. FinalizeFinalizeWrapperWithDataAndContext,
  4606. context,
  4607. CallJsInternal,
  4608. &tsfn._tsfn);
  4609. if (status != napi_ok) {
  4610. delete finalizeData;
  4611. NAPI_THROW_IF_FAILED(
  4612. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4613. }
  4614. return tsfn;
  4615. }
  4616. #endif
  4617. // static, with Callback [passed] Resource [missing] Finalizer [missing]
  4618. template <typename ContextType,
  4619. typename DataType,
  4620. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4621. template <typename ResourceString>
  4622. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4623. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4624. napi_env env,
  4625. const Function& callback,
  4626. ResourceString resourceName,
  4627. size_t maxQueueSize,
  4628. size_t initialThreadCount,
  4629. ContextType* context) {
  4630. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4631. napi_status status =
  4632. napi_create_threadsafe_function(env,
  4633. callback,
  4634. nullptr,
  4635. String::From(env, resourceName),
  4636. maxQueueSize,
  4637. initialThreadCount,
  4638. nullptr,
  4639. nullptr,
  4640. context,
  4641. CallJsInternal,
  4642. &tsfn._tsfn);
  4643. if (status != napi_ok) {
  4644. NAPI_THROW_IF_FAILED(
  4645. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4646. }
  4647. return tsfn;
  4648. }
  4649. // static, with Callback [passed] Resource [passed] Finalizer [missing]
  4650. template <typename ContextType,
  4651. typename DataType,
  4652. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4653. template <typename ResourceString>
  4654. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4655. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4656. napi_env env,
  4657. const Function& callback,
  4658. const Object& resource,
  4659. ResourceString resourceName,
  4660. size_t maxQueueSize,
  4661. size_t initialThreadCount,
  4662. ContextType* context) {
  4663. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4664. napi_status status =
  4665. napi_create_threadsafe_function(env,
  4666. callback,
  4667. resource,
  4668. String::From(env, resourceName),
  4669. maxQueueSize,
  4670. initialThreadCount,
  4671. nullptr,
  4672. nullptr,
  4673. context,
  4674. CallJsInternal,
  4675. &tsfn._tsfn);
  4676. if (status != napi_ok) {
  4677. NAPI_THROW_IF_FAILED(
  4678. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4679. }
  4680. return tsfn;
  4681. }
  4682. // static, with Callback [passed] Resource [missing] Finalizer [passed]
  4683. template <typename ContextType,
  4684. typename DataType,
  4685. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4686. template <typename ResourceString,
  4687. typename Finalizer,
  4688. typename FinalizerDataType>
  4689. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4690. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4691. napi_env env,
  4692. const Function& callback,
  4693. ResourceString resourceName,
  4694. size_t maxQueueSize,
  4695. size_t initialThreadCount,
  4696. ContextType* context,
  4697. Finalizer finalizeCallback,
  4698. FinalizerDataType* data) {
  4699. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4700. auto* finalizeData = new details::
  4701. ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>(
  4702. {data, finalizeCallback});
  4703. napi_status status = napi_create_threadsafe_function(
  4704. env,
  4705. callback,
  4706. nullptr,
  4707. String::From(env, resourceName),
  4708. maxQueueSize,
  4709. initialThreadCount,
  4710. finalizeData,
  4711. details::ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>::
  4712. FinalizeFinalizeWrapperWithDataAndContext,
  4713. context,
  4714. CallJsInternal,
  4715. &tsfn._tsfn);
  4716. if (status != napi_ok) {
  4717. delete finalizeData;
  4718. NAPI_THROW_IF_FAILED(
  4719. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4720. }
  4721. return tsfn;
  4722. }
  4723. // static, with: Callback [passed] Resource [passed] Finalizer [passed]
  4724. template <typename ContextType,
  4725. typename DataType,
  4726. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4727. template <typename CallbackType,
  4728. typename ResourceString,
  4729. typename Finalizer,
  4730. typename FinalizerDataType>
  4731. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>
  4732. TypedThreadSafeFunction<ContextType, DataType, CallJs>::New(
  4733. napi_env env,
  4734. CallbackType callback,
  4735. const Object& resource,
  4736. ResourceString resourceName,
  4737. size_t maxQueueSize,
  4738. size_t initialThreadCount,
  4739. ContextType* context,
  4740. Finalizer finalizeCallback,
  4741. FinalizerDataType* data) {
  4742. TypedThreadSafeFunction<ContextType, DataType, CallJs> tsfn;
  4743. auto* finalizeData = new details::
  4744. ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>(
  4745. {data, finalizeCallback});
  4746. napi_status status = napi_create_threadsafe_function(
  4747. env,
  4748. details::DefaultCallbackWrapper<
  4749. CallbackType,
  4750. TypedThreadSafeFunction<ContextType, DataType, CallJs>>(env,
  4751. callback),
  4752. resource,
  4753. String::From(env, resourceName),
  4754. maxQueueSize,
  4755. initialThreadCount,
  4756. finalizeData,
  4757. details::ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>::
  4758. FinalizeFinalizeWrapperWithDataAndContext,
  4759. context,
  4760. CallJsInternal,
  4761. &tsfn._tsfn);
  4762. if (status != napi_ok) {
  4763. delete finalizeData;
  4764. NAPI_THROW_IF_FAILED(
  4765. env, status, TypedThreadSafeFunction<ContextType, DataType, CallJs>());
  4766. }
  4767. return tsfn;
  4768. }
  4769. template <typename ContextType,
  4770. typename DataType,
  4771. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4772. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>::
  4773. TypedThreadSafeFunction()
  4774. : _tsfn() {}
  4775. template <typename ContextType,
  4776. typename DataType,
  4777. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4778. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>::
  4779. TypedThreadSafeFunction(napi_threadsafe_function tsfn)
  4780. : _tsfn(tsfn) {}
  4781. template <typename ContextType,
  4782. typename DataType,
  4783. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4784. inline TypedThreadSafeFunction<ContextType, DataType, CallJs>::
  4785. operator napi_threadsafe_function() const {
  4786. return _tsfn;
  4787. }
  4788. template <typename ContextType,
  4789. typename DataType,
  4790. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4791. inline napi_status
  4792. TypedThreadSafeFunction<ContextType, DataType, CallJs>::BlockingCall(
  4793. DataType* data) const {
  4794. return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking);
  4795. }
  4796. template <typename ContextType,
  4797. typename DataType,
  4798. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4799. inline napi_status
  4800. TypedThreadSafeFunction<ContextType, DataType, CallJs>::NonBlockingCall(
  4801. DataType* data) const {
  4802. return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking);
  4803. }
  4804. template <typename ContextType,
  4805. typename DataType,
  4806. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4807. inline void TypedThreadSafeFunction<ContextType, DataType, CallJs>::Ref(
  4808. napi_env env) const {
  4809. if (_tsfn != nullptr) {
  4810. napi_status status = napi_ref_threadsafe_function(env, _tsfn);
  4811. NAPI_THROW_IF_FAILED_VOID(env, status);
  4812. }
  4813. }
  4814. template <typename ContextType,
  4815. typename DataType,
  4816. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4817. inline void TypedThreadSafeFunction<ContextType, DataType, CallJs>::Unref(
  4818. napi_env env) const {
  4819. if (_tsfn != nullptr) {
  4820. napi_status status = napi_unref_threadsafe_function(env, _tsfn);
  4821. NAPI_THROW_IF_FAILED_VOID(env, status);
  4822. }
  4823. }
  4824. template <typename ContextType,
  4825. typename DataType,
  4826. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4827. inline napi_status
  4828. TypedThreadSafeFunction<ContextType, DataType, CallJs>::Acquire() const {
  4829. return napi_acquire_threadsafe_function(_tsfn);
  4830. }
  4831. template <typename ContextType,
  4832. typename DataType,
  4833. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4834. inline napi_status
  4835. TypedThreadSafeFunction<ContextType, DataType, CallJs>::Release() const {
  4836. return napi_release_threadsafe_function(_tsfn, napi_tsfn_release);
  4837. }
  4838. template <typename ContextType,
  4839. typename DataType,
  4840. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4841. inline napi_status
  4842. TypedThreadSafeFunction<ContextType, DataType, CallJs>::Abort() const {
  4843. return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort);
  4844. }
  4845. template <typename ContextType,
  4846. typename DataType,
  4847. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4848. inline ContextType*
  4849. TypedThreadSafeFunction<ContextType, DataType, CallJs>::GetContext() const {
  4850. void* context;
  4851. napi_status status = napi_get_threadsafe_function_context(_tsfn, &context);
  4852. NAPI_FATAL_IF_FAILED(status,
  4853. "TypedThreadSafeFunction::GetContext",
  4854. "napi_get_threadsafe_function_context");
  4855. return static_cast<ContextType*>(context);
  4856. }
  4857. // static
  4858. template <typename ContextType,
  4859. typename DataType,
  4860. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4861. void TypedThreadSafeFunction<ContextType, DataType, CallJs>::CallJsInternal(
  4862. napi_env env, napi_value jsCallback, void* context, void* data) {
  4863. details::CallJsWrapper<ContextType, DataType, decltype(CallJs), CallJs>(
  4864. env, jsCallback, context, data);
  4865. }
  4866. #if NAPI_VERSION == 4
  4867. // static
  4868. template <typename ContextType,
  4869. typename DataType,
  4870. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4871. Napi::Function
  4872. TypedThreadSafeFunction<ContextType, DataType, CallJs>::EmptyFunctionFactory(
  4873. Napi::Env env) {
  4874. return Napi::Function::New(env, [](const CallbackInfo& cb) {});
  4875. }
  4876. // static
  4877. template <typename ContextType,
  4878. typename DataType,
  4879. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4880. Napi::Function
  4881. TypedThreadSafeFunction<ContextType, DataType, CallJs>::FunctionOrEmpty(
  4882. Napi::Env env, Napi::Function& callback) {
  4883. if (callback.IsEmpty()) {
  4884. return EmptyFunctionFactory(env);
  4885. }
  4886. return callback;
  4887. }
  4888. #else
  4889. // static
  4890. template <typename ContextType,
  4891. typename DataType,
  4892. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4893. std::nullptr_t
  4894. TypedThreadSafeFunction<ContextType, DataType, CallJs>::EmptyFunctionFactory(
  4895. Napi::Env /*env*/) {
  4896. return nullptr;
  4897. }
  4898. // static
  4899. template <typename ContextType,
  4900. typename DataType,
  4901. void (*CallJs)(Napi::Env, Napi::Function, ContextType*, DataType*)>
  4902. Napi::Function
  4903. TypedThreadSafeFunction<ContextType, DataType, CallJs>::FunctionOrEmpty(
  4904. Napi::Env /*env*/, Napi::Function& callback) {
  4905. return callback;
  4906. }
  4907. #endif
  4908. ////////////////////////////////////////////////////////////////////////////////
  4909. // ThreadSafeFunction class
  4910. ////////////////////////////////////////////////////////////////////////////////
  4911. // static
  4912. template <typename ResourceString>
  4913. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4914. const Function& callback,
  4915. ResourceString resourceName,
  4916. size_t maxQueueSize,
  4917. size_t initialThreadCount) {
  4918. return New(
  4919. env, callback, Object(), resourceName, maxQueueSize, initialThreadCount);
  4920. }
  4921. // static
  4922. template <typename ResourceString, typename ContextType>
  4923. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4924. const Function& callback,
  4925. ResourceString resourceName,
  4926. size_t maxQueueSize,
  4927. size_t initialThreadCount,
  4928. ContextType* context) {
  4929. return New(env,
  4930. callback,
  4931. Object(),
  4932. resourceName,
  4933. maxQueueSize,
  4934. initialThreadCount,
  4935. context);
  4936. }
  4937. // static
  4938. template <typename ResourceString, typename Finalizer>
  4939. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4940. const Function& callback,
  4941. ResourceString resourceName,
  4942. size_t maxQueueSize,
  4943. size_t initialThreadCount,
  4944. Finalizer finalizeCallback) {
  4945. return New(env,
  4946. callback,
  4947. Object(),
  4948. resourceName,
  4949. maxQueueSize,
  4950. initialThreadCount,
  4951. finalizeCallback);
  4952. }
  4953. // static
  4954. template <typename ResourceString,
  4955. typename Finalizer,
  4956. typename FinalizerDataType>
  4957. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4958. const Function& callback,
  4959. ResourceString resourceName,
  4960. size_t maxQueueSize,
  4961. size_t initialThreadCount,
  4962. Finalizer finalizeCallback,
  4963. FinalizerDataType* data) {
  4964. return New(env,
  4965. callback,
  4966. Object(),
  4967. resourceName,
  4968. maxQueueSize,
  4969. initialThreadCount,
  4970. finalizeCallback,
  4971. data);
  4972. }
  4973. // static
  4974. template <typename ResourceString, typename ContextType, typename Finalizer>
  4975. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4976. const Function& callback,
  4977. ResourceString resourceName,
  4978. size_t maxQueueSize,
  4979. size_t initialThreadCount,
  4980. ContextType* context,
  4981. Finalizer finalizeCallback) {
  4982. return New(env,
  4983. callback,
  4984. Object(),
  4985. resourceName,
  4986. maxQueueSize,
  4987. initialThreadCount,
  4988. context,
  4989. finalizeCallback);
  4990. }
  4991. // static
  4992. template <typename ResourceString,
  4993. typename ContextType,
  4994. typename Finalizer,
  4995. typename FinalizerDataType>
  4996. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  4997. const Function& callback,
  4998. ResourceString resourceName,
  4999. size_t maxQueueSize,
  5000. size_t initialThreadCount,
  5001. ContextType* context,
  5002. Finalizer finalizeCallback,
  5003. FinalizerDataType* data) {
  5004. return New(env,
  5005. callback,
  5006. Object(),
  5007. resourceName,
  5008. maxQueueSize,
  5009. initialThreadCount,
  5010. context,
  5011. finalizeCallback,
  5012. data);
  5013. }
  5014. // static
  5015. template <typename ResourceString>
  5016. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  5017. const Function& callback,
  5018. const Object& resource,
  5019. ResourceString resourceName,
  5020. size_t maxQueueSize,
  5021. size_t initialThreadCount) {
  5022. return New(env,
  5023. callback,
  5024. resource,
  5025. resourceName,
  5026. maxQueueSize,
  5027. initialThreadCount,
  5028. static_cast<void*>(nullptr) /* context */);
  5029. }
  5030. // static
  5031. template <typename ResourceString, typename ContextType>
  5032. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  5033. const Function& callback,
  5034. const Object& resource,
  5035. ResourceString resourceName,
  5036. size_t maxQueueSize,
  5037. size_t initialThreadCount,
  5038. ContextType* context) {
  5039. return New(env,
  5040. callback,
  5041. resource,
  5042. resourceName,
  5043. maxQueueSize,
  5044. initialThreadCount,
  5045. context,
  5046. [](Env, ContextType*) {} /* empty finalizer */);
  5047. }
  5048. // static
  5049. template <typename ResourceString, typename Finalizer>
  5050. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  5051. const Function& callback,
  5052. const Object& resource,
  5053. ResourceString resourceName,
  5054. size_t maxQueueSize,
  5055. size_t initialThreadCount,
  5056. Finalizer finalizeCallback) {
  5057. return New(env,
  5058. callback,
  5059. resource,
  5060. resourceName,
  5061. maxQueueSize,
  5062. initialThreadCount,
  5063. static_cast<void*>(nullptr) /* context */,
  5064. finalizeCallback,
  5065. static_cast<void*>(nullptr) /* data */,
  5066. details::ThreadSafeFinalize<void, Finalizer>::Wrapper);
  5067. }
  5068. // static
  5069. template <typename ResourceString,
  5070. typename Finalizer,
  5071. typename FinalizerDataType>
  5072. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  5073. const Function& callback,
  5074. const Object& resource,
  5075. ResourceString resourceName,
  5076. size_t maxQueueSize,
  5077. size_t initialThreadCount,
  5078. Finalizer finalizeCallback,
  5079. FinalizerDataType* data) {
  5080. return New(env,
  5081. callback,
  5082. resource,
  5083. resourceName,
  5084. maxQueueSize,
  5085. initialThreadCount,
  5086. static_cast<void*>(nullptr) /* context */,
  5087. finalizeCallback,
  5088. data,
  5089. details::ThreadSafeFinalize<void, Finalizer, FinalizerDataType>::
  5090. FinalizeWrapperWithData);
  5091. }
  5092. // static
  5093. template <typename ResourceString, typename ContextType, typename Finalizer>
  5094. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  5095. const Function& callback,
  5096. const Object& resource,
  5097. ResourceString resourceName,
  5098. size_t maxQueueSize,
  5099. size_t initialThreadCount,
  5100. ContextType* context,
  5101. Finalizer finalizeCallback) {
  5102. return New(
  5103. env,
  5104. callback,
  5105. resource,
  5106. resourceName,
  5107. maxQueueSize,
  5108. initialThreadCount,
  5109. context,
  5110. finalizeCallback,
  5111. static_cast<void*>(nullptr) /* data */,
  5112. details::ThreadSafeFinalize<ContextType,
  5113. Finalizer>::FinalizeWrapperWithContext);
  5114. }
  5115. // static
  5116. template <typename ResourceString,
  5117. typename ContextType,
  5118. typename Finalizer,
  5119. typename FinalizerDataType>
  5120. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  5121. const Function& callback,
  5122. const Object& resource,
  5123. ResourceString resourceName,
  5124. size_t maxQueueSize,
  5125. size_t initialThreadCount,
  5126. ContextType* context,
  5127. Finalizer finalizeCallback,
  5128. FinalizerDataType* data) {
  5129. return New(
  5130. env,
  5131. callback,
  5132. resource,
  5133. resourceName,
  5134. maxQueueSize,
  5135. initialThreadCount,
  5136. context,
  5137. finalizeCallback,
  5138. data,
  5139. details::ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>::
  5140. FinalizeFinalizeWrapperWithDataAndContext);
  5141. }
  5142. inline ThreadSafeFunction::ThreadSafeFunction() : _tsfn() {}
  5143. inline ThreadSafeFunction::ThreadSafeFunction(napi_threadsafe_function tsfn)
  5144. : _tsfn(tsfn) {}
  5145. inline ThreadSafeFunction::operator napi_threadsafe_function() const {
  5146. return _tsfn;
  5147. }
  5148. inline napi_status ThreadSafeFunction::BlockingCall() const {
  5149. return CallInternal(nullptr, napi_tsfn_blocking);
  5150. }
  5151. template <>
  5152. inline napi_status ThreadSafeFunction::BlockingCall(void* data) const {
  5153. return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking);
  5154. }
  5155. template <typename Callback>
  5156. inline napi_status ThreadSafeFunction::BlockingCall(Callback callback) const {
  5157. return CallInternal(new CallbackWrapper(callback), napi_tsfn_blocking);
  5158. }
  5159. template <typename DataType, typename Callback>
  5160. inline napi_status ThreadSafeFunction::BlockingCall(DataType* data,
  5161. Callback callback) const {
  5162. auto wrapper = [data, callback](Env env, Function jsCallback) {
  5163. callback(env, jsCallback, data);
  5164. };
  5165. return CallInternal(new CallbackWrapper(wrapper), napi_tsfn_blocking);
  5166. }
  5167. inline napi_status ThreadSafeFunction::NonBlockingCall() const {
  5168. return CallInternal(nullptr, napi_tsfn_nonblocking);
  5169. }
  5170. template <>
  5171. inline napi_status ThreadSafeFunction::NonBlockingCall(void* data) const {
  5172. return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking);
  5173. }
  5174. template <typename Callback>
  5175. inline napi_status ThreadSafeFunction::NonBlockingCall(
  5176. Callback callback) const {
  5177. return CallInternal(new CallbackWrapper(callback), napi_tsfn_nonblocking);
  5178. }
  5179. template <typename DataType, typename Callback>
  5180. inline napi_status ThreadSafeFunction::NonBlockingCall(
  5181. DataType* data, Callback callback) const {
  5182. auto wrapper = [data, callback](Env env, Function jsCallback) {
  5183. callback(env, jsCallback, data);
  5184. };
  5185. return CallInternal(new CallbackWrapper(wrapper), napi_tsfn_nonblocking);
  5186. }
  5187. inline void ThreadSafeFunction::Ref(napi_env env) const {
  5188. if (_tsfn != nullptr) {
  5189. napi_status status = napi_ref_threadsafe_function(env, _tsfn);
  5190. NAPI_THROW_IF_FAILED_VOID(env, status);
  5191. }
  5192. }
  5193. inline void ThreadSafeFunction::Unref(napi_env env) const {
  5194. if (_tsfn != nullptr) {
  5195. napi_status status = napi_unref_threadsafe_function(env, _tsfn);
  5196. NAPI_THROW_IF_FAILED_VOID(env, status);
  5197. }
  5198. }
  5199. inline napi_status ThreadSafeFunction::Acquire() const {
  5200. return napi_acquire_threadsafe_function(_tsfn);
  5201. }
  5202. inline napi_status ThreadSafeFunction::Release() const {
  5203. return napi_release_threadsafe_function(_tsfn, napi_tsfn_release);
  5204. }
  5205. inline napi_status ThreadSafeFunction::Abort() const {
  5206. return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort);
  5207. }
  5208. inline ThreadSafeFunction::ConvertibleContext ThreadSafeFunction::GetContext()
  5209. const {
  5210. void* context;
  5211. napi_status status = napi_get_threadsafe_function_context(_tsfn, &context);
  5212. NAPI_FATAL_IF_FAILED(status,
  5213. "ThreadSafeFunction::GetContext",
  5214. "napi_get_threadsafe_function_context");
  5215. return ConvertibleContext({context});
  5216. }
  5217. // static
  5218. template <typename ResourceString,
  5219. typename ContextType,
  5220. typename Finalizer,
  5221. typename FinalizerDataType>
  5222. inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env,
  5223. const Function& callback,
  5224. const Object& resource,
  5225. ResourceString resourceName,
  5226. size_t maxQueueSize,
  5227. size_t initialThreadCount,
  5228. ContextType* context,
  5229. Finalizer finalizeCallback,
  5230. FinalizerDataType* data,
  5231. napi_finalize wrapper) {
  5232. static_assert(details::can_make_string<ResourceString>::value ||
  5233. std::is_convertible<ResourceString, napi_value>::value,
  5234. "Resource name should be convertible to the string type");
  5235. ThreadSafeFunction tsfn;
  5236. auto* finalizeData = new details::
  5237. ThreadSafeFinalize<ContextType, Finalizer, FinalizerDataType>(
  5238. {data, finalizeCallback});
  5239. napi_status status =
  5240. napi_create_threadsafe_function(env,
  5241. callback,
  5242. resource,
  5243. Value::From(env, resourceName),
  5244. maxQueueSize,
  5245. initialThreadCount,
  5246. finalizeData,
  5247. wrapper,
  5248. context,
  5249. CallJS,
  5250. &tsfn._tsfn);
  5251. if (status != napi_ok) {
  5252. delete finalizeData;
  5253. NAPI_THROW_IF_FAILED(env, status, ThreadSafeFunction());
  5254. }
  5255. return tsfn;
  5256. }
  5257. inline napi_status ThreadSafeFunction::CallInternal(
  5258. CallbackWrapper* callbackWrapper,
  5259. napi_threadsafe_function_call_mode mode) const {
  5260. napi_status status =
  5261. napi_call_threadsafe_function(_tsfn, callbackWrapper, mode);
  5262. if (status != napi_ok && callbackWrapper != nullptr) {
  5263. delete callbackWrapper;
  5264. }
  5265. return status;
  5266. }
  5267. // static
  5268. inline void ThreadSafeFunction::CallJS(napi_env env,
  5269. napi_value jsCallback,
  5270. void* /* context */,
  5271. void* data) {
  5272. if (env == nullptr && jsCallback == nullptr) {
  5273. return;
  5274. }
  5275. if (data != nullptr) {
  5276. auto* callbackWrapper = static_cast<CallbackWrapper*>(data);
  5277. (*callbackWrapper)(env, Function(env, jsCallback));
  5278. delete callbackWrapper;
  5279. } else if (jsCallback != nullptr) {
  5280. Function(env, jsCallback).Call({});
  5281. }
  5282. }
  5283. ////////////////////////////////////////////////////////////////////////////////
  5284. // Async Progress Worker Base class
  5285. ////////////////////////////////////////////////////////////////////////////////
  5286. template <typename DataType>
  5287. inline AsyncProgressWorkerBase<DataType>::AsyncProgressWorkerBase(
  5288. const Object& receiver,
  5289. const Function& callback,
  5290. const char* resource_name,
  5291. const Object& resource,
  5292. size_t queue_size)
  5293. : AsyncWorker(receiver, callback, resource_name, resource) {
  5294. // Fill all possible arguments to work around ambiguous
  5295. // ThreadSafeFunction::New signatures.
  5296. _tsfn = ThreadSafeFunction::New(callback.Env(),
  5297. callback,
  5298. resource,
  5299. resource_name,
  5300. queue_size,
  5301. /** initialThreadCount */ 1,
  5302. /** context */ this,
  5303. OnThreadSafeFunctionFinalize,
  5304. /** finalizeData */ this);
  5305. }
  5306. #if NAPI_VERSION > 4
  5307. template <typename DataType>
  5308. inline AsyncProgressWorkerBase<DataType>::AsyncProgressWorkerBase(
  5309. Napi::Env env,
  5310. const char* resource_name,
  5311. const Object& resource,
  5312. size_t queue_size)
  5313. : AsyncWorker(env, resource_name, resource) {
  5314. // TODO: Once the changes to make the callback optional for threadsafe
  5315. // functions are available on all versions we can remove the dummy Function
  5316. // here.
  5317. Function callback;
  5318. // Fill all possible arguments to work around ambiguous
  5319. // ThreadSafeFunction::New signatures.
  5320. _tsfn = ThreadSafeFunction::New(env,
  5321. callback,
  5322. resource,
  5323. resource_name,
  5324. queue_size,
  5325. /** initialThreadCount */ 1,
  5326. /** context */ this,
  5327. OnThreadSafeFunctionFinalize,
  5328. /** finalizeData */ this);
  5329. }
  5330. #endif
  5331. template <typename DataType>
  5332. inline AsyncProgressWorkerBase<DataType>::~AsyncProgressWorkerBase() {
  5333. // Abort pending tsfn call.
  5334. // Don't send progress events after we've already completed.
  5335. // It's ok to call ThreadSafeFunction::Abort and ThreadSafeFunction::Release
  5336. // duplicated.
  5337. _tsfn.Abort();
  5338. }
  5339. template <typename DataType>
  5340. inline void AsyncProgressWorkerBase<DataType>::OnAsyncWorkProgress(
  5341. Napi::Env /* env */, Napi::Function /* jsCallback */, void* data) {
  5342. ThreadSafeData* tsd = static_cast<ThreadSafeData*>(data);
  5343. tsd->asyncprogressworker()->OnWorkProgress(tsd->data());
  5344. delete tsd;
  5345. }
  5346. template <typename DataType>
  5347. inline napi_status AsyncProgressWorkerBase<DataType>::NonBlockingCall(
  5348. DataType* data) {
  5349. auto tsd = new AsyncProgressWorkerBase::ThreadSafeData(this, data);
  5350. auto ret = _tsfn.NonBlockingCall(tsd, OnAsyncWorkProgress);
  5351. if (ret != napi_ok) {
  5352. delete tsd;
  5353. }
  5354. return ret;
  5355. }
  5356. template <typename DataType>
  5357. inline void AsyncProgressWorkerBase<DataType>::OnWorkComplete(
  5358. Napi::Env /* env */, napi_status status) {
  5359. _work_completed = true;
  5360. _complete_status = status;
  5361. _tsfn.Release();
  5362. }
  5363. template <typename DataType>
  5364. inline void AsyncProgressWorkerBase<DataType>::OnThreadSafeFunctionFinalize(
  5365. Napi::Env env, void* /* data */, AsyncProgressWorkerBase* context) {
  5366. if (context->_work_completed) {
  5367. context->AsyncWorker::OnWorkComplete(env, context->_complete_status);
  5368. }
  5369. }
  5370. ////////////////////////////////////////////////////////////////////////////////
  5371. // Async Progress Worker class
  5372. ////////////////////////////////////////////////////////////////////////////////
  5373. template <class T>
  5374. inline AsyncProgressWorker<T>::AsyncProgressWorker(const Function& callback)
  5375. : AsyncProgressWorker(callback, "generic") {}
  5376. template <class T>
  5377. inline AsyncProgressWorker<T>::AsyncProgressWorker(const Function& callback,
  5378. const char* resource_name)
  5379. : AsyncProgressWorker(
  5380. callback, resource_name, Object::New(callback.Env())) {}
  5381. template <class T>
  5382. inline AsyncProgressWorker<T>::AsyncProgressWorker(const Function& callback,
  5383. const char* resource_name,
  5384. const Object& resource)
  5385. : AsyncProgressWorker(
  5386. Object::New(callback.Env()), callback, resource_name, resource) {}
  5387. template <class T>
  5388. inline AsyncProgressWorker<T>::AsyncProgressWorker(const Object& receiver,
  5389. const Function& callback)
  5390. : AsyncProgressWorker(receiver, callback, "generic") {}
  5391. template <class T>
  5392. inline AsyncProgressWorker<T>::AsyncProgressWorker(const Object& receiver,
  5393. const Function& callback,
  5394. const char* resource_name)
  5395. : AsyncProgressWorker(
  5396. receiver, callback, resource_name, Object::New(callback.Env())) {}
  5397. template <class T>
  5398. inline AsyncProgressWorker<T>::AsyncProgressWorker(const Object& receiver,
  5399. const Function& callback,
  5400. const char* resource_name,
  5401. const Object& resource)
  5402. : AsyncProgressWorkerBase(receiver, callback, resource_name, resource),
  5403. _asyncdata(nullptr),
  5404. _asyncsize(0),
  5405. _signaled(false) {}
  5406. #if NAPI_VERSION > 4
  5407. template <class T>
  5408. inline AsyncProgressWorker<T>::AsyncProgressWorker(Napi::Env env)
  5409. : AsyncProgressWorker(env, "generic") {}
  5410. template <class T>
  5411. inline AsyncProgressWorker<T>::AsyncProgressWorker(Napi::Env env,
  5412. const char* resource_name)
  5413. : AsyncProgressWorker(env, resource_name, Object::New(env)) {}
  5414. template <class T>
  5415. inline AsyncProgressWorker<T>::AsyncProgressWorker(Napi::Env env,
  5416. const char* resource_name,
  5417. const Object& resource)
  5418. : AsyncProgressWorkerBase(env, resource_name, resource),
  5419. _asyncdata(nullptr),
  5420. _asyncsize(0) {}
  5421. #endif
  5422. template <class T>
  5423. inline AsyncProgressWorker<T>::~AsyncProgressWorker() {
  5424. {
  5425. std::lock_guard<std::mutex> lock(this->_mutex);
  5426. _asyncdata = nullptr;
  5427. _asyncsize = 0;
  5428. }
  5429. }
  5430. template <class T>
  5431. inline void AsyncProgressWorker<T>::Execute() {
  5432. ExecutionProgress progress(this);
  5433. Execute(progress);
  5434. }
  5435. template <class T>
  5436. inline void AsyncProgressWorker<T>::OnWorkProgress(void*) {
  5437. T* data;
  5438. size_t size;
  5439. bool signaled;
  5440. {
  5441. std::lock_guard<std::mutex> lock(this->_mutex);
  5442. data = this->_asyncdata;
  5443. size = this->_asyncsize;
  5444. signaled = this->_signaled;
  5445. this->_asyncdata = nullptr;
  5446. this->_asyncsize = 0;
  5447. this->_signaled = false;
  5448. }
  5449. /**
  5450. * The callback of ThreadSafeFunction is not been invoked immediately on the
  5451. * callback of uv_async_t (uv io poll), rather the callback of TSFN is
  5452. * invoked on the right next uv idle callback. There are chances that during
  5453. * the deferring the signal of uv_async_t is been sent again, i.e. potential
  5454. * not coalesced two calls of the TSFN callback.
  5455. */
  5456. if (data == nullptr && !signaled) {
  5457. return;
  5458. }
  5459. this->OnProgress(data, size);
  5460. delete[] data;
  5461. }
  5462. template <class T>
  5463. inline void AsyncProgressWorker<T>::SendProgress_(const T* data, size_t count) {
  5464. T* new_data = new T[count];
  5465. std::copy(data, data + count, new_data);
  5466. T* old_data;
  5467. {
  5468. std::lock_guard<std::mutex> lock(this->_mutex);
  5469. old_data = _asyncdata;
  5470. _asyncdata = new_data;
  5471. _asyncsize = count;
  5472. _signaled = false;
  5473. }
  5474. this->NonBlockingCall(nullptr);
  5475. delete[] old_data;
  5476. }
  5477. template <class T>
  5478. inline void AsyncProgressWorker<T>::Signal() {
  5479. {
  5480. std::lock_guard<std::mutex> lock(this->_mutex);
  5481. _signaled = true;
  5482. }
  5483. this->NonBlockingCall(static_cast<T*>(nullptr));
  5484. }
  5485. template <class T>
  5486. inline void AsyncProgressWorker<T>::ExecutionProgress::Signal() const {
  5487. this->_worker->Signal();
  5488. }
  5489. template <class T>
  5490. inline void AsyncProgressWorker<T>::ExecutionProgress::Send(
  5491. const T* data, size_t count) const {
  5492. _worker->SendProgress_(data, count);
  5493. }
  5494. ////////////////////////////////////////////////////////////////////////////////
  5495. // Async Progress Queue Worker class
  5496. ////////////////////////////////////////////////////////////////////////////////
  5497. template <class T>
  5498. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5499. const Function& callback)
  5500. : AsyncProgressQueueWorker(callback, "generic") {}
  5501. template <class T>
  5502. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5503. const Function& callback, const char* resource_name)
  5504. : AsyncProgressQueueWorker(
  5505. callback, resource_name, Object::New(callback.Env())) {}
  5506. template <class T>
  5507. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5508. const Function& callback, const char* resource_name, const Object& resource)
  5509. : AsyncProgressQueueWorker(
  5510. Object::New(callback.Env()), callback, resource_name, resource) {}
  5511. template <class T>
  5512. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5513. const Object& receiver, const Function& callback)
  5514. : AsyncProgressQueueWorker(receiver, callback, "generic") {}
  5515. template <class T>
  5516. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5517. const Object& receiver, const Function& callback, const char* resource_name)
  5518. : AsyncProgressQueueWorker(
  5519. receiver, callback, resource_name, Object::New(callback.Env())) {}
  5520. template <class T>
  5521. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5522. const Object& receiver,
  5523. const Function& callback,
  5524. const char* resource_name,
  5525. const Object& resource)
  5526. : AsyncProgressWorkerBase<std::pair<T*, size_t>>(
  5527. receiver,
  5528. callback,
  5529. resource_name,
  5530. resource,
  5531. /** unlimited queue size */ 0) {}
  5532. #if NAPI_VERSION > 4
  5533. template <class T>
  5534. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(Napi::Env env)
  5535. : AsyncProgressQueueWorker(env, "generic") {}
  5536. template <class T>
  5537. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5538. Napi::Env env, const char* resource_name)
  5539. : AsyncProgressQueueWorker(env, resource_name, Object::New(env)) {}
  5540. template <class T>
  5541. inline AsyncProgressQueueWorker<T>::AsyncProgressQueueWorker(
  5542. Napi::Env env, const char* resource_name, const Object& resource)
  5543. : AsyncProgressWorkerBase<std::pair<T*, size_t>>(
  5544. env, resource_name, resource, /** unlimited queue size */ 0) {}
  5545. #endif
  5546. template <class T>
  5547. inline void AsyncProgressQueueWorker<T>::Execute() {
  5548. ExecutionProgress progress(this);
  5549. Execute(progress);
  5550. }
  5551. template <class T>
  5552. inline void AsyncProgressQueueWorker<T>::OnWorkProgress(
  5553. std::pair<T*, size_t>* datapair) {
  5554. if (datapair == nullptr) {
  5555. return;
  5556. }
  5557. T* data = datapair->first;
  5558. size_t size = datapair->second;
  5559. this->OnProgress(data, size);
  5560. delete datapair;
  5561. delete[] data;
  5562. }
  5563. template <class T>
  5564. inline void AsyncProgressQueueWorker<T>::SendProgress_(const T* data,
  5565. size_t count) {
  5566. T* new_data = new T[count];
  5567. std::copy(data, data + count, new_data);
  5568. auto pair = new std::pair<T*, size_t>(new_data, count);
  5569. this->NonBlockingCall(pair);
  5570. }
  5571. template <class T>
  5572. inline void AsyncProgressQueueWorker<T>::Signal() const {
  5573. this->SendProgress_(static_cast<T*>(nullptr), 0);
  5574. }
  5575. template <class T>
  5576. inline void AsyncProgressQueueWorker<T>::OnWorkComplete(Napi::Env env,
  5577. napi_status status) {
  5578. // Draining queued items in TSFN.
  5579. AsyncProgressWorkerBase<std::pair<T*, size_t>>::OnWorkComplete(env, status);
  5580. }
  5581. template <class T>
  5582. inline void AsyncProgressQueueWorker<T>::ExecutionProgress::Signal() const {
  5583. _worker->SendProgress_(static_cast<T*>(nullptr), 0);
  5584. }
  5585. template <class T>
  5586. inline void AsyncProgressQueueWorker<T>::ExecutionProgress::Send(
  5587. const T* data, size_t count) const {
  5588. _worker->SendProgress_(data, count);
  5589. }
  5590. #endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS
  5591. ////////////////////////////////////////////////////////////////////////////////
  5592. // Memory Management class
  5593. ////////////////////////////////////////////////////////////////////////////////
  5594. inline int64_t MemoryManagement::AdjustExternalMemory(Env env,
  5595. int64_t change_in_bytes) {
  5596. int64_t result;
  5597. napi_status status =
  5598. napi_adjust_external_memory(env, change_in_bytes, &result);
  5599. NAPI_THROW_IF_FAILED(env, status, 0);
  5600. return result;
  5601. }
  5602. ////////////////////////////////////////////////////////////////////////////////
  5603. // Version Management class
  5604. ////////////////////////////////////////////////////////////////////////////////
  5605. inline uint32_t VersionManagement::GetNapiVersion(Env env) {
  5606. uint32_t result;
  5607. napi_status status = napi_get_version(env, &result);
  5608. NAPI_THROW_IF_FAILED(env, status, 0);
  5609. return result;
  5610. }
  5611. inline const napi_node_version* VersionManagement::GetNodeVersion(Env env) {
  5612. const napi_node_version* result;
  5613. napi_status status = napi_get_node_version(env, &result);
  5614. NAPI_THROW_IF_FAILED(env, status, 0);
  5615. return result;
  5616. }
  5617. #if NAPI_VERSION > 5
  5618. ////////////////////////////////////////////////////////////////////////////////
  5619. // Addon<T> class
  5620. ////////////////////////////////////////////////////////////////////////////////
  5621. template <typename T>
  5622. inline Object Addon<T>::Init(Env env, Object exports) {
  5623. T* addon = new T(env, exports);
  5624. env.SetInstanceData(addon);
  5625. return addon->entry_point_;
  5626. }
  5627. template <typename T>
  5628. inline T* Addon<T>::Unwrap(Object wrapper) {
  5629. return wrapper.Env().GetInstanceData<T>();
  5630. }
  5631. template <typename T>
  5632. inline void Addon<T>::DefineAddon(
  5633. Object exports, const std::initializer_list<AddonProp>& props) {
  5634. DefineProperties(exports, props);
  5635. entry_point_ = exports;
  5636. }
  5637. template <typename T>
  5638. inline Napi::Object Addon<T>::DefineProperties(
  5639. Object object, const std::initializer_list<AddonProp>& props) {
  5640. const napi_property_descriptor* properties =
  5641. reinterpret_cast<const napi_property_descriptor*>(props.begin());
  5642. size_t size = props.size();
  5643. napi_status status =
  5644. napi_define_properties(object.Env(), object, size, properties);
  5645. NAPI_THROW_IF_FAILED(object.Env(), status, object);
  5646. for (size_t idx = 0; idx < size; idx++)
  5647. T::AttachPropData(object.Env(), object, &properties[idx]);
  5648. return object;
  5649. }
  5650. #endif // NAPI_VERSION > 5
  5651. #if NAPI_VERSION > 2
  5652. template <typename Hook, typename Arg>
  5653. Env::CleanupHook<Hook, Arg> Env::AddCleanupHook(Hook hook, Arg* arg) {
  5654. return CleanupHook<Hook, Arg>(*this, hook, arg);
  5655. }
  5656. template <typename Hook>
  5657. Env::CleanupHook<Hook> Env::AddCleanupHook(Hook hook) {
  5658. return CleanupHook<Hook>(*this, hook);
  5659. }
  5660. template <typename Hook, typename Arg>
  5661. Env::CleanupHook<Hook, Arg>::CleanupHook() {
  5662. data = nullptr;
  5663. }
  5664. template <typename Hook, typename Arg>
  5665. Env::CleanupHook<Hook, Arg>::CleanupHook(Napi::Env env, Hook hook)
  5666. : wrapper(Env::CleanupHook<Hook, Arg>::Wrapper) {
  5667. data = new CleanupData{std::move(hook), nullptr};
  5668. napi_status status = napi_add_env_cleanup_hook(env, wrapper, data);
  5669. if (status != napi_ok) {
  5670. delete data;
  5671. data = nullptr;
  5672. }
  5673. }
  5674. template <typename Hook, typename Arg>
  5675. Env::CleanupHook<Hook, Arg>::CleanupHook(Napi::Env env, Hook hook, Arg* arg)
  5676. : wrapper(Env::CleanupHook<Hook, Arg>::WrapperWithArg) {
  5677. data = new CleanupData{std::move(hook), arg};
  5678. napi_status status = napi_add_env_cleanup_hook(env, wrapper, data);
  5679. if (status != napi_ok) {
  5680. delete data;
  5681. data = nullptr;
  5682. }
  5683. }
  5684. template <class Hook, class Arg>
  5685. bool Env::CleanupHook<Hook, Arg>::Remove(Env env) {
  5686. napi_status status = napi_remove_env_cleanup_hook(env, wrapper, data);
  5687. delete data;
  5688. data = nullptr;
  5689. return status == napi_ok;
  5690. }
  5691. template <class Hook, class Arg>
  5692. bool Env::CleanupHook<Hook, Arg>::IsEmpty() const {
  5693. return data == nullptr;
  5694. }
  5695. #endif // NAPI_VERSION > 2
  5696. #ifdef NAPI_CPP_CUSTOM_NAMESPACE
  5697. } // namespace NAPI_CPP_CUSTOM_NAMESPACE
  5698. #endif
  5699. } // namespace Napi
  5700. #endif // SRC_NAPI_INL_H_