lib.deno.d.ts 551 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249
  1. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  2. /// <reference no-default-lib="true" />
  3. /// <reference lib="esnext" />
  4. /// <reference lib="deno.net" />
  5. /** Deno provides extra properties on `import.meta`. These are included here
  6. * to ensure that these are still available when using the Deno namespace in
  7. * conjunction with other type libs, like `dom`.
  8. *
  9. * @category Platform
  10. */
  11. declare interface ImportMeta {
  12. /** A string representation of the fully qualified module URL. When the
  13. * module is loaded locally, the value will be a file URL (e.g.
  14. * `file:///path/module.ts`).
  15. *
  16. * You can also parse the string as a URL to determine more information about
  17. * how the current module was loaded. For example to determine if a module was
  18. * local or not:
  19. *
  20. * ```ts
  21. * const url = new URL(import.meta.url);
  22. * if (url.protocol === "file:") {
  23. * console.log("this module was loaded locally");
  24. * }
  25. * ```
  26. */
  27. url: string;
  28. /** The absolute path of the current module.
  29. *
  30. * This property is only provided for local modules (ie. using `file://` URLs).
  31. *
  32. * Example:
  33. * ```
  34. * // Unix
  35. * console.log(import.meta.filename); // /home/alice/my_module.ts
  36. *
  37. * // Windows
  38. * console.log(import.meta.filename); // C:\alice\my_module.ts
  39. * ```
  40. */
  41. filename?: string;
  42. /** The absolute path of the directory containing the current module.
  43. *
  44. * This property is only provided for local modules (ie. using `file://` URLs).
  45. *
  46. * * Example:
  47. * ```
  48. * // Unix
  49. * console.log(import.meta.dirname); // /home/alice
  50. *
  51. * // Windows
  52. * console.log(import.meta.dirname); // C:\alice
  53. * ```
  54. */
  55. dirname?: string;
  56. /** A flag that indicates if the current module is the main module that was
  57. * called when starting the program under Deno.
  58. *
  59. * ```ts
  60. * if (import.meta.main) {
  61. * // this was loaded as the main module, maybe do some bootstrapping
  62. * }
  63. * ```
  64. */
  65. main: boolean;
  66. /** A function that returns resolved specifier as if it would be imported
  67. * using `import(specifier)`.
  68. *
  69. * ```ts
  70. * console.log(import.meta.resolve("./foo.js"));
  71. * // file:///dev/foo.js
  72. * ```
  73. */
  74. resolve(specifier: string): string;
  75. }
  76. /** Deno supports [User Timing Level 3](https://w3c.github.io/user-timing)
  77. * which is not widely supported yet in other runtimes.
  78. *
  79. * Check out the
  80. * [Performance API](https://developer.mozilla.org/en-US/docs/Web/API/Performance)
  81. * documentation on MDN for further information about how to use the API.
  82. *
  83. * @category Performance
  84. */
  85. declare interface Performance {
  86. /** Stores a timestamp with the associated name (a "mark"). */
  87. mark(markName: string, options?: PerformanceMarkOptions): PerformanceMark;
  88. /** Stores the `DOMHighResTimeStamp` duration between two marks along with the
  89. * associated name (a "measure"). */
  90. measure(
  91. measureName: string,
  92. options?: PerformanceMeasureOptions,
  93. ): PerformanceMeasure;
  94. }
  95. /**
  96. * Options which are used in conjunction with `performance.mark`. Check out the
  97. * MDN
  98. * [`performance.mark()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark#markoptions)
  99. * documentation for more details.
  100. *
  101. * @category Performance
  102. */
  103. declare interface PerformanceMarkOptions {
  104. /** Metadata to be included in the mark. */
  105. // deno-lint-ignore no-explicit-any
  106. detail?: any;
  107. /** Timestamp to be used as the mark time. */
  108. startTime?: number;
  109. }
  110. /**
  111. * Options which are used in conjunction with `performance.measure`. Check out the
  112. * MDN
  113. * [`performance.mark()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/measure#measureoptions)
  114. * documentation for more details.
  115. *
  116. * @category Performance
  117. */
  118. declare interface PerformanceMeasureOptions {
  119. /** Metadata to be included in the measure. */
  120. // deno-lint-ignore no-explicit-any
  121. detail?: any;
  122. /** Timestamp to be used as the start time or string to be used as start
  123. * mark. */
  124. start?: string | number;
  125. /** Duration between the start and end times. */
  126. duration?: number;
  127. /** Timestamp to be used as the end time or string to be used as end mark. */
  128. end?: string | number;
  129. }
  130. /** The global namespace where Deno specific, non-standard APIs are located. */
  131. declare namespace Deno {
  132. /** A set of error constructors that are raised by Deno APIs.
  133. *
  134. * Can be used to provide more specific handling of failures within code
  135. * which is using Deno APIs. For example, handling attempting to open a file
  136. * which does not exist:
  137. *
  138. * ```ts
  139. * try {
  140. * const file = await Deno.open("./some/file.txt");
  141. * } catch (error) {
  142. * if (error instanceof Deno.errors.NotFound) {
  143. * console.error("the file was not found");
  144. * } else {
  145. * // otherwise re-throw
  146. * throw error;
  147. * }
  148. * }
  149. * ```
  150. *
  151. * @category Errors
  152. */
  153. export namespace errors {
  154. /**
  155. * Raised when the underlying operating system indicates that the file
  156. * was not found.
  157. *
  158. * @category Errors */
  159. export class NotFound extends Error {}
  160. /**
  161. * Raised when the underlying operating system indicates the current user
  162. * which the Deno process is running under does not have the appropriate
  163. * permissions to a file or resource, or the user _did not_ provide required
  164. * `--allow-*` flag.
  165. *
  166. * @category Errors */
  167. export class PermissionDenied extends Error {}
  168. /**
  169. * Raised when the underlying operating system reports that a connection to
  170. * a resource is refused.
  171. *
  172. * @category Errors */
  173. export class ConnectionRefused extends Error {}
  174. /**
  175. * Raised when the underlying operating system reports that a connection has
  176. * been reset. With network servers, it can be a _normal_ occurrence where a
  177. * client will abort a connection instead of properly shutting it down.
  178. *
  179. * @category Errors */
  180. export class ConnectionReset extends Error {}
  181. /**
  182. * Raised when the underlying operating system reports an `ECONNABORTED`
  183. * error.
  184. *
  185. * @category Errors */
  186. export class ConnectionAborted extends Error {}
  187. /**
  188. * Raised when the underlying operating system reports an `ENOTCONN` error.
  189. *
  190. * @category Errors */
  191. export class NotConnected extends Error {}
  192. /**
  193. * Raised when attempting to open a server listener on an address and port
  194. * that already has a listener.
  195. *
  196. * @category Errors */
  197. export class AddrInUse extends Error {}
  198. /**
  199. * Raised when the underlying operating system reports an `EADDRNOTAVAIL`
  200. * error.
  201. *
  202. * @category Errors */
  203. export class AddrNotAvailable extends Error {}
  204. /**
  205. * Raised when trying to write to a resource and a broken pipe error occurs.
  206. * This can happen when trying to write directly to `stdout` or `stderr`
  207. * and the operating system is unable to pipe the output for a reason
  208. * external to the Deno runtime.
  209. *
  210. * @category Errors */
  211. export class BrokenPipe extends Error {}
  212. /**
  213. * Raised when trying to create a resource, like a file, that already
  214. * exits.
  215. *
  216. * @category Errors */
  217. export class AlreadyExists extends Error {}
  218. /**
  219. * Raised when an operation to returns data that is invalid for the
  220. * operation being performed.
  221. *
  222. * @category Errors */
  223. export class InvalidData extends Error {}
  224. /**
  225. * Raised when the underlying operating system reports that an I/O operation
  226. * has timed out (`ETIMEDOUT`).
  227. *
  228. * @category Errors */
  229. export class TimedOut extends Error {}
  230. /**
  231. * Raised when the underlying operating system reports an `EINTR` error. In
  232. * many cases, this underlying IO error will be handled internally within
  233. * Deno, or result in an @{link BadResource} error instead.
  234. *
  235. * @category Errors */
  236. export class Interrupted extends Error {}
  237. /**
  238. * Raised when the underlying operating system would need to block to
  239. * complete but an asynchronous (non-blocking) API is used.
  240. *
  241. * @category Errors */
  242. export class WouldBlock extends Error {}
  243. /**
  244. * Raised when expecting to write to a IO buffer resulted in zero bytes
  245. * being written.
  246. *
  247. * @category Errors */
  248. export class WriteZero extends Error {}
  249. /**
  250. * Raised when attempting to read bytes from a resource, but the EOF was
  251. * unexpectedly encountered.
  252. *
  253. * @category Errors */
  254. export class UnexpectedEof extends Error {}
  255. /**
  256. * The underlying IO resource is invalid or closed, and so the operation
  257. * could not be performed.
  258. *
  259. * @category Errors */
  260. export class BadResource extends Error {}
  261. /**
  262. * Raised in situations where when attempting to load a dynamic import,
  263. * too many redirects were encountered.
  264. *
  265. * @category Errors */
  266. export class Http extends Error {}
  267. /**
  268. * Raised when the underlying IO resource is not available because it is
  269. * being awaited on in another block of code.
  270. *
  271. * @category Errors */
  272. export class Busy extends Error {}
  273. /**
  274. * Raised when the underlying Deno API is asked to perform a function that
  275. * is not currently supported.
  276. *
  277. * @category Errors */
  278. export class NotSupported extends Error {}
  279. /**
  280. * Raised when too many symbolic links were encountered when resolving the
  281. * filename.
  282. *
  283. * @category Errors */
  284. export class FilesystemLoop extends Error {}
  285. /**
  286. * Raised when trying to open, create or write to a directory.
  287. *
  288. * @category Errors */
  289. export class IsADirectory extends Error {}
  290. /**
  291. * Raised when performing a socket operation but the remote host is
  292. * not reachable.
  293. *
  294. * @category Errors */
  295. export class NetworkUnreachable extends Error {}
  296. /**
  297. * Raised when trying to perform an operation on a path that is not a
  298. * directory, when directory is required.
  299. *
  300. * @category Errors */
  301. export class NotADirectory extends Error {}
  302. }
  303. /** The current process ID of this instance of the Deno CLI.
  304. *
  305. * ```ts
  306. * console.log(Deno.pid);
  307. * ```
  308. *
  309. * @category Runtime
  310. */
  311. export const pid: number;
  312. /**
  313. * The process ID of parent process of this instance of the Deno CLI.
  314. *
  315. * ```ts
  316. * console.log(Deno.ppid);
  317. * ```
  318. *
  319. * @category Runtime
  320. */
  321. export const ppid: number;
  322. /** @category Runtime */
  323. export interface MemoryUsage {
  324. /** The number of bytes of the current Deno's process resident set size,
  325. * which is the amount of memory occupied in main memory (RAM). */
  326. rss: number;
  327. /** The total size of the heap for V8, in bytes. */
  328. heapTotal: number;
  329. /** The amount of the heap used for V8, in bytes. */
  330. heapUsed: number;
  331. /** Memory, in bytes, associated with JavaScript objects outside of the
  332. * JavaScript isolate. */
  333. external: number;
  334. }
  335. /**
  336. * Returns an object describing the memory usage of the Deno process and the
  337. * V8 subsystem measured in bytes.
  338. *
  339. * @category Runtime
  340. */
  341. export function memoryUsage(): MemoryUsage;
  342. /**
  343. * Get the `hostname` of the machine the Deno process is running on.
  344. *
  345. * ```ts
  346. * console.log(Deno.hostname());
  347. * ```
  348. *
  349. * Requires `allow-sys` permission.
  350. *
  351. * @tags allow-sys
  352. * @category Runtime
  353. */
  354. export function hostname(): string;
  355. /**
  356. * Returns an array containing the 1, 5, and 15 minute load averages. The
  357. * load average is a measure of CPU and IO utilization of the last one, five,
  358. * and 15 minute periods expressed as a fractional number. Zero means there
  359. * is no load. On Windows, the three values are always the same and represent
  360. * the current load, not the 1, 5 and 15 minute load averages.
  361. *
  362. * ```ts
  363. * console.log(Deno.loadavg()); // e.g. [ 0.71, 0.44, 0.44 ]
  364. * ```
  365. *
  366. * Requires `allow-sys` permission.
  367. *
  368. * On Windows there is no API available to retrieve this information and this method returns `[ 0, 0, 0 ]`.
  369. *
  370. * @tags allow-sys
  371. * @category Runtime
  372. */
  373. export function loadavg(): number[];
  374. /**
  375. * The information for a network interface returned from a call to
  376. * {@linkcode Deno.networkInterfaces}.
  377. *
  378. * @category Network
  379. */
  380. export interface NetworkInterfaceInfo {
  381. /** The network interface name. */
  382. name: string;
  383. /** The IP protocol version. */
  384. family: "IPv4" | "IPv6";
  385. /** The IP address bound to the interface. */
  386. address: string;
  387. /** The netmask applied to the interface. */
  388. netmask: string;
  389. /** The IPv6 scope id or `null`. */
  390. scopeid: number | null;
  391. /** The CIDR range. */
  392. cidr: string;
  393. /** The MAC address. */
  394. mac: string;
  395. }
  396. /**
  397. * Returns an array of the network interface information.
  398. *
  399. * ```ts
  400. * console.log(Deno.networkInterfaces());
  401. * ```
  402. *
  403. * Requires `allow-sys` permission.
  404. *
  405. * @tags allow-sys
  406. * @category Network
  407. */
  408. export function networkInterfaces(): NetworkInterfaceInfo[];
  409. /**
  410. * Displays the total amount of free and used physical and swap memory in the
  411. * system, as well as the buffers and caches used by the kernel.
  412. *
  413. * This is similar to the `free` command in Linux
  414. *
  415. * ```ts
  416. * console.log(Deno.systemMemoryInfo());
  417. * ```
  418. *
  419. * Requires `allow-sys` permission.
  420. *
  421. * @tags allow-sys
  422. * @category Runtime
  423. */
  424. export function systemMemoryInfo(): SystemMemoryInfo;
  425. /**
  426. * Information returned from a call to {@linkcode Deno.systemMemoryInfo}.
  427. *
  428. * @category Runtime
  429. */
  430. export interface SystemMemoryInfo {
  431. /** Total installed memory in bytes. */
  432. total: number;
  433. /** Unused memory in bytes. */
  434. free: number;
  435. /** Estimation of how much memory, in bytes, is available for starting new
  436. * applications, without swapping. Unlike the data provided by the cache or
  437. * free fields, this field takes into account page cache and also that not
  438. * all reclaimable memory will be reclaimed due to items being in use.
  439. */
  440. available: number;
  441. /** Memory used by kernel buffers. */
  442. buffers: number;
  443. /** Memory used by the page cache and slabs. */
  444. cached: number;
  445. /** Total swap memory. */
  446. swapTotal: number;
  447. /** Unused swap memory. */
  448. swapFree: number;
  449. }
  450. /** Reflects the `NO_COLOR` environment variable at program start.
  451. *
  452. * When the value is `true`, the Deno CLI will attempt to not send color codes
  453. * to `stderr` or `stdout` and other command line programs should also attempt
  454. * to respect this value.
  455. *
  456. * See: https://no-color.org/
  457. *
  458. * @category Runtime
  459. */
  460. export const noColor: boolean;
  461. /**
  462. * Returns the release version of the Operating System.
  463. *
  464. * ```ts
  465. * console.log(Deno.osRelease());
  466. * ```
  467. *
  468. * Requires `allow-sys` permission.
  469. * Under consideration to possibly move to Deno.build or Deno.versions and if
  470. * it should depend sys-info, which may not be desirable.
  471. *
  472. * @tags allow-sys
  473. * @category Runtime
  474. */
  475. export function osRelease(): string;
  476. /**
  477. * Returns the Operating System uptime in number of seconds.
  478. *
  479. * ```ts
  480. * console.log(Deno.osUptime());
  481. * ```
  482. *
  483. * Requires `allow-sys` permission.
  484. *
  485. * @tags allow-sys
  486. * @category Runtime
  487. */
  488. export function osUptime(): number;
  489. /**
  490. * Options which define the permissions within a test or worker context.
  491. *
  492. * `"inherit"` ensures that all permissions of the parent process will be
  493. * applied to the test context. `"none"` ensures the test context has no
  494. * permissions. A `PermissionOptionsObject` provides a more specific
  495. * set of permissions to the test context.
  496. *
  497. * @category Permissions */
  498. export type PermissionOptions =
  499. | "inherit"
  500. | "none"
  501. | PermissionOptionsObject;
  502. /**
  503. * A set of options which can define the permissions within a test or worker
  504. * context at a highly specific level.
  505. *
  506. * @category Permissions */
  507. export interface PermissionOptionsObject {
  508. /** Specifies if the `env` permission should be requested or revoked.
  509. * If set to `"inherit"`, the current `env` permission will be inherited.
  510. * If set to `true`, the global `env` permission will be requested.
  511. * If set to `false`, the global `env` permission will be revoked.
  512. *
  513. * @default {false}
  514. */
  515. env?: "inherit" | boolean | string[];
  516. /** Specifies if the `sys` permission should be requested or revoked.
  517. * If set to `"inherit"`, the current `sys` permission will be inherited.
  518. * If set to `true`, the global `sys` permission will be requested.
  519. * If set to `false`, the global `sys` permission will be revoked.
  520. *
  521. * @default {false}
  522. */
  523. sys?: "inherit" | boolean | string[];
  524. /** Specifies if the `hrtime` permission should be requested or revoked.
  525. * If set to `"inherit"`, the current `hrtime` permission will be inherited.
  526. * If set to `true`, the global `hrtime` permission will be requested.
  527. * If set to `false`, the global `hrtime` permission will be revoked.
  528. *
  529. * @default {false}
  530. */
  531. hrtime?: "inherit" | boolean;
  532. /** Specifies if the `net` permission should be requested or revoked.
  533. * if set to `"inherit"`, the current `net` permission will be inherited.
  534. * if set to `true`, the global `net` permission will be requested.
  535. * if set to `false`, the global `net` permission will be revoked.
  536. * if set to `string[]`, the `net` permission will be requested with the
  537. * specified host strings with the format `"<host>[:<port>]`.
  538. *
  539. * @default {false}
  540. *
  541. * Examples:
  542. *
  543. * ```ts
  544. * import { assertEquals } from "jsr:@std/assert";
  545. *
  546. * Deno.test({
  547. * name: "inherit",
  548. * permissions: {
  549. * net: "inherit",
  550. * },
  551. * async fn() {
  552. * const status = await Deno.permissions.query({ name: "net" })
  553. * assertEquals(status.state, "granted");
  554. * },
  555. * });
  556. * ```
  557. *
  558. * ```ts
  559. * import { assertEquals } from "jsr:@std/assert";
  560. *
  561. * Deno.test({
  562. * name: "true",
  563. * permissions: {
  564. * net: true,
  565. * },
  566. * async fn() {
  567. * const status = await Deno.permissions.query({ name: "net" });
  568. * assertEquals(status.state, "granted");
  569. * },
  570. * });
  571. * ```
  572. *
  573. * ```ts
  574. * import { assertEquals } from "jsr:@std/assert";
  575. *
  576. * Deno.test({
  577. * name: "false",
  578. * permissions: {
  579. * net: false,
  580. * },
  581. * async fn() {
  582. * const status = await Deno.permissions.query({ name: "net" });
  583. * assertEquals(status.state, "denied");
  584. * },
  585. * });
  586. * ```
  587. *
  588. * ```ts
  589. * import { assertEquals } from "jsr:@std/assert";
  590. *
  591. * Deno.test({
  592. * name: "localhost:8080",
  593. * permissions: {
  594. * net: ["localhost:8080"],
  595. * },
  596. * async fn() {
  597. * const status = await Deno.permissions.query({ name: "net", host: "localhost:8080" });
  598. * assertEquals(status.state, "granted");
  599. * },
  600. * });
  601. * ```
  602. */
  603. net?: "inherit" | boolean | string[];
  604. /** Specifies if the `ffi` permission should be requested or revoked.
  605. * If set to `"inherit"`, the current `ffi` permission will be inherited.
  606. * If set to `true`, the global `ffi` permission will be requested.
  607. * If set to `false`, the global `ffi` permission will be revoked.
  608. *
  609. * @default {false}
  610. */
  611. ffi?: "inherit" | boolean | Array<string | URL>;
  612. /** Specifies if the `read` permission should be requested or revoked.
  613. * If set to `"inherit"`, the current `read` permission will be inherited.
  614. * If set to `true`, the global `read` permission will be requested.
  615. * If set to `false`, the global `read` permission will be revoked.
  616. * If set to `Array<string | URL>`, the `read` permission will be requested with the
  617. * specified file paths.
  618. *
  619. * @default {false}
  620. */
  621. read?: "inherit" | boolean | Array<string | URL>;
  622. /** Specifies if the `run` permission should be requested or revoked.
  623. * If set to `"inherit"`, the current `run` permission will be inherited.
  624. * If set to `true`, the global `run` permission will be requested.
  625. * If set to `false`, the global `run` permission will be revoked.
  626. *
  627. * @default {false}
  628. */
  629. run?: "inherit" | boolean | Array<string | URL>;
  630. /** Specifies if the `write` permission should be requested or revoked.
  631. * If set to `"inherit"`, the current `write` permission will be inherited.
  632. * If set to `true`, the global `write` permission will be requested.
  633. * If set to `false`, the global `write` permission will be revoked.
  634. * If set to `Array<string | URL>`, the `write` permission will be requested with the
  635. * specified file paths.
  636. *
  637. * @default {false}
  638. */
  639. write?: "inherit" | boolean | Array<string | URL>;
  640. }
  641. /**
  642. * Context that is passed to a testing function, which can be used to either
  643. * gain information about the current test, or register additional test
  644. * steps within the current test.
  645. *
  646. * @category Testing */
  647. export interface TestContext {
  648. /** The current test name. */
  649. name: string;
  650. /** The string URL of the current test. */
  651. origin: string;
  652. /** If the current test is a step of another test, the parent test context
  653. * will be set here. */
  654. parent?: TestContext;
  655. /** Run a sub step of the parent test or step. Returns a promise
  656. * that resolves to a boolean signifying if the step completed successfully.
  657. *
  658. * The returned promise never rejects unless the arguments are invalid.
  659. *
  660. * If the test was ignored the promise returns `false`.
  661. *
  662. * ```ts
  663. * Deno.test({
  664. * name: "a parent test",
  665. * async fn(t) {
  666. * console.log("before the step");
  667. * await t.step({
  668. * name: "step 1",
  669. * fn(t) {
  670. * console.log("current step:", t.name);
  671. * }
  672. * });
  673. * console.log("after the step");
  674. * }
  675. * });
  676. * ```
  677. */
  678. step(definition: TestStepDefinition): Promise<boolean>;
  679. /** Run a sub step of the parent test or step. Returns a promise
  680. * that resolves to a boolean signifying if the step completed successfully.
  681. *
  682. * The returned promise never rejects unless the arguments are invalid.
  683. *
  684. * If the test was ignored the promise returns `false`.
  685. *
  686. * ```ts
  687. * Deno.test(
  688. * "a parent test",
  689. * async (t) => {
  690. * console.log("before the step");
  691. * await t.step(
  692. * "step 1",
  693. * (t) => {
  694. * console.log("current step:", t.name);
  695. * }
  696. * );
  697. * console.log("after the step");
  698. * }
  699. * );
  700. * ```
  701. */
  702. step(
  703. name: string,
  704. fn: (t: TestContext) => void | Promise<void>,
  705. ): Promise<boolean>;
  706. /** Run a sub step of the parent test or step. Returns a promise
  707. * that resolves to a boolean signifying if the step completed successfully.
  708. *
  709. * The returned promise never rejects unless the arguments are invalid.
  710. *
  711. * If the test was ignored the promise returns `false`.
  712. *
  713. * ```ts
  714. * Deno.test(async function aParentTest(t) {
  715. * console.log("before the step");
  716. * await t.step(function step1(t) {
  717. * console.log("current step:", t.name);
  718. * });
  719. * console.log("after the step");
  720. * });
  721. * ```
  722. */
  723. step(fn: (t: TestContext) => void | Promise<void>): Promise<boolean>;
  724. }
  725. /** @category Testing */
  726. export interface TestStepDefinition {
  727. /** The test function that will be tested when this step is executed. The
  728. * function can take an argument which will provide information about the
  729. * current step's context. */
  730. fn: (t: TestContext) => void | Promise<void>;
  731. /** The name of the step. */
  732. name: string;
  733. /** If truthy the current test step will be ignored.
  734. *
  735. * This is a quick way to skip over a step, but also can be used for
  736. * conditional logic, like determining if an environment feature is present.
  737. */
  738. ignore?: boolean;
  739. /** Check that the number of async completed operations after the test step
  740. * is the same as number of dispatched operations. This ensures that the
  741. * code tested does not start async operations which it then does
  742. * not await. This helps in preventing logic errors and memory leaks
  743. * in the application code.
  744. *
  745. * Defaults to the parent test or step's value. */
  746. sanitizeOps?: boolean;
  747. /** Ensure the test step does not "leak" resources - like open files or
  748. * network connections - by ensuring the open resources at the start of the
  749. * step match the open resources at the end of the step.
  750. *
  751. * Defaults to the parent test or step's value. */
  752. sanitizeResources?: boolean;
  753. /** Ensure the test step does not prematurely cause the process to exit,
  754. * for example via a call to {@linkcode Deno.exit}.
  755. *
  756. * Defaults to the parent test or step's value. */
  757. sanitizeExit?: boolean;
  758. }
  759. /** @category Testing */
  760. export interface TestDefinition {
  761. fn: (t: TestContext) => void | Promise<void>;
  762. /** The name of the test. */
  763. name: string;
  764. /** If truthy the current test step will be ignored.
  765. *
  766. * It is a quick way to skip over a step, but also can be used for
  767. * conditional logic, like determining if an environment feature is present.
  768. */
  769. ignore?: boolean;
  770. /** If at least one test has `only` set to `true`, only run tests that have
  771. * `only` set to `true` and fail the test suite. */
  772. only?: boolean;
  773. /** Check that the number of async completed operations after the test step
  774. * is the same as number of dispatched operations. This ensures that the
  775. * code tested does not start async operations which it then does
  776. * not await. This helps in preventing logic errors and memory leaks
  777. * in the application code.
  778. *
  779. * @default {true} */
  780. sanitizeOps?: boolean;
  781. /** Ensure the test step does not "leak" resources - like open files or
  782. * network connections - by ensuring the open resources at the start of the
  783. * test match the open resources at the end of the test.
  784. *
  785. * @default {true} */
  786. sanitizeResources?: boolean;
  787. /** Ensure the test case does not prematurely cause the process to exit,
  788. * for example via a call to {@linkcode Deno.exit}.
  789. *
  790. * @default {true} */
  791. sanitizeExit?: boolean;
  792. /** Specifies the permissions that should be used to run the test.
  793. *
  794. * Set this to "inherit" to keep the calling runtime permissions, set this
  795. * to "none" to revoke all permissions, or set a more specific set of
  796. * permissions using a {@linkcode PermissionOptionsObject}.
  797. *
  798. * @default {"inherit"} */
  799. permissions?: PermissionOptions;
  800. }
  801. /** Register a test which will be run when `deno test` is used on the command
  802. * line and the containing module looks like a test module.
  803. *
  804. * `fn` can be async if required.
  805. *
  806. * ```ts
  807. * import { assertEquals } from "jsr:@std/assert";
  808. *
  809. * Deno.test({
  810. * name: "example test",
  811. * fn() {
  812. * assertEquals("world", "world");
  813. * },
  814. * });
  815. *
  816. * Deno.test({
  817. * name: "example ignored test",
  818. * ignore: Deno.build.os === "windows",
  819. * fn() {
  820. * // This test is ignored only on Windows machines
  821. * },
  822. * });
  823. *
  824. * Deno.test({
  825. * name: "example async test",
  826. * async fn() {
  827. * const decoder = new TextDecoder("utf-8");
  828. * const data = await Deno.readFile("hello_world.txt");
  829. * assertEquals(decoder.decode(data), "Hello world");
  830. * }
  831. * });
  832. * ```
  833. *
  834. * @category Testing
  835. */
  836. export const test: DenoTest;
  837. /**
  838. * @category Testing
  839. */
  840. export interface DenoTest {
  841. /** Register a test which will be run when `deno test` is used on the command
  842. * line and the containing module looks like a test module.
  843. *
  844. * `fn` can be async if required.
  845. *
  846. * ```ts
  847. * import { assertEquals } from "jsr:@std/assert";
  848. *
  849. * Deno.test({
  850. * name: "example test",
  851. * fn() {
  852. * assertEquals("world", "world");
  853. * },
  854. * });
  855. *
  856. * Deno.test({
  857. * name: "example ignored test",
  858. * ignore: Deno.build.os === "windows",
  859. * fn() {
  860. * // This test is ignored only on Windows machines
  861. * },
  862. * });
  863. *
  864. * Deno.test({
  865. * name: "example async test",
  866. * async fn() {
  867. * const decoder = new TextDecoder("utf-8");
  868. * const data = await Deno.readFile("hello_world.txt");
  869. * assertEquals(decoder.decode(data), "Hello world");
  870. * }
  871. * });
  872. * ```
  873. *
  874. * @category Testing
  875. */
  876. (t: TestDefinition): void;
  877. /** Register a test which will be run when `deno test` is used on the command
  878. * line and the containing module looks like a test module.
  879. *
  880. * `fn` can be async if required.
  881. *
  882. * ```ts
  883. * import { assertEquals } from "jsr:@std/assert";
  884. *
  885. * Deno.test("My test description", () => {
  886. * assertEquals("hello", "hello");
  887. * });
  888. *
  889. * Deno.test("My async test description", async () => {
  890. * const decoder = new TextDecoder("utf-8");
  891. * const data = await Deno.readFile("hello_world.txt");
  892. * assertEquals(decoder.decode(data), "Hello world");
  893. * });
  894. * ```
  895. *
  896. * @category Testing
  897. */
  898. (
  899. name: string,
  900. fn: (t: TestContext) => void | Promise<void>,
  901. ): void;
  902. /** Register a test which will be run when `deno test` is used on the command
  903. * line and the containing module looks like a test module.
  904. *
  905. * `fn` can be async if required. Declared function must have a name.
  906. *
  907. * ```ts
  908. * import { assertEquals } from "jsr:@std/assert";
  909. *
  910. * Deno.test(function myTestName() {
  911. * assertEquals("hello", "hello");
  912. * });
  913. *
  914. * Deno.test(async function myOtherTestName() {
  915. * const decoder = new TextDecoder("utf-8");
  916. * const data = await Deno.readFile("hello_world.txt");
  917. * assertEquals(decoder.decode(data), "Hello world");
  918. * });
  919. * ```
  920. *
  921. * @category Testing
  922. */
  923. (fn: (t: TestContext) => void | Promise<void>): void;
  924. /** Register a test which will be run when `deno test` is used on the command
  925. * line and the containing module looks like a test module.
  926. *
  927. * `fn` can be async if required.
  928. *
  929. * ```ts
  930. * import { assert, fail, assertEquals } from "jsr:@std/assert";
  931. *
  932. * Deno.test("My test description", { permissions: { read: true } }, (): void => {
  933. * assertEquals("hello", "hello");
  934. * });
  935. *
  936. * Deno.test("My async test description", { permissions: { read: false } }, async (): Promise<void> => {
  937. * const decoder = new TextDecoder("utf-8");
  938. * const data = await Deno.readFile("hello_world.txt");
  939. * assertEquals(decoder.decode(data), "Hello world");
  940. * });
  941. * ```
  942. *
  943. * @category Testing
  944. */
  945. (
  946. name: string,
  947. options: Omit<TestDefinition, "fn" | "name">,
  948. fn: (t: TestContext) => void | Promise<void>,
  949. ): void;
  950. /** Register a test which will be run when `deno test` is used on the command
  951. * line and the containing module looks like a test module.
  952. *
  953. * `fn` can be async if required.
  954. *
  955. * ```ts
  956. * import { assertEquals } from "jsr:@std/assert";
  957. *
  958. * Deno.test(
  959. * {
  960. * name: "My test description",
  961. * permissions: { read: true },
  962. * },
  963. * () => {
  964. * assertEquals("hello", "hello");
  965. * },
  966. * );
  967. *
  968. * Deno.test(
  969. * {
  970. * name: "My async test description",
  971. * permissions: { read: false },
  972. * },
  973. * async () => {
  974. * const decoder = new TextDecoder("utf-8");
  975. * const data = await Deno.readFile("hello_world.txt");
  976. * assertEquals(decoder.decode(data), "Hello world");
  977. * },
  978. * );
  979. * ```
  980. *
  981. * @category Testing
  982. */
  983. (
  984. options: Omit<TestDefinition, "fn" | "name">,
  985. fn: (t: TestContext) => void | Promise<void>,
  986. ): void;
  987. /** Register a test which will be run when `deno test` is used on the command
  988. * line and the containing module looks like a test module.
  989. *
  990. * `fn` can be async if required. Declared function must have a name.
  991. *
  992. * ```ts
  993. * import { assertEquals } from "jsr:@std/assert";
  994. *
  995. * Deno.test(
  996. * { permissions: { read: true } },
  997. * function myTestName() {
  998. * assertEquals("hello", "hello");
  999. * },
  1000. * );
  1001. *
  1002. * Deno.test(
  1003. * { permissions: { read: false } },
  1004. * async function myOtherTestName() {
  1005. * const decoder = new TextDecoder("utf-8");
  1006. * const data = await Deno.readFile("hello_world.txt");
  1007. * assertEquals(decoder.decode(data), "Hello world");
  1008. * },
  1009. * );
  1010. * ```
  1011. *
  1012. * @category Testing
  1013. */
  1014. (
  1015. options: Omit<TestDefinition, "fn">,
  1016. fn: (t: TestContext) => void | Promise<void>,
  1017. ): void;
  1018. /** Shorthand property for ignoring a particular test case.
  1019. *
  1020. * @category Testing
  1021. */
  1022. ignore(t: Omit<TestDefinition, "ignore">): void;
  1023. /** Shorthand property for ignoring a particular test case.
  1024. *
  1025. * @category Testing
  1026. */
  1027. ignore(
  1028. name: string,
  1029. fn: (t: TestContext) => void | Promise<void>,
  1030. ): void;
  1031. /** Shorthand property for ignoring a particular test case.
  1032. *
  1033. * @category Testing
  1034. */
  1035. ignore(fn: (t: TestContext) => void | Promise<void>): void;
  1036. /** Shorthand property for ignoring a particular test case.
  1037. *
  1038. * @category Testing
  1039. */
  1040. ignore(
  1041. name: string,
  1042. options: Omit<TestDefinition, "fn" | "name" | "ignore">,
  1043. fn: (t: TestContext) => void | Promise<void>,
  1044. ): void;
  1045. /** Shorthand property for ignoring a particular test case.
  1046. *
  1047. * @category Testing
  1048. */
  1049. ignore(
  1050. options: Omit<TestDefinition, "fn" | "name" | "ignore">,
  1051. fn: (t: TestContext) => void | Promise<void>,
  1052. ): void;
  1053. /** Shorthand property for ignoring a particular test case.
  1054. *
  1055. * @category Testing
  1056. */
  1057. ignore(
  1058. options: Omit<TestDefinition, "fn" | "ignore">,
  1059. fn: (t: TestContext) => void | Promise<void>,
  1060. ): void;
  1061. /** Shorthand property for focusing a particular test case.
  1062. *
  1063. * @category Testing
  1064. */
  1065. only(t: Omit<TestDefinition, "only">): void;
  1066. /** Shorthand property for focusing a particular test case.
  1067. *
  1068. * @category Testing
  1069. */
  1070. only(
  1071. name: string,
  1072. fn: (t: TestContext) => void | Promise<void>,
  1073. ): void;
  1074. /** Shorthand property for focusing a particular test case.
  1075. *
  1076. * @category Testing
  1077. */
  1078. only(fn: (t: TestContext) => void | Promise<void>): void;
  1079. /** Shorthand property for focusing a particular test case.
  1080. *
  1081. * @category Testing
  1082. */
  1083. only(
  1084. name: string,
  1085. options: Omit<TestDefinition, "fn" | "name" | "only">,
  1086. fn: (t: TestContext) => void | Promise<void>,
  1087. ): void;
  1088. /** Shorthand property for focusing a particular test case.
  1089. *
  1090. * @category Testing
  1091. */
  1092. only(
  1093. options: Omit<TestDefinition, "fn" | "name" | "only">,
  1094. fn: (t: TestContext) => void | Promise<void>,
  1095. ): void;
  1096. /** Shorthand property for focusing a particular test case.
  1097. *
  1098. * @category Testing
  1099. */
  1100. only(
  1101. options: Omit<TestDefinition, "fn" | "only">,
  1102. fn: (t: TestContext) => void | Promise<void>,
  1103. ): void;
  1104. }
  1105. /**
  1106. * Context that is passed to a benchmarked function. The instance is shared
  1107. * between iterations of the benchmark. Its methods can be used for example
  1108. * to override of the measured portion of the function.
  1109. *
  1110. * @category Testing
  1111. */
  1112. export interface BenchContext {
  1113. /** The current benchmark name. */
  1114. name: string;
  1115. /** The string URL of the current benchmark. */
  1116. origin: string;
  1117. /** Restarts the timer for the bench measurement. This should be called
  1118. * after doing setup work which should not be measured.
  1119. *
  1120. * Warning: This method should not be used for benchmarks averaging less
  1121. * than 10μs per iteration. In such cases it will be disabled but the call
  1122. * will still have noticeable overhead, resulting in a warning.
  1123. *
  1124. * ```ts
  1125. * Deno.bench("foo", async (t) => {
  1126. * const data = await Deno.readFile("data.txt");
  1127. * t.start();
  1128. * // some operation on `data`...
  1129. * });
  1130. * ```
  1131. */
  1132. start(): void;
  1133. /** End the timer early for the bench measurement. This should be called
  1134. * before doing teardown work which should not be measured.
  1135. *
  1136. * Warning: This method should not be used for benchmarks averaging less
  1137. * than 10μs per iteration. In such cases it will be disabled but the call
  1138. * will still have noticeable overhead, resulting in a warning.
  1139. *
  1140. * ```ts
  1141. * Deno.bench("foo", async (t) => {
  1142. * using file = await Deno.open("data.txt");
  1143. * t.start();
  1144. * // some operation on `file`...
  1145. * t.end();
  1146. * });
  1147. * ```
  1148. */
  1149. end(): void;
  1150. }
  1151. /**
  1152. * The interface for defining a benchmark test using {@linkcode Deno.bench}.
  1153. *
  1154. * @category Testing
  1155. */
  1156. export interface BenchDefinition {
  1157. /** The test function which will be benchmarked. */
  1158. fn: (b: BenchContext) => void | Promise<void>;
  1159. /** The name of the test, which will be used in displaying the results. */
  1160. name: string;
  1161. /** If truthy, the benchmark test will be ignored/skipped. */
  1162. ignore?: boolean;
  1163. /** Group name for the benchmark.
  1164. *
  1165. * Grouped benchmarks produce a group time summary, where the difference
  1166. * in performance between each test of the group is compared. */
  1167. group?: string;
  1168. /** Benchmark should be used as the baseline for other benchmarks.
  1169. *
  1170. * If there are multiple baselines in a group, the first one is used as the
  1171. * baseline. */
  1172. baseline?: boolean;
  1173. /** If at least one bench has `only` set to true, only run benches that have
  1174. * `only` set to `true` and fail the bench suite. */
  1175. only?: boolean;
  1176. /** Ensure the bench case does not prematurely cause the process to exit,
  1177. * for example via a call to {@linkcode Deno.exit}.
  1178. *
  1179. * @default {true} */
  1180. sanitizeExit?: boolean;
  1181. /** Specifies the permissions that should be used to run the bench.
  1182. *
  1183. * Set this to `"inherit"` to keep the calling thread's permissions.
  1184. *
  1185. * Set this to `"none"` to revoke all permissions.
  1186. *
  1187. * @default {"inherit"}
  1188. */
  1189. permissions?: PermissionOptions;
  1190. }
  1191. /**
  1192. * Register a benchmark test which will be run when `deno bench` is used on
  1193. * the command line and the containing module looks like a bench module.
  1194. *
  1195. * If the test function (`fn`) returns a promise or is async, the test runner
  1196. * will await resolution to consider the test complete.
  1197. *
  1198. * ```ts
  1199. * import { assertEquals } from "jsr:@std/assert";
  1200. *
  1201. * Deno.bench({
  1202. * name: "example test",
  1203. * fn() {
  1204. * assertEquals("world", "world");
  1205. * },
  1206. * });
  1207. *
  1208. * Deno.bench({
  1209. * name: "example ignored test",
  1210. * ignore: Deno.build.os === "windows",
  1211. * fn() {
  1212. * // This test is ignored only on Windows machines
  1213. * },
  1214. * });
  1215. *
  1216. * Deno.bench({
  1217. * name: "example async test",
  1218. * async fn() {
  1219. * const decoder = new TextDecoder("utf-8");
  1220. * const data = await Deno.readFile("hello_world.txt");
  1221. * assertEquals(decoder.decode(data), "Hello world");
  1222. * }
  1223. * });
  1224. * ```
  1225. *
  1226. * @category Testing
  1227. */
  1228. export function bench(b: BenchDefinition): void;
  1229. /**
  1230. * Register a benchmark test which will be run when `deno bench` is used on
  1231. * the command line and the containing module looks like a bench module.
  1232. *
  1233. * If the test function (`fn`) returns a promise or is async, the test runner
  1234. * will await resolution to consider the test complete.
  1235. *
  1236. * ```ts
  1237. * import { assertEquals } from "jsr:@std/assert";
  1238. *
  1239. * Deno.bench("My test description", () => {
  1240. * assertEquals("hello", "hello");
  1241. * });
  1242. *
  1243. * Deno.bench("My async test description", async () => {
  1244. * const decoder = new TextDecoder("utf-8");
  1245. * const data = await Deno.readFile("hello_world.txt");
  1246. * assertEquals(decoder.decode(data), "Hello world");
  1247. * });
  1248. * ```
  1249. *
  1250. * @category Testing
  1251. */
  1252. export function bench(
  1253. name: string,
  1254. fn: (b: BenchContext) => void | Promise<void>,
  1255. ): void;
  1256. /**
  1257. * Register a benchmark test which will be run when `deno bench` is used on
  1258. * the command line and the containing module looks like a bench module.
  1259. *
  1260. * If the test function (`fn`) returns a promise or is async, the test runner
  1261. * will await resolution to consider the test complete.
  1262. *
  1263. * ```ts
  1264. * import { assertEquals } from "jsr:@std/assert";
  1265. *
  1266. * Deno.bench(function myTestName() {
  1267. * assertEquals("hello", "hello");
  1268. * });
  1269. *
  1270. * Deno.bench(async function myOtherTestName() {
  1271. * const decoder = new TextDecoder("utf-8");
  1272. * const data = await Deno.readFile("hello_world.txt");
  1273. * assertEquals(decoder.decode(data), "Hello world");
  1274. * });
  1275. * ```
  1276. *
  1277. * @category Testing
  1278. */
  1279. export function bench(fn: (b: BenchContext) => void | Promise<void>): void;
  1280. /**
  1281. * Register a benchmark test which will be run when `deno bench` is used on
  1282. * the command line and the containing module looks like a bench module.
  1283. *
  1284. * If the test function (`fn`) returns a promise or is async, the test runner
  1285. * will await resolution to consider the test complete.
  1286. *
  1287. * ```ts
  1288. * import { assertEquals } from "jsr:@std/assert";
  1289. *
  1290. * Deno.bench(
  1291. * "My test description",
  1292. * { permissions: { read: true } },
  1293. * () => {
  1294. * assertEquals("hello", "hello");
  1295. * }
  1296. * );
  1297. *
  1298. * Deno.bench(
  1299. * "My async test description",
  1300. * { permissions: { read: false } },
  1301. * async () => {
  1302. * const decoder = new TextDecoder("utf-8");
  1303. * const data = await Deno.readFile("hello_world.txt");
  1304. * assertEquals(decoder.decode(data), "Hello world");
  1305. * }
  1306. * );
  1307. * ```
  1308. *
  1309. * @category Testing
  1310. */
  1311. export function bench(
  1312. name: string,
  1313. options: Omit<BenchDefinition, "fn" | "name">,
  1314. fn: (b: BenchContext) => void | Promise<void>,
  1315. ): void;
  1316. /**
  1317. * Register a benchmark test which will be run when `deno bench` is used on
  1318. * the command line and the containing module looks like a bench module.
  1319. *
  1320. * If the test function (`fn`) returns a promise or is async, the test runner
  1321. * will await resolution to consider the test complete.
  1322. *
  1323. * ```ts
  1324. * import { assertEquals } from "jsr:@std/assert";
  1325. *
  1326. * Deno.bench(
  1327. * { name: "My test description", permissions: { read: true } },
  1328. * () => {
  1329. * assertEquals("hello", "hello");
  1330. * }
  1331. * );
  1332. *
  1333. * Deno.bench(
  1334. * { name: "My async test description", permissions: { read: false } },
  1335. * async () => {
  1336. * const decoder = new TextDecoder("utf-8");
  1337. * const data = await Deno.readFile("hello_world.txt");
  1338. * assertEquals(decoder.decode(data), "Hello world");
  1339. * }
  1340. * );
  1341. * ```
  1342. *
  1343. * @category Testing
  1344. */
  1345. export function bench(
  1346. options: Omit<BenchDefinition, "fn">,
  1347. fn: (b: BenchContext) => void | Promise<void>,
  1348. ): void;
  1349. /**
  1350. * Register a benchmark test which will be run when `deno bench` is used on
  1351. * the command line and the containing module looks like a bench module.
  1352. *
  1353. * If the test function (`fn`) returns a promise or is async, the test runner
  1354. * will await resolution to consider the test complete.
  1355. *
  1356. * ```ts
  1357. * import { assertEquals } from "jsr:@std/assert";
  1358. *
  1359. * Deno.bench(
  1360. * { permissions: { read: true } },
  1361. * function myTestName() {
  1362. * assertEquals("hello", "hello");
  1363. * }
  1364. * );
  1365. *
  1366. * Deno.bench(
  1367. * { permissions: { read: false } },
  1368. * async function myOtherTestName() {
  1369. * const decoder = new TextDecoder("utf-8");
  1370. * const data = await Deno.readFile("hello_world.txt");
  1371. * assertEquals(decoder.decode(data), "Hello world");
  1372. * }
  1373. * );
  1374. * ```
  1375. *
  1376. * @category Testing
  1377. */
  1378. export function bench(
  1379. options: Omit<BenchDefinition, "fn" | "name">,
  1380. fn: (b: BenchContext) => void | Promise<void>,
  1381. ): void;
  1382. /** Exit the Deno process with optional exit code.
  1383. *
  1384. * If no exit code is supplied then Deno will exit with return code of `0`.
  1385. *
  1386. * In worker contexts this is an alias to `self.close();`.
  1387. *
  1388. * ```ts
  1389. * Deno.exit(5);
  1390. * ```
  1391. *
  1392. * @category Runtime
  1393. */
  1394. export function exit(code?: number): never;
  1395. /** The exit code for the Deno process.
  1396. *
  1397. * If no exit code has been supplied, then Deno will assume a return code of `0`.
  1398. *
  1399. * When setting an exit code value, a number or non-NaN string must be provided,
  1400. * otherwise a TypeError will be thrown.
  1401. *
  1402. * ```ts
  1403. * console.log(Deno.exitCode); //-> 0
  1404. * Deno.exitCode = 1;
  1405. * console.log(Deno.exitCode); //-> 1
  1406. * ```
  1407. *
  1408. * @category Runtime
  1409. */
  1410. export var exitCode: number;
  1411. /** An interface containing methods to interact with the process environment
  1412. * variables.
  1413. *
  1414. * @tags allow-env
  1415. * @category Runtime
  1416. */
  1417. export interface Env {
  1418. /** Retrieve the value of an environment variable.
  1419. *
  1420. * Returns `undefined` if the supplied environment variable is not defined.
  1421. *
  1422. * ```ts
  1423. * console.log(Deno.env.get("HOME")); // e.g. outputs "/home/alice"
  1424. * console.log(Deno.env.get("MADE_UP_VAR")); // outputs "undefined"
  1425. * ```
  1426. *
  1427. * Requires `allow-env` permission.
  1428. *
  1429. * @tags allow-env
  1430. */
  1431. get(key: string): string | undefined;
  1432. /** Set the value of an environment variable.
  1433. *
  1434. * ```ts
  1435. * Deno.env.set("SOME_VAR", "Value");
  1436. * Deno.env.get("SOME_VAR"); // outputs "Value"
  1437. * ```
  1438. *
  1439. * Requires `allow-env` permission.
  1440. *
  1441. * @tags allow-env
  1442. */
  1443. set(key: string, value: string): void;
  1444. /** Delete the value of an environment variable.
  1445. *
  1446. * ```ts
  1447. * Deno.env.set("SOME_VAR", "Value");
  1448. * Deno.env.delete("SOME_VAR"); // outputs "undefined"
  1449. * ```
  1450. *
  1451. * Requires `allow-env` permission.
  1452. *
  1453. * @tags allow-env
  1454. */
  1455. delete(key: string): void;
  1456. /** Check whether an environment variable is present or not.
  1457. *
  1458. * ```ts
  1459. * Deno.env.set("SOME_VAR", "Value");
  1460. * Deno.env.has("SOME_VAR"); // outputs true
  1461. * ```
  1462. *
  1463. * Requires `allow-env` permission.
  1464. *
  1465. * @tags allow-env
  1466. */
  1467. has(key: string): boolean;
  1468. /** Returns a snapshot of the environment variables at invocation as a
  1469. * simple object of keys and values.
  1470. *
  1471. * ```ts
  1472. * Deno.env.set("TEST_VAR", "A");
  1473. * const myEnv = Deno.env.toObject();
  1474. * console.log(myEnv.SHELL);
  1475. * Deno.env.set("TEST_VAR", "B");
  1476. * console.log(myEnv.TEST_VAR); // outputs "A"
  1477. * ```
  1478. *
  1479. * Requires `allow-env` permission.
  1480. *
  1481. * @tags allow-env
  1482. */
  1483. toObject(): { [index: string]: string };
  1484. }
  1485. /** An interface containing methods to interact with the process environment
  1486. * variables.
  1487. *
  1488. * @tags allow-env
  1489. * @category Runtime
  1490. */
  1491. export const env: Env;
  1492. /**
  1493. * Returns the path to the current deno executable.
  1494. *
  1495. * ```ts
  1496. * console.log(Deno.execPath()); // e.g. "/home/alice/.local/bin/deno"
  1497. * ```
  1498. *
  1499. * Requires `allow-read` permission.
  1500. *
  1501. * @tags allow-read
  1502. * @category Runtime
  1503. */
  1504. export function execPath(): string;
  1505. /**
  1506. * Change the current working directory to the specified path.
  1507. *
  1508. * ```ts
  1509. * Deno.chdir("/home/userA");
  1510. * Deno.chdir("../userB");
  1511. * Deno.chdir("C:\\Program Files (x86)\\Java");
  1512. * ```
  1513. *
  1514. * Throws {@linkcode Deno.errors.NotFound} if directory not found.
  1515. *
  1516. * Throws {@linkcode Deno.errors.PermissionDenied} if the user does not have
  1517. * operating system file access rights.
  1518. *
  1519. * Requires `allow-read` permission.
  1520. *
  1521. * @tags allow-read
  1522. * @category Runtime
  1523. */
  1524. export function chdir(directory: string | URL): void;
  1525. /**
  1526. * Return a string representing the current working directory.
  1527. *
  1528. * If the current directory can be reached via multiple paths (due to symbolic
  1529. * links), `cwd()` may return any one of them.
  1530. *
  1531. * ```ts
  1532. * const currentWorkingDirectory = Deno.cwd();
  1533. * ```
  1534. *
  1535. * Throws {@linkcode Deno.errors.NotFound} if directory not available.
  1536. *
  1537. * Requires `allow-read` permission.
  1538. *
  1539. * @tags allow-read
  1540. * @category Runtime
  1541. */
  1542. export function cwd(): string;
  1543. /**
  1544. * Creates `newpath` as a hard link to `oldpath`.
  1545. *
  1546. * ```ts
  1547. * await Deno.link("old/name", "new/name");
  1548. * ```
  1549. *
  1550. * Requires `allow-read` and `allow-write` permissions.
  1551. *
  1552. * @tags allow-read, allow-write
  1553. * @category File System
  1554. */
  1555. export function link(oldpath: string, newpath: string): Promise<void>;
  1556. /**
  1557. * Synchronously creates `newpath` as a hard link to `oldpath`.
  1558. *
  1559. * ```ts
  1560. * Deno.linkSync("old/name", "new/name");
  1561. * ```
  1562. *
  1563. * Requires `allow-read` and `allow-write` permissions.
  1564. *
  1565. * @tags allow-read, allow-write
  1566. * @category File System
  1567. */
  1568. export function linkSync(oldpath: string, newpath: string): void;
  1569. /**
  1570. * A enum which defines the seek mode for IO related APIs that support
  1571. * seeking.
  1572. *
  1573. * @category I/O */
  1574. export enum SeekMode {
  1575. /* Seek from the start of the file/resource. */
  1576. Start = 0,
  1577. /* Seek from the current position within the file/resource. */
  1578. Current = 1,
  1579. /* Seek from the end of the current file/resource. */
  1580. End = 2,
  1581. }
  1582. /**
  1583. * An abstract interface which when implemented provides an interface to read
  1584. * bytes into an array buffer asynchronously.
  1585. *
  1586. * @deprecated This will be removed in Deno 2.0. See the
  1587. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  1588. * for migration instructions.
  1589. *
  1590. * @category I/O */
  1591. export interface Reader {
  1592. /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number of
  1593. * bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error
  1594. * encountered. Even if `read()` resolves to `n` < `p.byteLength`, it may
  1595. * use all of `p` as scratch space during the call. If some data is
  1596. * available but not `p.byteLength` bytes, `read()` conventionally resolves
  1597. * to what is available instead of waiting for more.
  1598. *
  1599. * When `read()` encounters end-of-file condition, it resolves to EOF
  1600. * (`null`).
  1601. *
  1602. * When `read()` encounters an error, it rejects with an error.
  1603. *
  1604. * Callers should always process the `n` > `0` bytes returned before
  1605. * considering the EOF (`null`). Doing so correctly handles I/O errors that
  1606. * happen after reading some bytes and also both of the allowed EOF
  1607. * behaviors.
  1608. *
  1609. * Implementations should not retain a reference to `p`.
  1610. *
  1611. * Use
  1612. * {@linkcode https://jsr.io/@std/io/doc/iterate-reader/~/iterateReader | iterateReader}
  1613. * to turn {@linkcode Reader} into an {@linkcode AsyncIterator}.
  1614. */
  1615. read(p: Uint8Array): Promise<number | null>;
  1616. }
  1617. /**
  1618. * An abstract interface which when implemented provides an interface to read
  1619. * bytes into an array buffer synchronously.
  1620. *
  1621. * @deprecated This will be removed in Deno 2.0. See the
  1622. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  1623. * for migration instructions.
  1624. *
  1625. * @category I/O */
  1626. export interface ReaderSync {
  1627. /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number
  1628. * of bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error
  1629. * encountered. Even if `readSync()` returns `n` < `p.byteLength`, it may use
  1630. * all of `p` as scratch space during the call. If some data is available
  1631. * but not `p.byteLength` bytes, `readSync()` conventionally returns what is
  1632. * available instead of waiting for more.
  1633. *
  1634. * When `readSync()` encounters end-of-file condition, it returns EOF
  1635. * (`null`).
  1636. *
  1637. * When `readSync()` encounters an error, it throws with an error.
  1638. *
  1639. * Callers should always process the `n` > `0` bytes returned before
  1640. * considering the EOF (`null`). Doing so correctly handles I/O errors that
  1641. * happen after reading some bytes and also both of the allowed EOF
  1642. * behaviors.
  1643. *
  1644. * Implementations should not retain a reference to `p`.
  1645. *
  1646. * Use
  1647. * {@linkcode https://jsr.io/@std/io/doc/iterate-reader/~/iterateReaderSync | iterateReaderSync}
  1648. * to turn {@linkcode ReaderSync} into an {@linkcode Iterator}.
  1649. */
  1650. readSync(p: Uint8Array): number | null;
  1651. }
  1652. /**
  1653. * An abstract interface which when implemented provides an interface to write
  1654. * bytes from an array buffer to a file/resource asynchronously.
  1655. *
  1656. * @deprecated This will be removed in Deno 2.0. See the
  1657. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  1658. * for migration instructions.
  1659. *
  1660. * @category I/O */
  1661. export interface Writer {
  1662. /** Writes `p.byteLength` bytes from `p` to the underlying data stream. It
  1663. * resolves to the number of bytes written from `p` (`0` <= `n` <=
  1664. * `p.byteLength`) or reject with the error encountered that caused the
  1665. * write to stop early. `write()` must reject with a non-null error if
  1666. * would resolve to `n` < `p.byteLength`. `write()` must not modify the
  1667. * slice data, even temporarily.
  1668. *
  1669. * This function is one of the lowest
  1670. * level APIs and most users should not work with this directly, but rather
  1671. * use {@linkcode https://jsr.io/@std/io/doc/write-all/~/writeAll | writeAll}
  1672. * instead.
  1673. *
  1674. * Implementations should not retain a reference to `p`.
  1675. */
  1676. write(p: Uint8Array): Promise<number>;
  1677. }
  1678. /**
  1679. * An abstract interface which when implemented provides an interface to write
  1680. * bytes from an array buffer to a file/resource synchronously.
  1681. *
  1682. * @deprecated This will be removed in Deno 2.0. See the
  1683. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  1684. * for migration instructions.
  1685. *
  1686. * @category I/O */
  1687. export interface WriterSync {
  1688. /** Writes `p.byteLength` bytes from `p` to the underlying data
  1689. * stream. It returns the number of bytes written from `p` (`0` <= `n`
  1690. * <= `p.byteLength`) and any error encountered that caused the write to
  1691. * stop early. `writeSync()` must throw a non-null error if it returns `n` <
  1692. * `p.byteLength`. `writeSync()` must not modify the slice data, even
  1693. * temporarily.
  1694. *
  1695. * Implementations should not retain a reference to `p`.
  1696. */
  1697. writeSync(p: Uint8Array): number;
  1698. }
  1699. /**
  1700. * An abstract interface which when implemented provides an interface to close
  1701. * files/resources that were previously opened.
  1702. *
  1703. * @deprecated This will be removed in Deno 2.0. See the
  1704. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  1705. * for migration instructions.
  1706. *
  1707. * @category I/O */
  1708. export interface Closer {
  1709. /** Closes the resource, "freeing" the backing file/resource. */
  1710. close(): void;
  1711. }
  1712. /**
  1713. * An abstract interface which when implemented provides an interface to seek
  1714. * within an open file/resource asynchronously.
  1715. *
  1716. * @category I/O */
  1717. export interface Seeker {
  1718. /** Seek sets the offset for the next `read()` or `write()` to offset,
  1719. * interpreted according to `whence`: `Start` means relative to the
  1720. * start of the file, `Current` means relative to the current offset,
  1721. * and `End` means relative to the end. Seek resolves to the new offset
  1722. * relative to the start of the file.
  1723. *
  1724. * Seeking to an offset before the start of the file is an error. Seeking to
  1725. * any positive offset is legal, but the behavior of subsequent I/O
  1726. * operations on the underlying object is implementation-dependent.
  1727. *
  1728. * It resolves with the updated offset.
  1729. */
  1730. seek(offset: number | bigint, whence: SeekMode): Promise<number>;
  1731. }
  1732. /**
  1733. * An abstract interface which when implemented provides an interface to seek
  1734. * within an open file/resource synchronously.
  1735. *
  1736. * @category I/O */
  1737. export interface SeekerSync {
  1738. /** Seek sets the offset for the next `readSync()` or `writeSync()` to
  1739. * offset, interpreted according to `whence`: `Start` means relative
  1740. * to the start of the file, `Current` means relative to the current
  1741. * offset, and `End` means relative to the end.
  1742. *
  1743. * Seeking to an offset before the start of the file is an error. Seeking to
  1744. * any positive offset is legal, but the behavior of subsequent I/O
  1745. * operations on the underlying object is implementation-dependent.
  1746. *
  1747. * It returns the updated offset.
  1748. */
  1749. seekSync(offset: number | bigint, whence: SeekMode): number;
  1750. }
  1751. /**
  1752. * Copies from `src` to `dst` until either EOF (`null`) is read from `src` or
  1753. * an error occurs. It resolves to the number of bytes copied or rejects with
  1754. * the first error encountered while copying.
  1755. *
  1756. * @deprecated This will be removed in Deno 2.0. See the
  1757. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  1758. * for migration instructions.
  1759. *
  1760. * @category I/O
  1761. *
  1762. * @param src The source to copy from
  1763. * @param dst The destination to copy to
  1764. * @param options Can be used to tune size of the buffer. Default size is 32kB
  1765. */
  1766. export function copy(
  1767. src: Reader,
  1768. dst: Writer,
  1769. options?: { bufSize?: number },
  1770. ): Promise<number>;
  1771. /**
  1772. * Turns a Reader, `r`, into an async iterator.
  1773. *
  1774. * @deprecated This will be removed in Deno 2.0. See the
  1775. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  1776. * for migration instructions.
  1777. *
  1778. * @category I/O
  1779. */
  1780. export function iter(
  1781. r: Reader,
  1782. options?: { bufSize?: number },
  1783. ): AsyncIterableIterator<Uint8Array>;
  1784. /**
  1785. * Turns a ReaderSync, `r`, into an iterator.
  1786. *
  1787. * @deprecated This will be removed in Deno 2.0. See the
  1788. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  1789. * for migration instructions.
  1790. *
  1791. * @category I/O
  1792. */
  1793. export function iterSync(
  1794. r: ReaderSync,
  1795. options?: {
  1796. bufSize?: number;
  1797. },
  1798. ): IterableIterator<Uint8Array>;
  1799. /** Open a file and resolve to an instance of {@linkcode Deno.FsFile}. The
  1800. * file does not need to previously exist if using the `create` or `createNew`
  1801. * open options. The caller may have the resulting file automatically closed
  1802. * by the runtime once it's out of scope by declaring the file variable with
  1803. * the `using` keyword.
  1804. *
  1805. * ```ts
  1806. * using file = await Deno.open("/foo/bar.txt", { read: true, write: true });
  1807. * // Do work with file
  1808. * ```
  1809. *
  1810. * Alternatively, the caller may manually close the resource when finished with
  1811. * it.
  1812. *
  1813. * ```ts
  1814. * const file = await Deno.open("/foo/bar.txt", { read: true, write: true });
  1815. * // Do work with file
  1816. * file.close();
  1817. * ```
  1818. *
  1819. * Requires `allow-read` and/or `allow-write` permissions depending on
  1820. * options.
  1821. *
  1822. * @tags allow-read, allow-write
  1823. * @category File System
  1824. */
  1825. export function open(
  1826. path: string | URL,
  1827. options?: OpenOptions,
  1828. ): Promise<FsFile>;
  1829. /** Synchronously open a file and return an instance of
  1830. * {@linkcode Deno.FsFile}. The file does not need to previously exist if
  1831. * using the `create` or `createNew` open options. The caller may have the
  1832. * resulting file automatically closed by the runtime once it's out of scope
  1833. * by declaring the file variable with the `using` keyword.
  1834. *
  1835. * ```ts
  1836. * using file = Deno.openSync("/foo/bar.txt", { read: true, write: true });
  1837. * // Do work with file
  1838. * ```
  1839. *
  1840. * Alternatively, the caller may manually close the resource when finished with
  1841. * it.
  1842. *
  1843. * ```ts
  1844. * const file = Deno.openSync("/foo/bar.txt", { read: true, write: true });
  1845. * // Do work with file
  1846. * file.close();
  1847. * ```
  1848. *
  1849. * Requires `allow-read` and/or `allow-write` permissions depending on
  1850. * options.
  1851. *
  1852. * @tags allow-read, allow-write
  1853. * @category File System
  1854. */
  1855. export function openSync(path: string | URL, options?: OpenOptions): FsFile;
  1856. /** Creates a file if none exists or truncates an existing file and resolves to
  1857. * an instance of {@linkcode Deno.FsFile}.
  1858. *
  1859. * ```ts
  1860. * const file = await Deno.create("/foo/bar.txt");
  1861. * ```
  1862. *
  1863. * Requires `allow-read` and `allow-write` permissions.
  1864. *
  1865. * @tags allow-read, allow-write
  1866. * @category File System
  1867. */
  1868. export function create(path: string | URL): Promise<FsFile>;
  1869. /** Creates a file if none exists or truncates an existing file and returns
  1870. * an instance of {@linkcode Deno.FsFile}.
  1871. *
  1872. * ```ts
  1873. * const file = Deno.createSync("/foo/bar.txt");
  1874. * ```
  1875. *
  1876. * Requires `allow-read` and `allow-write` permissions.
  1877. *
  1878. * @tags allow-read, allow-write
  1879. * @category File System
  1880. */
  1881. export function createSync(path: string | URL): FsFile;
  1882. /** Read from a resource ID (`rid`) into an array buffer (`buffer`).
  1883. *
  1884. * Resolves to either the number of bytes read during the operation or EOF
  1885. * (`null`) if there was nothing more to read.
  1886. *
  1887. * It is possible for a read to successfully return with `0` bytes. This does
  1888. * not indicate EOF.
  1889. *
  1890. * This function is one of the lowest level APIs and most users should not
  1891. * work with this directly, but rather use {@linkcode ReadableStream} and
  1892. * {@linkcode https://jsr.io/@std/streams/doc/to-array-buffer/~/toArrayBuffer | toArrayBuffer}
  1893. * instead.
  1894. *
  1895. * **It is not guaranteed that the full buffer will be read in a single call.**
  1896. *
  1897. * ```ts
  1898. * // if "/foo/bar.txt" contains the text "hello world":
  1899. * using file = await Deno.open("/foo/bar.txt");
  1900. * const buf = new Uint8Array(100);
  1901. * const numberOfBytesRead = await Deno.read(file.rid, buf); // 11 bytes
  1902. * const text = new TextDecoder().decode(buf); // "hello world"
  1903. * ```
  1904. *
  1905. * @deprecated This will be removed in Deno 2.0. See the
  1906. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  1907. * for migration instructions.
  1908. *
  1909. * @category I/O
  1910. */
  1911. export function read(rid: number, buffer: Uint8Array): Promise<number | null>;
  1912. /** Synchronously read from a resource ID (`rid`) into an array buffer
  1913. * (`buffer`).
  1914. *
  1915. * Returns either the number of bytes read during the operation or EOF
  1916. * (`null`) if there was nothing more to read.
  1917. *
  1918. * It is possible for a read to successfully return with `0` bytes. This does
  1919. * not indicate EOF.
  1920. *
  1921. * This function is one of the lowest level APIs and most users should not
  1922. * work with this directly, but rather use {@linkcode ReadableStream} and
  1923. * {@linkcode https://jsr.io/@std/streams/doc/to-array-buffer/~/toArrayBuffer | toArrayBuffer}
  1924. * instead.
  1925. *
  1926. * **It is not guaranteed that the full buffer will be read in a single
  1927. * call.**
  1928. *
  1929. * ```ts
  1930. * // if "/foo/bar.txt" contains the text "hello world":
  1931. * using file = Deno.openSync("/foo/bar.txt");
  1932. * const buf = new Uint8Array(100);
  1933. * const numberOfBytesRead = Deno.readSync(file.rid, buf); // 11 bytes
  1934. * const text = new TextDecoder().decode(buf); // "hello world"
  1935. * ```
  1936. *
  1937. * @deprecated This will be removed in Deno 2.0. See the
  1938. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  1939. * for migration instructions.
  1940. *
  1941. * @category I/O
  1942. */
  1943. export function readSync(rid: number, buffer: Uint8Array): number | null;
  1944. /** Write to the resource ID (`rid`) the contents of the array buffer (`data`).
  1945. *
  1946. * Resolves to the number of bytes written. This function is one of the lowest
  1947. * level APIs and most users should not work with this directly, but rather
  1948. * use {@linkcode WritableStream}, {@linkcode ReadableStream.from} and
  1949. * {@linkcode ReadableStream.pipeTo}.
  1950. *
  1951. * **It is not guaranteed that the full buffer will be written in a single
  1952. * call.**
  1953. *
  1954. * ```ts
  1955. * const encoder = new TextEncoder();
  1956. * const data = encoder.encode("Hello world");
  1957. * using file = await Deno.open("/foo/bar.txt", { write: true });
  1958. * const bytesWritten = await Deno.write(file.rid, data); // 11
  1959. * ```
  1960. *
  1961. * @deprecated This will be removed in Deno 2.0. See the
  1962. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  1963. * for migration instructions.
  1964. *
  1965. * @category I/O
  1966. */
  1967. export function write(rid: number, data: Uint8Array): Promise<number>;
  1968. /** Synchronously write to the resource ID (`rid`) the contents of the array
  1969. * buffer (`data`).
  1970. *
  1971. * Returns the number of bytes written. This function is one of the lowest
  1972. * level APIs and most users should not work with this directly, but rather
  1973. * use {@linkcode WritableStream}, {@linkcode ReadableStream.from} and
  1974. * {@linkcode ReadableStream.pipeTo}.
  1975. *
  1976. * **It is not guaranteed that the full buffer will be written in a single
  1977. * call.**
  1978. *
  1979. * ```ts
  1980. * const encoder = new TextEncoder();
  1981. * const data = encoder.encode("Hello world");
  1982. * using file = Deno.openSync("/foo/bar.txt", { write: true });
  1983. * const bytesWritten = Deno.writeSync(file.rid, data); // 11
  1984. * ```
  1985. *
  1986. * @deprecated This will be removed in Deno 2.0. See the
  1987. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  1988. * for migration instructions.
  1989. *
  1990. * @category I/O
  1991. */
  1992. export function writeSync(rid: number, data: Uint8Array): number;
  1993. /** Seek a resource ID (`rid`) to the given `offset` under mode given by `whence`.
  1994. * The call resolves to the new position within the resource (bytes from the start).
  1995. *
  1996. * ```ts
  1997. * // Given file.rid pointing to file with "Hello world", which is 11 bytes long:
  1998. * using file = await Deno.open(
  1999. * "hello.txt",
  2000. * { read: true, write: true, truncate: true, create: true },
  2001. * );
  2002. * await file.write(new TextEncoder().encode("Hello world"));
  2003. *
  2004. * // advance cursor 6 bytes
  2005. * const cursorPosition = await Deno.seek(file.rid, 6, Deno.SeekMode.Start);
  2006. * console.log(cursorPosition); // 6
  2007. * const buf = new Uint8Array(100);
  2008. * await file.read(buf);
  2009. * console.log(new TextDecoder().decode(buf)); // "world"
  2010. * ```
  2011. *
  2012. * The seek modes work as follows:
  2013. *
  2014. * ```ts
  2015. * // Given file.rid pointing to file with "Hello world", which is 11 bytes long:
  2016. * using file = await Deno.open(
  2017. * "hello.txt",
  2018. * { read: true, write: true, truncate: true, create: true },
  2019. * );
  2020. * await file.write(new TextEncoder().encode("Hello world"));
  2021. *
  2022. * // Seek 6 bytes from the start of the file
  2023. * console.log(await Deno.seek(file.rid, 6, Deno.SeekMode.Start)); // "6"
  2024. * // Seek 2 more bytes from the current position
  2025. * console.log(await Deno.seek(file.rid, 2, Deno.SeekMode.Current)); // "8"
  2026. * // Seek backwards 2 bytes from the end of the file
  2027. * console.log(await Deno.seek(file.rid, -2, Deno.SeekMode.End)); // "9" (i.e. 11-2)
  2028. * ```
  2029. *
  2030. * @deprecated This will be removed in Deno 2.0. See the
  2031. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2032. * for migration instructions.
  2033. *
  2034. * @category I/O
  2035. */
  2036. export function seek(
  2037. rid: number,
  2038. offset: number | bigint,
  2039. whence: SeekMode,
  2040. ): Promise<number>;
  2041. /** Synchronously seek a resource ID (`rid`) to the given `offset` under mode
  2042. * given by `whence`. The new position within the resource (bytes from the
  2043. * start) is returned.
  2044. *
  2045. * ```ts
  2046. * using file = Deno.openSync(
  2047. * "hello.txt",
  2048. * { read: true, write: true, truncate: true, create: true },
  2049. * );
  2050. * file.writeSync(new TextEncoder().encode("Hello world"));
  2051. *
  2052. * // advance cursor 6 bytes
  2053. * const cursorPosition = Deno.seekSync(file.rid, 6, Deno.SeekMode.Start);
  2054. * console.log(cursorPosition); // 6
  2055. * const buf = new Uint8Array(100);
  2056. * file.readSync(buf);
  2057. * console.log(new TextDecoder().decode(buf)); // "world"
  2058. * ```
  2059. *
  2060. * The seek modes work as follows:
  2061. *
  2062. * ```ts
  2063. * // Given file.rid pointing to file with "Hello world", which is 11 bytes long:
  2064. * using file = Deno.openSync(
  2065. * "hello.txt",
  2066. * { read: true, write: true, truncate: true, create: true },
  2067. * );
  2068. * file.writeSync(new TextEncoder().encode("Hello world"));
  2069. *
  2070. * // Seek 6 bytes from the start of the file
  2071. * console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.Start)); // "6"
  2072. * // Seek 2 more bytes from the current position
  2073. * console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.Current)); // "8"
  2074. * // Seek backwards 2 bytes from the end of the file
  2075. * console.log(Deno.seekSync(file.rid, -2, Deno.SeekMode.End)); // "9" (i.e. 11-2)
  2076. * ```
  2077. *
  2078. * @deprecated This will be removed in Deno 2.0. See the
  2079. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2080. * for migration instructions.
  2081. *
  2082. * @category I/O
  2083. */
  2084. export function seekSync(
  2085. rid: number,
  2086. offset: number | bigint,
  2087. whence: SeekMode,
  2088. ): number;
  2089. /**
  2090. * Flushes any pending data and metadata operations of the given file stream
  2091. * to disk.
  2092. *
  2093. * ```ts
  2094. * const file = await Deno.open(
  2095. * "my_file.txt",
  2096. * { read: true, write: true, create: true },
  2097. * );
  2098. * await file.write(new TextEncoder().encode("Hello World"));
  2099. * await file.truncate(1);
  2100. * await Deno.fsync(file.rid);
  2101. * console.log(await Deno.readTextFile("my_file.txt")); // H
  2102. * ```
  2103. *
  2104. * @category File System
  2105. */
  2106. export function fsync(rid: number): Promise<void>;
  2107. /**
  2108. * Synchronously flushes any pending data and metadata operations of the given
  2109. * file stream to disk.
  2110. *
  2111. * ```ts
  2112. * const file = Deno.openSync(
  2113. * "my_file.txt",
  2114. * { read: true, write: true, create: true },
  2115. * );
  2116. * file.writeSync(new TextEncoder().encode("Hello World"));
  2117. * file.truncateSync(1);
  2118. * Deno.fsyncSync(file.rid);
  2119. * console.log(Deno.readTextFileSync("my_file.txt")); // H
  2120. * ```
  2121. *
  2122. * @category File System
  2123. */
  2124. export function fsyncSync(rid: number): void;
  2125. /**
  2126. * Flushes any pending data operations of the given file stream to disk.
  2127. * ```ts
  2128. * const file = await Deno.open(
  2129. * "my_file.txt",
  2130. * { read: true, write: true, create: true },
  2131. * );
  2132. * await file.write(new TextEncoder().encode("Hello World"));
  2133. * await Deno.fdatasync(file.rid);
  2134. * console.log(await Deno.readTextFile("my_file.txt")); // Hello World
  2135. * ```
  2136. *
  2137. * @category File System
  2138. */
  2139. export function fdatasync(rid: number): Promise<void>;
  2140. /**
  2141. * Synchronously flushes any pending data operations of the given file stream
  2142. * to disk.
  2143. *
  2144. * ```ts
  2145. * const file = Deno.openSync(
  2146. * "my_file.txt",
  2147. * { read: true, write: true, create: true },
  2148. * );
  2149. * file.writeSync(new TextEncoder().encode("Hello World"));
  2150. * Deno.fdatasyncSync(file.rid);
  2151. * console.log(Deno.readTextFileSync("my_file.txt")); // Hello World
  2152. * ```
  2153. *
  2154. * @category File System
  2155. */
  2156. export function fdatasyncSync(rid: number): void;
  2157. /** Close the given resource ID (`rid`) which has been previously opened, such
  2158. * as via opening or creating a file. Closing a file when you are finished
  2159. * with it is important to avoid leaking resources.
  2160. *
  2161. * ```ts
  2162. * const file = await Deno.open("my_file.txt");
  2163. * // do work with "file" object
  2164. * Deno.close(file.rid);
  2165. * ```
  2166. *
  2167. * It is recommended to define the variable with the `using` keyword so the
  2168. * runtime will automatically close the resource when it goes out of scope.
  2169. * Doing so negates the need to manually close the resource.
  2170. *
  2171. * ```ts
  2172. * using file = await Deno.open("my_file.txt");
  2173. * // do work with "file" object
  2174. * ```
  2175. *
  2176. * @deprecated This will be removed in Deno 2.0. See the
  2177. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2178. * for migration instructions.
  2179. *
  2180. * @category I/O
  2181. */
  2182. export function close(rid: number): void;
  2183. /** The Deno abstraction for reading and writing files.
  2184. *
  2185. * This is the most straight forward way of handling files within Deno and is
  2186. * recommended over using the discrete functions within the `Deno` namespace.
  2187. *
  2188. * ```ts
  2189. * using file = await Deno.open("/foo/bar.txt", { read: true });
  2190. * const fileInfo = await file.stat();
  2191. * if (fileInfo.isFile) {
  2192. * const buf = new Uint8Array(100);
  2193. * const numberOfBytesRead = await file.read(buf); // 11 bytes
  2194. * const text = new TextDecoder().decode(buf); // "hello world"
  2195. * }
  2196. * ```
  2197. *
  2198. * @category File System
  2199. */
  2200. export class FsFile
  2201. implements
  2202. Reader,
  2203. ReaderSync,
  2204. Writer,
  2205. WriterSync,
  2206. Seeker,
  2207. SeekerSync,
  2208. Closer,
  2209. Disposable {
  2210. /**
  2211. * The resource ID associated with the file instance. The resource ID
  2212. * should be considered an opaque reference to resource.
  2213. *
  2214. * @deprecated This will be removed in Deno 2.0. See the
  2215. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2216. * for migration instructions.
  2217. */
  2218. readonly rid: number;
  2219. /** A {@linkcode ReadableStream} instance representing to the byte contents
  2220. * of the file. This makes it easy to interoperate with other web streams
  2221. * based APIs.
  2222. *
  2223. * ```ts
  2224. * using file = await Deno.open("my_file.txt", { read: true });
  2225. * const decoder = new TextDecoder();
  2226. * for await (const chunk of file.readable) {
  2227. * console.log(decoder.decode(chunk));
  2228. * }
  2229. * ```
  2230. */
  2231. readonly readable: ReadableStream<Uint8Array>;
  2232. /** A {@linkcode WritableStream} instance to write the contents of the
  2233. * file. This makes it easy to interoperate with other web streams based
  2234. * APIs.
  2235. *
  2236. * ```ts
  2237. * const items = ["hello", "world"];
  2238. * using file = await Deno.open("my_file.txt", { write: true });
  2239. * const encoder = new TextEncoder();
  2240. * const writer = file.writable.getWriter();
  2241. * for (const item of items) {
  2242. * await writer.write(encoder.encode(item));
  2243. * }
  2244. * ```
  2245. */
  2246. readonly writable: WritableStream<Uint8Array>;
  2247. /**
  2248. * The constructor which takes a resource ID. Generally `FsFile` should
  2249. * not be constructed directly. Instead use {@linkcode Deno.open} or
  2250. * {@linkcode Deno.openSync} to create a new instance of `FsFile`.
  2251. *
  2252. * @deprecated This will be removed in Deno 2.0. See the
  2253. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2254. * for migration instructions.
  2255. */
  2256. constructor(rid: number);
  2257. /** Write the contents of the array buffer (`p`) to the file.
  2258. *
  2259. * Resolves to the number of bytes written.
  2260. *
  2261. * **It is not guaranteed that the full buffer will be written in a single
  2262. * call.**
  2263. *
  2264. * ```ts
  2265. * const encoder = new TextEncoder();
  2266. * const data = encoder.encode("Hello world");
  2267. * using file = await Deno.open("/foo/bar.txt", { write: true });
  2268. * const bytesWritten = await file.write(data); // 11
  2269. * ```
  2270. *
  2271. * @category I/O
  2272. */
  2273. write(p: Uint8Array): Promise<number>;
  2274. /** Synchronously write the contents of the array buffer (`p`) to the file.
  2275. *
  2276. * Returns the number of bytes written.
  2277. *
  2278. * **It is not guaranteed that the full buffer will be written in a single
  2279. * call.**
  2280. *
  2281. * ```ts
  2282. * const encoder = new TextEncoder();
  2283. * const data = encoder.encode("Hello world");
  2284. * using file = Deno.openSync("/foo/bar.txt", { write: true });
  2285. * const bytesWritten = file.writeSync(data); // 11
  2286. * ```
  2287. */
  2288. writeSync(p: Uint8Array): number;
  2289. /** Truncates (or extends) the file to reach the specified `len`. If `len`
  2290. * is not specified, then the entire file contents are truncated.
  2291. *
  2292. * ### Truncate the entire file
  2293. *
  2294. * ```ts
  2295. * using file = await Deno.open("my_file.txt", { write: true });
  2296. * await file.truncate();
  2297. * ```
  2298. *
  2299. * ### Truncate part of the file
  2300. *
  2301. * ```ts
  2302. * // if "my_file.txt" contains the text "hello world":
  2303. * using file = await Deno.open("my_file.txt", { write: true });
  2304. * await file.truncate(7);
  2305. * const buf = new Uint8Array(100);
  2306. * await file.read(buf);
  2307. * const text = new TextDecoder().decode(buf); // "hello w"
  2308. * ```
  2309. */
  2310. truncate(len?: number): Promise<void>;
  2311. /** Synchronously truncates (or extends) the file to reach the specified
  2312. * `len`. If `len` is not specified, then the entire file contents are
  2313. * truncated.
  2314. *
  2315. * ### Truncate the entire file
  2316. *
  2317. * ```ts
  2318. * using file = Deno.openSync("my_file.txt", { write: true });
  2319. * file.truncateSync();
  2320. * ```
  2321. *
  2322. * ### Truncate part of the file
  2323. *
  2324. * ```ts
  2325. * // if "my_file.txt" contains the text "hello world":
  2326. * using file = Deno.openSync("my_file.txt", { write: true });
  2327. * file.truncateSync(7);
  2328. * const buf = new Uint8Array(100);
  2329. * file.readSync(buf);
  2330. * const text = new TextDecoder().decode(buf); // "hello w"
  2331. * ```
  2332. */
  2333. truncateSync(len?: number): void;
  2334. /** Read the file into an array buffer (`p`).
  2335. *
  2336. * Resolves to either the number of bytes read during the operation or EOF
  2337. * (`null`) if there was nothing more to read.
  2338. *
  2339. * It is possible for a read to successfully return with `0` bytes. This
  2340. * does not indicate EOF.
  2341. *
  2342. * **It is not guaranteed that the full buffer will be read in a single
  2343. * call.**
  2344. *
  2345. * ```ts
  2346. * // if "/foo/bar.txt" contains the text "hello world":
  2347. * using file = await Deno.open("/foo/bar.txt");
  2348. * const buf = new Uint8Array(100);
  2349. * const numberOfBytesRead = await file.read(buf); // 11 bytes
  2350. * const text = new TextDecoder().decode(buf); // "hello world"
  2351. * ```
  2352. */
  2353. read(p: Uint8Array): Promise<number | null>;
  2354. /** Synchronously read from the file into an array buffer (`p`).
  2355. *
  2356. * Returns either the number of bytes read during the operation or EOF
  2357. * (`null`) if there was nothing more to read.
  2358. *
  2359. * It is possible for a read to successfully return with `0` bytes. This
  2360. * does not indicate EOF.
  2361. *
  2362. * **It is not guaranteed that the full buffer will be read in a single
  2363. * call.**
  2364. *
  2365. * ```ts
  2366. * // if "/foo/bar.txt" contains the text "hello world":
  2367. * using file = Deno.openSync("/foo/bar.txt");
  2368. * const buf = new Uint8Array(100);
  2369. * const numberOfBytesRead = file.readSync(buf); // 11 bytes
  2370. * const text = new TextDecoder().decode(buf); // "hello world"
  2371. * ```
  2372. */
  2373. readSync(p: Uint8Array): number | null;
  2374. /** Seek to the given `offset` under mode given by `whence`. The call
  2375. * resolves to the new position within the resource (bytes from the start).
  2376. *
  2377. * ```ts
  2378. * // Given file pointing to file with "Hello world", which is 11 bytes long:
  2379. * using file = await Deno.open(
  2380. * "hello.txt",
  2381. * { read: true, write: true, truncate: true, create: true },
  2382. * );
  2383. * await file.write(new TextEncoder().encode("Hello world"));
  2384. *
  2385. * // advance cursor 6 bytes
  2386. * const cursorPosition = await file.seek(6, Deno.SeekMode.Start);
  2387. * console.log(cursorPosition); // 6
  2388. * const buf = new Uint8Array(100);
  2389. * await file.read(buf);
  2390. * console.log(new TextDecoder().decode(buf)); // "world"
  2391. * ```
  2392. *
  2393. * The seek modes work as follows:
  2394. *
  2395. * ```ts
  2396. * // Given file.rid pointing to file with "Hello world", which is 11 bytes long:
  2397. * const file = await Deno.open(
  2398. * "hello.txt",
  2399. * { read: true, write: true, truncate: true, create: true },
  2400. * );
  2401. * await file.write(new TextEncoder().encode("Hello world"));
  2402. *
  2403. * // Seek 6 bytes from the start of the file
  2404. * console.log(await file.seek(6, Deno.SeekMode.Start)); // "6"
  2405. * // Seek 2 more bytes from the current position
  2406. * console.log(await file.seek(2, Deno.SeekMode.Current)); // "8"
  2407. * // Seek backwards 2 bytes from the end of the file
  2408. * console.log(await file.seek(-2, Deno.SeekMode.End)); // "9" (i.e. 11-2)
  2409. * ```
  2410. */
  2411. seek(offset: number | bigint, whence: SeekMode): Promise<number>;
  2412. /** Synchronously seek to the given `offset` under mode given by `whence`.
  2413. * The new position within the resource (bytes from the start) is returned.
  2414. *
  2415. * ```ts
  2416. * using file = Deno.openSync(
  2417. * "hello.txt",
  2418. * { read: true, write: true, truncate: true, create: true },
  2419. * );
  2420. * file.writeSync(new TextEncoder().encode("Hello world"));
  2421. *
  2422. * // advance cursor 6 bytes
  2423. * const cursorPosition = file.seekSync(6, Deno.SeekMode.Start);
  2424. * console.log(cursorPosition); // 6
  2425. * const buf = new Uint8Array(100);
  2426. * file.readSync(buf);
  2427. * console.log(new TextDecoder().decode(buf)); // "world"
  2428. * ```
  2429. *
  2430. * The seek modes work as follows:
  2431. *
  2432. * ```ts
  2433. * // Given file.rid pointing to file with "Hello world", which is 11 bytes long:
  2434. * using file = Deno.openSync(
  2435. * "hello.txt",
  2436. * { read: true, write: true, truncate: true, create: true },
  2437. * );
  2438. * file.writeSync(new TextEncoder().encode("Hello world"));
  2439. *
  2440. * // Seek 6 bytes from the start of the file
  2441. * console.log(file.seekSync(6, Deno.SeekMode.Start)); // "6"
  2442. * // Seek 2 more bytes from the current position
  2443. * console.log(file.seekSync(2, Deno.SeekMode.Current)); // "8"
  2444. * // Seek backwards 2 bytes from the end of the file
  2445. * console.log(file.seekSync(-2, Deno.SeekMode.End)); // "9" (i.e. 11-2)
  2446. * ```
  2447. */
  2448. seekSync(offset: number | bigint, whence: SeekMode): number;
  2449. /** Resolves to a {@linkcode Deno.FileInfo} for the file.
  2450. *
  2451. * ```ts
  2452. * import { assert } from "jsr:@std/assert";
  2453. *
  2454. * using file = await Deno.open("hello.txt");
  2455. * const fileInfo = await file.stat();
  2456. * assert(fileInfo.isFile);
  2457. * ```
  2458. */
  2459. stat(): Promise<FileInfo>;
  2460. /** Synchronously returns a {@linkcode Deno.FileInfo} for the file.
  2461. *
  2462. * ```ts
  2463. * import { assert } from "jsr:@std/assert";
  2464. *
  2465. * using file = Deno.openSync("hello.txt")
  2466. * const fileInfo = file.statSync();
  2467. * assert(fileInfo.isFile);
  2468. * ```
  2469. */
  2470. statSync(): FileInfo;
  2471. /**
  2472. * Flushes any pending data and metadata operations of the given file
  2473. * stream to disk.
  2474. *
  2475. * ```ts
  2476. * const file = await Deno.open(
  2477. * "my_file.txt",
  2478. * { read: true, write: true, create: true },
  2479. * );
  2480. * await file.write(new TextEncoder().encode("Hello World"));
  2481. * await file.truncate(1);
  2482. * await file.sync();
  2483. * console.log(await Deno.readTextFile("my_file.txt")); // H
  2484. * ```
  2485. *
  2486. * @category I/O
  2487. */
  2488. sync(): Promise<void>;
  2489. /**
  2490. * Synchronously flushes any pending data and metadata operations of the given
  2491. * file stream to disk.
  2492. *
  2493. * ```ts
  2494. * const file = Deno.openSync(
  2495. * "my_file.txt",
  2496. * { read: true, write: true, create: true },
  2497. * );
  2498. * file.writeSync(new TextEncoder().encode("Hello World"));
  2499. * file.truncateSync(1);
  2500. * file.syncSync();
  2501. * console.log(Deno.readTextFileSync("my_file.txt")); // H
  2502. * ```
  2503. *
  2504. * @category I/O
  2505. */
  2506. syncSync(): void;
  2507. /**
  2508. * Flushes any pending data operations of the given file stream to disk.
  2509. * ```ts
  2510. * using file = await Deno.open(
  2511. * "my_file.txt",
  2512. * { read: true, write: true, create: true },
  2513. * );
  2514. * await file.write(new TextEncoder().encode("Hello World"));
  2515. * await file.syncData();
  2516. * console.log(await Deno.readTextFile("my_file.txt")); // Hello World
  2517. * ```
  2518. *
  2519. * @category I/O
  2520. */
  2521. syncData(): Promise<void>;
  2522. /**
  2523. * Synchronously flushes any pending data operations of the given file stream
  2524. * to disk.
  2525. *
  2526. * ```ts
  2527. * using file = Deno.openSync(
  2528. * "my_file.txt",
  2529. * { read: true, write: true, create: true },
  2530. * );
  2531. * file.writeSync(new TextEncoder().encode("Hello World"));
  2532. * file.syncDataSync();
  2533. * console.log(Deno.readTextFileSync("my_file.txt")); // Hello World
  2534. * ```
  2535. *
  2536. * @category I/O
  2537. */
  2538. syncDataSync(): void;
  2539. /**
  2540. * Changes the access (`atime`) and modification (`mtime`) times of the
  2541. * file stream resource. Given times are either in seconds (UNIX epoch
  2542. * time) or as `Date` objects.
  2543. *
  2544. * ```ts
  2545. * using file = await Deno.open("file.txt", { create: true, write: true });
  2546. * await file.utime(1556495550, new Date());
  2547. * ```
  2548. *
  2549. * @category File System
  2550. */
  2551. utime(atime: number | Date, mtime: number | Date): Promise<void>;
  2552. /**
  2553. * Synchronously changes the access (`atime`) and modification (`mtime`)
  2554. * times of the file stream resource. Given times are either in seconds
  2555. * (UNIX epoch time) or as `Date` objects.
  2556. *
  2557. * ```ts
  2558. * using file = Deno.openSync("file.txt", { create: true, write: true });
  2559. * file.utime(1556495550, new Date());
  2560. * ```
  2561. *
  2562. * @category File System
  2563. */
  2564. utimeSync(atime: number | Date, mtime: number | Date): void;
  2565. /** **UNSTABLE**: New API, yet to be vetted.
  2566. *
  2567. * Checks if the file resource is a TTY (terminal).
  2568. *
  2569. * ```ts
  2570. * // This example is system and context specific
  2571. * using file = await Deno.open("/dev/tty6");
  2572. * file.isTerminal(); // true
  2573. * ```
  2574. */
  2575. isTerminal(): boolean;
  2576. /** **UNSTABLE**: New API, yet to be vetted.
  2577. *
  2578. * Set TTY to be under raw mode or not. In raw mode, characters are read and
  2579. * returned as is, without being processed. All special processing of
  2580. * characters by the terminal is disabled, including echoing input
  2581. * characters. Reading from a TTY device in raw mode is faster than reading
  2582. * from a TTY device in canonical mode.
  2583. *
  2584. * ```ts
  2585. * using file = await Deno.open("/dev/tty6");
  2586. * file.setRaw(true, { cbreak: true });
  2587. * ```
  2588. */
  2589. setRaw(mode: boolean, options?: SetRawOptions): void;
  2590. /**
  2591. * Acquire an advisory file-system lock for the file.
  2592. *
  2593. * @param [exclusive=false]
  2594. */
  2595. lock(exclusive?: boolean): Promise<void>;
  2596. /**
  2597. * Synchronously acquire an advisory file-system lock synchronously for the file.
  2598. *
  2599. * @param [exclusive=false]
  2600. */
  2601. lockSync(exclusive?: boolean): void;
  2602. /**
  2603. * Release an advisory file-system lock for the file.
  2604. */
  2605. unlock(): Promise<void>;
  2606. /**
  2607. * Synchronously release an advisory file-system lock for the file.
  2608. */
  2609. unlockSync(): void;
  2610. /** Close the file. Closing a file when you are finished with it is
  2611. * important to avoid leaking resources.
  2612. *
  2613. * ```ts
  2614. * using file = await Deno.open("my_file.txt");
  2615. * // do work with "file" object
  2616. * ```
  2617. */
  2618. close(): void;
  2619. [Symbol.dispose](): void;
  2620. }
  2621. /**
  2622. * The Deno abstraction for reading and writing files.
  2623. *
  2624. * @deprecated This will be removed in Deno 2.0. See the
  2625. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2626. * for migration instructions.
  2627. *
  2628. * @category File System
  2629. */
  2630. export const File: typeof FsFile;
  2631. /** Gets the size of the console as columns/rows.
  2632. *
  2633. * ```ts
  2634. * const { columns, rows } = Deno.consoleSize();
  2635. * ```
  2636. *
  2637. * This returns the size of the console window as reported by the operating
  2638. * system. It's not a reflection of how many characters will fit within the
  2639. * console window, but can be used as part of that calculation.
  2640. *
  2641. * @category I/O
  2642. */
  2643. export function consoleSize(): {
  2644. columns: number;
  2645. rows: number;
  2646. };
  2647. /** @category I/O */
  2648. export interface SetRawOptions {
  2649. /**
  2650. * The `cbreak` option can be used to indicate that characters that
  2651. * correspond to a signal should still be generated. When disabling raw
  2652. * mode, this option is ignored. This functionality currently only works on
  2653. * Linux and Mac OS.
  2654. */
  2655. cbreak: boolean;
  2656. }
  2657. /** A reference to `stdin` which can be used to read directly from `stdin`.
  2658. * It implements the Deno specific {@linkcode Reader}, {@linkcode ReaderSync},
  2659. * and {@linkcode Closer} interfaces as well as provides a
  2660. * {@linkcode ReadableStream} interface.
  2661. *
  2662. * ### Reading chunks from the readable stream
  2663. *
  2664. * ```ts
  2665. * const decoder = new TextDecoder();
  2666. * for await (const chunk of Deno.stdin.readable) {
  2667. * const text = decoder.decode(chunk);
  2668. * // do something with the text
  2669. * }
  2670. * ```
  2671. *
  2672. * @category I/O
  2673. */
  2674. export const stdin: Reader & ReaderSync & Closer & {
  2675. /**
  2676. * The resource ID assigned to `stdin`. This can be used with the discrete
  2677. * I/O functions in the `Deno` namespace.
  2678. *
  2679. * @deprecated This will be soft-removed in Deno 2.0. See the
  2680. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2681. * for migration instructions.
  2682. */
  2683. readonly rid: number;
  2684. /** A readable stream interface to `stdin`. */
  2685. readonly readable: ReadableStream<Uint8Array>;
  2686. /**
  2687. * Set TTY to be under raw mode or not. In raw mode, characters are read and
  2688. * returned as is, without being processed. All special processing of
  2689. * characters by the terminal is disabled, including echoing input
  2690. * characters. Reading from a TTY device in raw mode is faster than reading
  2691. * from a TTY device in canonical mode.
  2692. *
  2693. * ```ts
  2694. * Deno.stdin.setRaw(true, { cbreak: true });
  2695. * ```
  2696. *
  2697. * @category I/O
  2698. */
  2699. setRaw(mode: boolean, options?: SetRawOptions): void;
  2700. /**
  2701. * Checks if `stdin` is a TTY (terminal).
  2702. *
  2703. * ```ts
  2704. * // This example is system and context specific
  2705. * Deno.stdin.isTerminal(); // true
  2706. * ```
  2707. *
  2708. * @category I/O
  2709. */
  2710. isTerminal(): boolean;
  2711. };
  2712. /** A reference to `stdout` which can be used to write directly to `stdout`.
  2713. * It implements the Deno specific {@linkcode Writer}, {@linkcode WriterSync},
  2714. * and {@linkcode Closer} interfaces as well as provides a
  2715. * {@linkcode WritableStream} interface.
  2716. *
  2717. * These are low level constructs, and the {@linkcode console} interface is a
  2718. * more straight forward way to interact with `stdout` and `stderr`.
  2719. *
  2720. * @category I/O
  2721. */
  2722. export const stdout: Writer & WriterSync & Closer & {
  2723. /**
  2724. * The resource ID assigned to `stdout`. This can be used with the discrete
  2725. * I/O functions in the `Deno` namespace.
  2726. *
  2727. * @deprecated This will be soft-removed in Deno 2.0. See the
  2728. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2729. * for migration instructions.
  2730. */
  2731. readonly rid: number;
  2732. /** A writable stream interface to `stdout`. */
  2733. readonly writable: WritableStream<Uint8Array>;
  2734. /**
  2735. * Checks if `stdout` is a TTY (terminal).
  2736. *
  2737. * ```ts
  2738. * // This example is system and context specific
  2739. * Deno.stdout.isTerminal(); // true
  2740. * ```
  2741. *
  2742. * @category I/O
  2743. */
  2744. isTerminal(): boolean;
  2745. };
  2746. /** A reference to `stderr` which can be used to write directly to `stderr`.
  2747. * It implements the Deno specific {@linkcode Writer}, {@linkcode WriterSync},
  2748. * and {@linkcode Closer} interfaces as well as provides a
  2749. * {@linkcode WritableStream} interface.
  2750. *
  2751. * These are low level constructs, and the {@linkcode console} interface is a
  2752. * more straight forward way to interact with `stdout` and `stderr`.
  2753. *
  2754. * @category I/O
  2755. */
  2756. export const stderr: Writer & WriterSync & Closer & {
  2757. /**
  2758. * The resource ID assigned to `stderr`. This can be used with the discrete
  2759. * I/O functions in the `Deno` namespace.
  2760. *
  2761. * @deprecated This will be soft-removed in Deno 2.0. See the
  2762. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2763. * for migration instructions.
  2764. */
  2765. readonly rid: number;
  2766. /** A writable stream interface to `stderr`. */
  2767. readonly writable: WritableStream<Uint8Array>;
  2768. /**
  2769. * Checks if `stderr` is a TTY (terminal).
  2770. *
  2771. * ```ts
  2772. * // This example is system and context specific
  2773. * Deno.stderr.isTerminal(); // true
  2774. * ```
  2775. *
  2776. * @category I/O
  2777. */
  2778. isTerminal(): boolean;
  2779. };
  2780. /**
  2781. * Options which can be set when doing {@linkcode Deno.open} and
  2782. * {@linkcode Deno.openSync}.
  2783. *
  2784. * @category File System */
  2785. export interface OpenOptions {
  2786. /** Sets the option for read access. This option, when `true`, means that
  2787. * the file should be read-able if opened.
  2788. *
  2789. * @default {true} */
  2790. read?: boolean;
  2791. /** Sets the option for write access. This option, when `true`, means that
  2792. * the file should be write-able if opened. If the file already exists,
  2793. * any write calls on it will overwrite its contents, by default without
  2794. * truncating it.
  2795. *
  2796. * @default {false} */
  2797. write?: boolean;
  2798. /** Sets the option for the append mode. This option, when `true`, means
  2799. * that writes will append to a file instead of overwriting previous
  2800. * contents.
  2801. *
  2802. * Note that setting `{ write: true, append: true }` has the same effect as
  2803. * setting only `{ append: true }`.
  2804. *
  2805. * @default {false} */
  2806. append?: boolean;
  2807. /** Sets the option for truncating a previous file. If a file is
  2808. * successfully opened with this option set it will truncate the file to `0`
  2809. * size if it already exists. The file must be opened with write access
  2810. * for truncate to work.
  2811. *
  2812. * @default {false} */
  2813. truncate?: boolean;
  2814. /** Sets the option to allow creating a new file, if one doesn't already
  2815. * exist at the specified path. Requires write or append access to be
  2816. * used.
  2817. *
  2818. * @default {false} */
  2819. create?: boolean;
  2820. /** If set to `true`, no file, directory, or symlink is allowed to exist at
  2821. * the target location. Requires write or append access to be used. When
  2822. * createNew is set to `true`, create and truncate are ignored.
  2823. *
  2824. * @default {false} */
  2825. createNew?: boolean;
  2826. /** Permissions to use if creating the file (defaults to `0o666`, before
  2827. * the process's umask).
  2828. *
  2829. * Ignored on Windows. */
  2830. mode?: number;
  2831. }
  2832. /**
  2833. * Options which can be set when using {@linkcode Deno.readFile} or
  2834. * {@linkcode Deno.readFileSync}.
  2835. *
  2836. * @category File System */
  2837. export interface ReadFileOptions {
  2838. /**
  2839. * An abort signal to allow cancellation of the file read operation.
  2840. * If the signal becomes aborted the readFile operation will be stopped
  2841. * and the promise returned will be rejected with an AbortError.
  2842. */
  2843. signal?: AbortSignal;
  2844. }
  2845. /**
  2846. * Check if a given resource id (`rid`) is a TTY (a terminal).
  2847. *
  2848. * ```ts
  2849. * // This example is system and context specific
  2850. * const nonTTYRid = Deno.openSync("my_file.txt").rid;
  2851. * const ttyRid = Deno.openSync("/dev/tty6").rid;
  2852. * console.log(Deno.isatty(nonTTYRid)); // false
  2853. * console.log(Deno.isatty(ttyRid)); // true
  2854. * ```
  2855. *
  2856. * @deprecated This will be soft-removed in Deno 2.0. See the
  2857. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2858. * for migration instructions.
  2859. *
  2860. * @category I/O
  2861. */
  2862. export function isatty(rid: number): boolean;
  2863. /**
  2864. * A variable-sized buffer of bytes with `read()` and `write()` methods.
  2865. *
  2866. * @deprecated This will be removed in Deno 2.0. See the
  2867. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2868. * for migration instructions.
  2869. *
  2870. * @category I/O
  2871. */
  2872. export class Buffer implements Reader, ReaderSync, Writer, WriterSync {
  2873. constructor(ab?: ArrayBuffer);
  2874. /** Returns a slice holding the unread portion of the buffer.
  2875. *
  2876. * The slice is valid for use only until the next buffer modification (that
  2877. * is, only until the next call to a method like `read()`, `write()`,
  2878. * `reset()`, or `truncate()`). If `options.copy` is false the slice aliases the buffer content at
  2879. * least until the next buffer modification, so immediate changes to the
  2880. * slice will affect the result of future reads.
  2881. * @param options Defaults to `{ copy: true }`
  2882. */
  2883. bytes(options?: { copy?: boolean }): Uint8Array;
  2884. /** Returns whether the unread portion of the buffer is empty. */
  2885. empty(): boolean;
  2886. /** A read only number of bytes of the unread portion of the buffer. */
  2887. readonly length: number;
  2888. /** The read only capacity of the buffer's underlying byte slice, that is,
  2889. * the total space allocated for the buffer's data. */
  2890. readonly capacity: number;
  2891. /** Discards all but the first `n` unread bytes from the buffer but
  2892. * continues to use the same allocated storage. It throws if `n` is
  2893. * negative or greater than the length of the buffer. */
  2894. truncate(n: number): void;
  2895. /** Resets the buffer to be empty, but it retains the underlying storage for
  2896. * use by future writes. `.reset()` is the same as `.truncate(0)`. */
  2897. reset(): void;
  2898. /** Reads the next `p.length` bytes from the buffer or until the buffer is
  2899. * drained. Returns the number of bytes read. If the buffer has no data to
  2900. * return, the return is EOF (`null`). */
  2901. readSync(p: Uint8Array): number | null;
  2902. /** Reads the next `p.length` bytes from the buffer or until the buffer is
  2903. * drained. Resolves to the number of bytes read. If the buffer has no
  2904. * data to return, resolves to EOF (`null`).
  2905. *
  2906. * NOTE: This methods reads bytes synchronously; it's provided for
  2907. * compatibility with `Reader` interfaces.
  2908. */
  2909. read(p: Uint8Array): Promise<number | null>;
  2910. writeSync(p: Uint8Array): number;
  2911. /** NOTE: This methods writes bytes synchronously; it's provided for
  2912. * compatibility with `Writer` interface. */
  2913. write(p: Uint8Array): Promise<number>;
  2914. /** Grows the buffer's capacity, if necessary, to guarantee space for
  2915. * another `n` bytes. After `.grow(n)`, at least `n` bytes can be written to
  2916. * the buffer without another allocation. If `n` is negative, `.grow()` will
  2917. * throw. If the buffer can't grow it will throw an error.
  2918. *
  2919. * Based on Go Lang's
  2920. * [Buffer.Grow](https://golang.org/pkg/bytes/#Buffer.Grow). */
  2921. grow(n: number): void;
  2922. /** Reads data from `r` until EOF (`null`) and appends it to the buffer,
  2923. * growing the buffer as needed. It resolves to the number of bytes read.
  2924. * If the buffer becomes too large, `.readFrom()` will reject with an error.
  2925. *
  2926. * Based on Go Lang's
  2927. * [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */
  2928. readFrom(r: Reader): Promise<number>;
  2929. /** Reads data from `r` until EOF (`null`) and appends it to the buffer,
  2930. * growing the buffer as needed. It returns the number of bytes read. If the
  2931. * buffer becomes too large, `.readFromSync()` will throw an error.
  2932. *
  2933. * Based on Go Lang's
  2934. * [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */
  2935. readFromSync(r: ReaderSync): number;
  2936. }
  2937. /**
  2938. * Read Reader `r` until EOF (`null`) and resolve to the content as
  2939. * Uint8Array`.
  2940. *
  2941. * @deprecated This will be removed in Deno 2.0. See the
  2942. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2943. * for migration instructions.
  2944. *
  2945. * @category I/O
  2946. */
  2947. export function readAll(r: Reader): Promise<Uint8Array>;
  2948. /**
  2949. * Synchronously reads Reader `r` until EOF (`null`) and returns the content
  2950. * as `Uint8Array`.
  2951. *
  2952. * @deprecated This will be removed in Deno 2.0. See the
  2953. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2954. * for migration instructions.
  2955. *
  2956. * @category I/O
  2957. */
  2958. export function readAllSync(r: ReaderSync): Uint8Array;
  2959. /**
  2960. * Write all the content of the array buffer (`arr`) to the writer (`w`).
  2961. *
  2962. * @deprecated This will be removed in Deno 2.0. See the
  2963. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2964. * for migration instructions.
  2965. *
  2966. * @category I/O
  2967. */
  2968. export function writeAll(w: Writer, arr: Uint8Array): Promise<void>;
  2969. /**
  2970. * Synchronously write all the content of the array buffer (`arr`) to the
  2971. * writer (`w`).
  2972. *
  2973. * @deprecated This will be removed in Deno 2.0. See the
  2974. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  2975. * for migration instructions.
  2976. *
  2977. * @category I/O
  2978. */
  2979. export function writeAllSync(w: WriterSync, arr: Uint8Array): void;
  2980. /**
  2981. * Options which can be set when using {@linkcode Deno.mkdir} and
  2982. * {@linkcode Deno.mkdirSync}.
  2983. *
  2984. * @category File System */
  2985. export interface MkdirOptions {
  2986. /** If set to `true`, means that any intermediate directories will also be
  2987. * created (as with the shell command `mkdir -p`).
  2988. *
  2989. * Intermediate directories are created with the same permissions.
  2990. *
  2991. * When recursive is set to `true`, succeeds silently (without changing any
  2992. * permissions) if a directory already exists at the path, or if the path
  2993. * is a symlink to an existing directory.
  2994. *
  2995. * @default {false} */
  2996. recursive?: boolean;
  2997. /** Permissions to use when creating the directory (defaults to `0o777`,
  2998. * before the process's umask).
  2999. *
  3000. * Ignored on Windows. */
  3001. mode?: number;
  3002. }
  3003. /** Creates a new directory with the specified path.
  3004. *
  3005. * ```ts
  3006. * await Deno.mkdir("new_dir");
  3007. * await Deno.mkdir("nested/directories", { recursive: true });
  3008. * await Deno.mkdir("restricted_access_dir", { mode: 0o700 });
  3009. * ```
  3010. *
  3011. * Defaults to throwing error if the directory already exists.
  3012. *
  3013. * Requires `allow-write` permission.
  3014. *
  3015. * @tags allow-write
  3016. * @category File System
  3017. */
  3018. export function mkdir(
  3019. path: string | URL,
  3020. options?: MkdirOptions,
  3021. ): Promise<void>;
  3022. /** Synchronously creates a new directory with the specified path.
  3023. *
  3024. * ```ts
  3025. * Deno.mkdirSync("new_dir");
  3026. * Deno.mkdirSync("nested/directories", { recursive: true });
  3027. * Deno.mkdirSync("restricted_access_dir", { mode: 0o700 });
  3028. * ```
  3029. *
  3030. * Defaults to throwing error if the directory already exists.
  3031. *
  3032. * Requires `allow-write` permission.
  3033. *
  3034. * @tags allow-write
  3035. * @category File System
  3036. */
  3037. export function mkdirSync(path: string | URL, options?: MkdirOptions): void;
  3038. /**
  3039. * Options which can be set when using {@linkcode Deno.makeTempDir},
  3040. * {@linkcode Deno.makeTempDirSync}, {@linkcode Deno.makeTempFile}, and
  3041. * {@linkcode Deno.makeTempFileSync}.
  3042. *
  3043. * @category File System */
  3044. export interface MakeTempOptions {
  3045. /** Directory where the temporary directory should be created (defaults to
  3046. * the env variable `TMPDIR`, or the system's default, usually `/tmp`).
  3047. *
  3048. * Note that if the passed `dir` is relative, the path returned by
  3049. * `makeTempFile()` and `makeTempDir()` will also be relative. Be mindful of
  3050. * this when changing working directory. */
  3051. dir?: string;
  3052. /** String that should precede the random portion of the temporary
  3053. * directory's name. */
  3054. prefix?: string;
  3055. /** String that should follow the random portion of the temporary
  3056. * directory's name. */
  3057. suffix?: string;
  3058. }
  3059. /** Creates a new temporary directory in the default directory for temporary
  3060. * files, unless `dir` is specified. Other optional options include
  3061. * prefixing and suffixing the directory name with `prefix` and `suffix`
  3062. * respectively.
  3063. *
  3064. * This call resolves to the full path to the newly created directory.
  3065. *
  3066. * Multiple programs calling this function simultaneously will create different
  3067. * directories. It is the caller's responsibility to remove the directory when
  3068. * no longer needed.
  3069. *
  3070. * ```ts
  3071. * const tempDirName0 = await Deno.makeTempDir(); // e.g. /tmp/2894ea76
  3072. * const tempDirName1 = await Deno.makeTempDir({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d
  3073. * ```
  3074. *
  3075. * Requires `allow-write` permission.
  3076. *
  3077. * @tags allow-write
  3078. * @category File System
  3079. */
  3080. // TODO(ry) Doesn't check permissions.
  3081. export function makeTempDir(options?: MakeTempOptions): Promise<string>;
  3082. /** Synchronously creates a new temporary directory in the default directory
  3083. * for temporary files, unless `dir` is specified. Other optional options
  3084. * include prefixing and suffixing the directory name with `prefix` and
  3085. * `suffix` respectively.
  3086. *
  3087. * The full path to the newly created directory is returned.
  3088. *
  3089. * Multiple programs calling this function simultaneously will create different
  3090. * directories. It is the caller's responsibility to remove the directory when
  3091. * no longer needed.
  3092. *
  3093. * ```ts
  3094. * const tempDirName0 = Deno.makeTempDirSync(); // e.g. /tmp/2894ea76
  3095. * const tempDirName1 = Deno.makeTempDirSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d
  3096. * ```
  3097. *
  3098. * Requires `allow-write` permission.
  3099. *
  3100. * @tags allow-write
  3101. * @category File System
  3102. */
  3103. // TODO(ry) Doesn't check permissions.
  3104. export function makeTempDirSync(options?: MakeTempOptions): string;
  3105. /** Creates a new temporary file in the default directory for temporary
  3106. * files, unless `dir` is specified.
  3107. *
  3108. * Other options include prefixing and suffixing the directory name with
  3109. * `prefix` and `suffix` respectively.
  3110. *
  3111. * This call resolves to the full path to the newly created file.
  3112. *
  3113. * Multiple programs calling this function simultaneously will create
  3114. * different files. It is the caller's responsibility to remove the file when
  3115. * no longer needed.
  3116. *
  3117. * ```ts
  3118. * const tmpFileName0 = await Deno.makeTempFile(); // e.g. /tmp/419e0bf2
  3119. * const tmpFileName1 = await Deno.makeTempFile({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098
  3120. * ```
  3121. *
  3122. * Requires `allow-write` permission.
  3123. *
  3124. * @tags allow-write
  3125. * @category File System
  3126. */
  3127. export function makeTempFile(options?: MakeTempOptions): Promise<string>;
  3128. /** Synchronously creates a new temporary file in the default directory for
  3129. * temporary files, unless `dir` is specified.
  3130. *
  3131. * Other options include prefixing and suffixing the directory name with
  3132. * `prefix` and `suffix` respectively.
  3133. *
  3134. * The full path to the newly created file is returned.
  3135. *
  3136. * Multiple programs calling this function simultaneously will create
  3137. * different files. It is the caller's responsibility to remove the file when
  3138. * no longer needed.
  3139. *
  3140. * ```ts
  3141. * const tempFileName0 = Deno.makeTempFileSync(); // e.g. /tmp/419e0bf2
  3142. * const tempFileName1 = Deno.makeTempFileSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098
  3143. * ```
  3144. *
  3145. * Requires `allow-write` permission.
  3146. *
  3147. * @tags allow-write
  3148. * @category File System
  3149. */
  3150. export function makeTempFileSync(options?: MakeTempOptions): string;
  3151. /** Changes the permission of a specific file/directory of specified path.
  3152. * Ignores the process's umask.
  3153. *
  3154. * ```ts
  3155. * await Deno.chmod("/path/to/file", 0o666);
  3156. * ```
  3157. *
  3158. * The mode is a sequence of 3 octal numbers. The first/left-most number
  3159. * specifies the permissions for the owner. The second number specifies the
  3160. * permissions for the group. The last/right-most number specifies the
  3161. * permissions for others. For example, with a mode of 0o764, the owner (7)
  3162. * can read/write/execute, the group (6) can read/write and everyone else (4)
  3163. * can read only.
  3164. *
  3165. * | Number | Description |
  3166. * | ------ | ----------- |
  3167. * | 7 | read, write, and execute |
  3168. * | 6 | read and write |
  3169. * | 5 | read and execute |
  3170. * | 4 | read only |
  3171. * | 3 | write and execute |
  3172. * | 2 | write only |
  3173. * | 1 | execute only |
  3174. * | 0 | no permission |
  3175. *
  3176. * NOTE: This API currently throws on Windows
  3177. *
  3178. * Requires `allow-write` permission.
  3179. *
  3180. * @tags allow-write
  3181. * @category File System
  3182. */
  3183. export function chmod(path: string | URL, mode: number): Promise<void>;
  3184. /** Synchronously changes the permission of a specific file/directory of
  3185. * specified path. Ignores the process's umask.
  3186. *
  3187. * ```ts
  3188. * Deno.chmodSync("/path/to/file", 0o666);
  3189. * ```
  3190. *
  3191. * For a full description, see {@linkcode Deno.chmod}.
  3192. *
  3193. * NOTE: This API currently throws on Windows
  3194. *
  3195. * Requires `allow-write` permission.
  3196. *
  3197. * @tags allow-write
  3198. * @category File System
  3199. */
  3200. export function chmodSync(path: string | URL, mode: number): void;
  3201. /** Change owner of a regular file or directory.
  3202. *
  3203. * This functionality is not available on Windows.
  3204. *
  3205. * ```ts
  3206. * await Deno.chown("myFile.txt", 1000, 1002);
  3207. * ```
  3208. *
  3209. * Requires `allow-write` permission.
  3210. *
  3211. * Throws Error (not implemented) if executed on Windows.
  3212. *
  3213. * @tags allow-write
  3214. * @category File System
  3215. *
  3216. * @param path path to the file
  3217. * @param uid user id (UID) of the new owner, or `null` for no change
  3218. * @param gid group id (GID) of the new owner, or `null` for no change
  3219. */
  3220. export function chown(
  3221. path: string | URL,
  3222. uid: number | null,
  3223. gid: number | null,
  3224. ): Promise<void>;
  3225. /** Synchronously change owner of a regular file or directory.
  3226. *
  3227. * This functionality is not available on Windows.
  3228. *
  3229. * ```ts
  3230. * Deno.chownSync("myFile.txt", 1000, 1002);
  3231. * ```
  3232. *
  3233. * Requires `allow-write` permission.
  3234. *
  3235. * Throws Error (not implemented) if executed on Windows.
  3236. *
  3237. * @tags allow-write
  3238. * @category File System
  3239. *
  3240. * @param path path to the file
  3241. * @param uid user id (UID) of the new owner, or `null` for no change
  3242. * @param gid group id (GID) of the new owner, or `null` for no change
  3243. */
  3244. export function chownSync(
  3245. path: string | URL,
  3246. uid: number | null,
  3247. gid: number | null,
  3248. ): void;
  3249. /**
  3250. * Options which can be set when using {@linkcode Deno.remove} and
  3251. * {@linkcode Deno.removeSync}.
  3252. *
  3253. * @category File System */
  3254. export interface RemoveOptions {
  3255. /** If set to `true`, path will be removed even if it's a non-empty directory.
  3256. *
  3257. * @default {false} */
  3258. recursive?: boolean;
  3259. }
  3260. /** Removes the named file or directory.
  3261. *
  3262. * ```ts
  3263. * await Deno.remove("/path/to/empty_dir/or/file");
  3264. * await Deno.remove("/path/to/populated_dir/or/file", { recursive: true });
  3265. * ```
  3266. *
  3267. * Throws error if permission denied, path not found, or path is a non-empty
  3268. * directory and the `recursive` option isn't set to `true`.
  3269. *
  3270. * Requires `allow-write` permission.
  3271. *
  3272. * @tags allow-write
  3273. * @category File System
  3274. */
  3275. export function remove(
  3276. path: string | URL,
  3277. options?: RemoveOptions,
  3278. ): Promise<void>;
  3279. /** Synchronously removes the named file or directory.
  3280. *
  3281. * ```ts
  3282. * Deno.removeSync("/path/to/empty_dir/or/file");
  3283. * Deno.removeSync("/path/to/populated_dir/or/file", { recursive: true });
  3284. * ```
  3285. *
  3286. * Throws error if permission denied, path not found, or path is a non-empty
  3287. * directory and the `recursive` option isn't set to `true`.
  3288. *
  3289. * Requires `allow-write` permission.
  3290. *
  3291. * @tags allow-write
  3292. * @category File System
  3293. */
  3294. export function removeSync(path: string | URL, options?: RemoveOptions): void;
  3295. /** Synchronously renames (moves) `oldpath` to `newpath`. Paths may be files or
  3296. * directories. If `newpath` already exists and is not a directory,
  3297. * `renameSync()` replaces it. OS-specific restrictions may apply when
  3298. * `oldpath` and `newpath` are in different directories.
  3299. *
  3300. * ```ts
  3301. * Deno.renameSync("old/path", "new/path");
  3302. * ```
  3303. *
  3304. * On Unix-like OSes, this operation does not follow symlinks at either path.
  3305. *
  3306. * It varies between platforms when the operation throws errors, and if so what
  3307. * they are. It's always an error to rename anything to a non-empty directory.
  3308. *
  3309. * Requires `allow-read` and `allow-write` permissions.
  3310. *
  3311. * @tags allow-read, allow-write
  3312. * @category File System
  3313. */
  3314. export function renameSync(
  3315. oldpath: string | URL,
  3316. newpath: string | URL,
  3317. ): void;
  3318. /** Renames (moves) `oldpath` to `newpath`. Paths may be files or directories.
  3319. * If `newpath` already exists and is not a directory, `rename()` replaces it.
  3320. * OS-specific restrictions may apply when `oldpath` and `newpath` are in
  3321. * different directories.
  3322. *
  3323. * ```ts
  3324. * await Deno.rename("old/path", "new/path");
  3325. * ```
  3326. *
  3327. * On Unix-like OSes, this operation does not follow symlinks at either path.
  3328. *
  3329. * It varies between platforms when the operation throws errors, and if so
  3330. * what they are. It's always an error to rename anything to a non-empty
  3331. * directory.
  3332. *
  3333. * Requires `allow-read` and `allow-write` permissions.
  3334. *
  3335. * @tags allow-read, allow-write
  3336. * @category File System
  3337. */
  3338. export function rename(
  3339. oldpath: string | URL,
  3340. newpath: string | URL,
  3341. ): Promise<void>;
  3342. /** Asynchronously reads and returns the entire contents of a file as an UTF-8
  3343. * decoded string. Reading a directory throws an error.
  3344. *
  3345. * ```ts
  3346. * const data = await Deno.readTextFile("hello.txt");
  3347. * console.log(data);
  3348. * ```
  3349. *
  3350. * Requires `allow-read` permission.
  3351. *
  3352. * @tags allow-read
  3353. * @category File System
  3354. */
  3355. export function readTextFile(
  3356. path: string | URL,
  3357. options?: ReadFileOptions,
  3358. ): Promise<string>;
  3359. /** Synchronously reads and returns the entire contents of a file as an UTF-8
  3360. * decoded string. Reading a directory throws an error.
  3361. *
  3362. * ```ts
  3363. * const data = Deno.readTextFileSync("hello.txt");
  3364. * console.log(data);
  3365. * ```
  3366. *
  3367. * Requires `allow-read` permission.
  3368. *
  3369. * @tags allow-read
  3370. * @category File System
  3371. */
  3372. export function readTextFileSync(path: string | URL): string;
  3373. /** Reads and resolves to the entire contents of a file as an array of bytes.
  3374. * `TextDecoder` can be used to transform the bytes to string if required.
  3375. * Reading a directory returns an empty data array.
  3376. *
  3377. * ```ts
  3378. * const decoder = new TextDecoder("utf-8");
  3379. * const data = await Deno.readFile("hello.txt");
  3380. * console.log(decoder.decode(data));
  3381. * ```
  3382. *
  3383. * Requires `allow-read` permission.
  3384. *
  3385. * @tags allow-read
  3386. * @category File System
  3387. */
  3388. export function readFile(
  3389. path: string | URL,
  3390. options?: ReadFileOptions,
  3391. ): Promise<Uint8Array>;
  3392. /** Synchronously reads and returns the entire contents of a file as an array
  3393. * of bytes. `TextDecoder` can be used to transform the bytes to string if
  3394. * required. Reading a directory returns an empty data array.
  3395. *
  3396. * ```ts
  3397. * const decoder = new TextDecoder("utf-8");
  3398. * const data = Deno.readFileSync("hello.txt");
  3399. * console.log(decoder.decode(data));
  3400. * ```
  3401. *
  3402. * Requires `allow-read` permission.
  3403. *
  3404. * @tags allow-read
  3405. * @category File System
  3406. */
  3407. export function readFileSync(path: string | URL): Uint8Array;
  3408. /** Provides information about a file and is returned by
  3409. * {@linkcode Deno.stat}, {@linkcode Deno.lstat}, {@linkcode Deno.statSync},
  3410. * and {@linkcode Deno.lstatSync} or from calling `stat()` and `statSync()`
  3411. * on an {@linkcode Deno.FsFile} instance.
  3412. *
  3413. * @category File System
  3414. */
  3415. export interface FileInfo {
  3416. /** True if this is info for a regular file. Mutually exclusive to
  3417. * `FileInfo.isDirectory` and `FileInfo.isSymlink`. */
  3418. isFile: boolean;
  3419. /** True if this is info for a regular directory. Mutually exclusive to
  3420. * `FileInfo.isFile` and `FileInfo.isSymlink`. */
  3421. isDirectory: boolean;
  3422. /** True if this is info for a symlink. Mutually exclusive to
  3423. * `FileInfo.isFile` and `FileInfo.isDirectory`. */
  3424. isSymlink: boolean;
  3425. /** The size of the file, in bytes. */
  3426. size: number;
  3427. /** The last modification time of the file. This corresponds to the `mtime`
  3428. * field from `stat` on Linux/Mac OS and `ftLastWriteTime` on Windows. This
  3429. * may not be available on all platforms. */
  3430. mtime: Date | null;
  3431. /** The last access time of the file. This corresponds to the `atime`
  3432. * field from `stat` on Unix and `ftLastAccessTime` on Windows. This may not
  3433. * be available on all platforms. */
  3434. atime: Date | null;
  3435. /** The creation time of the file. This corresponds to the `birthtime`
  3436. * field from `stat` on Mac/BSD and `ftCreationTime` on Windows. This may
  3437. * not be available on all platforms. */
  3438. birthtime: Date | null;
  3439. /** ID of the device containing the file. */
  3440. dev: number;
  3441. /** Inode number.
  3442. *
  3443. * _Linux/Mac OS only._ */
  3444. ino: number | null;
  3445. /** The underlying raw `st_mode` bits that contain the standard Unix
  3446. * permissions for this file/directory.
  3447. *
  3448. * _Linux/Mac OS only._ */
  3449. mode: number | null;
  3450. /** Number of hard links pointing to this file.
  3451. *
  3452. * _Linux/Mac OS only._ */
  3453. nlink: number | null;
  3454. /** User ID of the owner of this file.
  3455. *
  3456. * _Linux/Mac OS only._ */
  3457. uid: number | null;
  3458. /** Group ID of the owner of this file.
  3459. *
  3460. * _Linux/Mac OS only._ */
  3461. gid: number | null;
  3462. /** Device ID of this file.
  3463. *
  3464. * _Linux/Mac OS only._ */
  3465. rdev: number | null;
  3466. /** Blocksize for filesystem I/O.
  3467. *
  3468. * _Linux/Mac OS only._ */
  3469. blksize: number | null;
  3470. /** Number of blocks allocated to the file, in 512-byte units.
  3471. *
  3472. * _Linux/Mac OS only._ */
  3473. blocks: number | null;
  3474. /** True if this is info for a block device.
  3475. *
  3476. * _Linux/Mac OS only._ */
  3477. isBlockDevice: boolean | null;
  3478. /** True if this is info for a char device.
  3479. *
  3480. * _Linux/Mac OS only._ */
  3481. isCharDevice: boolean | null;
  3482. /** True if this is info for a fifo.
  3483. *
  3484. * _Linux/Mac OS only._ */
  3485. isFifo: boolean | null;
  3486. /** True if this is info for a socket.
  3487. *
  3488. * _Linux/Mac OS only._ */
  3489. isSocket: boolean | null;
  3490. }
  3491. /** Resolves to the absolute normalized path, with symbolic links resolved.
  3492. *
  3493. * ```ts
  3494. * // e.g. given /home/alice/file.txt and current directory /home/alice
  3495. * await Deno.symlink("file.txt", "symlink_file.txt");
  3496. * const realPath = await Deno.realPath("./file.txt");
  3497. * const realSymLinkPath = await Deno.realPath("./symlink_file.txt");
  3498. * console.log(realPath); // outputs "/home/alice/file.txt"
  3499. * console.log(realSymLinkPath); // outputs "/home/alice/file.txt"
  3500. * ```
  3501. *
  3502. * Requires `allow-read` permission for the target path.
  3503. *
  3504. * Also requires `allow-read` permission for the `CWD` if the target path is
  3505. * relative.
  3506. *
  3507. * @tags allow-read
  3508. * @category File System
  3509. */
  3510. export function realPath(path: string | URL): Promise<string>;
  3511. /** Synchronously returns absolute normalized path, with symbolic links
  3512. * resolved.
  3513. *
  3514. * ```ts
  3515. * // e.g. given /home/alice/file.txt and current directory /home/alice
  3516. * Deno.symlinkSync("file.txt", "symlink_file.txt");
  3517. * const realPath = Deno.realPathSync("./file.txt");
  3518. * const realSymLinkPath = Deno.realPathSync("./symlink_file.txt");
  3519. * console.log(realPath); // outputs "/home/alice/file.txt"
  3520. * console.log(realSymLinkPath); // outputs "/home/alice/file.txt"
  3521. * ```
  3522. *
  3523. * Requires `allow-read` permission for the target path.
  3524. *
  3525. * Also requires `allow-read` permission for the `CWD` if the target path is
  3526. * relative.
  3527. *
  3528. * @tags allow-read
  3529. * @category File System
  3530. */
  3531. export function realPathSync(path: string | URL): string;
  3532. /**
  3533. * Information about a directory entry returned from {@linkcode Deno.readDir}
  3534. * and {@linkcode Deno.readDirSync}.
  3535. *
  3536. * @category File System */
  3537. export interface DirEntry {
  3538. /** The file name of the entry. It is just the entity name and does not
  3539. * include the full path. */
  3540. name: string;
  3541. /** True if this is info for a regular file. Mutually exclusive to
  3542. * `DirEntry.isDirectory` and `DirEntry.isSymlink`. */
  3543. isFile: boolean;
  3544. /** True if this is info for a regular directory. Mutually exclusive to
  3545. * `DirEntry.isFile` and `DirEntry.isSymlink`. */
  3546. isDirectory: boolean;
  3547. /** True if this is info for a symlink. Mutually exclusive to
  3548. * `DirEntry.isFile` and `DirEntry.isDirectory`. */
  3549. isSymlink: boolean;
  3550. }
  3551. /** Reads the directory given by `path` and returns an async iterable of
  3552. * {@linkcode Deno.DirEntry}. The order of entries is not guaranteed.
  3553. *
  3554. * ```ts
  3555. * for await (const dirEntry of Deno.readDir("/")) {
  3556. * console.log(dirEntry.name);
  3557. * }
  3558. * ```
  3559. *
  3560. * Throws error if `path` is not a directory.
  3561. *
  3562. * Requires `allow-read` permission.
  3563. *
  3564. * @tags allow-read
  3565. * @category File System
  3566. */
  3567. export function readDir(path: string | URL): AsyncIterable<DirEntry>;
  3568. /** Synchronously reads the directory given by `path` and returns an iterable
  3569. * of {@linkcode Deno.DirEntry}. The order of entries is not guaranteed.
  3570. *
  3571. * ```ts
  3572. * for (const dirEntry of Deno.readDirSync("/")) {
  3573. * console.log(dirEntry.name);
  3574. * }
  3575. * ```
  3576. *
  3577. * Throws error if `path` is not a directory.
  3578. *
  3579. * Requires `allow-read` permission.
  3580. *
  3581. * @tags allow-read
  3582. * @category File System
  3583. */
  3584. export function readDirSync(path: string | URL): Iterable<DirEntry>;
  3585. /** Copies the contents and permissions of one file to another specified path,
  3586. * by default creating a new file if needed, else overwriting. Fails if target
  3587. * path is a directory or is unwritable.
  3588. *
  3589. * ```ts
  3590. * await Deno.copyFile("from.txt", "to.txt");
  3591. * ```
  3592. *
  3593. * Requires `allow-read` permission on `fromPath`.
  3594. *
  3595. * Requires `allow-write` permission on `toPath`.
  3596. *
  3597. * @tags allow-read, allow-write
  3598. * @category File System
  3599. */
  3600. export function copyFile(
  3601. fromPath: string | URL,
  3602. toPath: string | URL,
  3603. ): Promise<void>;
  3604. /** Synchronously copies the contents and permissions of one file to another
  3605. * specified path, by default creating a new file if needed, else overwriting.
  3606. * Fails if target path is a directory or is unwritable.
  3607. *
  3608. * ```ts
  3609. * Deno.copyFileSync("from.txt", "to.txt");
  3610. * ```
  3611. *
  3612. * Requires `allow-read` permission on `fromPath`.
  3613. *
  3614. * Requires `allow-write` permission on `toPath`.
  3615. *
  3616. * @tags allow-read, allow-write
  3617. * @category File System
  3618. */
  3619. export function copyFileSync(
  3620. fromPath: string | URL,
  3621. toPath: string | URL,
  3622. ): void;
  3623. /** Resolves to the full path destination of the named symbolic link.
  3624. *
  3625. * ```ts
  3626. * await Deno.symlink("./test.txt", "./test_link.txt");
  3627. * const target = await Deno.readLink("./test_link.txt"); // full path of ./test.txt
  3628. * ```
  3629. *
  3630. * Throws TypeError if called with a hard link.
  3631. *
  3632. * Requires `allow-read` permission.
  3633. *
  3634. * @tags allow-read
  3635. * @category File System
  3636. */
  3637. export function readLink(path: string | URL): Promise<string>;
  3638. /** Synchronously returns the full path destination of the named symbolic
  3639. * link.
  3640. *
  3641. * ```ts
  3642. * Deno.symlinkSync("./test.txt", "./test_link.txt");
  3643. * const target = Deno.readLinkSync("./test_link.txt"); // full path of ./test.txt
  3644. * ```
  3645. *
  3646. * Throws TypeError if called with a hard link.
  3647. *
  3648. * Requires `allow-read` permission.
  3649. *
  3650. * @tags allow-read
  3651. * @category File System
  3652. */
  3653. export function readLinkSync(path: string | URL): string;
  3654. /** Resolves to a {@linkcode Deno.FileInfo} for the specified `path`. If
  3655. * `path` is a symlink, information for the symlink will be returned instead
  3656. * of what it points to.
  3657. *
  3658. * ```ts
  3659. * import { assert } from "jsr:@std/assert";
  3660. * const fileInfo = await Deno.lstat("hello.txt");
  3661. * assert(fileInfo.isFile);
  3662. * ```
  3663. *
  3664. * Requires `allow-read` permission.
  3665. *
  3666. * @tags allow-read
  3667. * @category File System
  3668. */
  3669. export function lstat(path: string | URL): Promise<FileInfo>;
  3670. /** Synchronously returns a {@linkcode Deno.FileInfo} for the specified
  3671. * `path`. If `path` is a symlink, information for the symlink will be
  3672. * returned instead of what it points to.
  3673. *
  3674. * ```ts
  3675. * import { assert } from "jsr:@std/assert";
  3676. * const fileInfo = Deno.lstatSync("hello.txt");
  3677. * assert(fileInfo.isFile);
  3678. * ```
  3679. *
  3680. * Requires `allow-read` permission.
  3681. *
  3682. * @tags allow-read
  3683. * @category File System
  3684. */
  3685. export function lstatSync(path: string | URL): FileInfo;
  3686. /** Resolves to a {@linkcode Deno.FileInfo} for the specified `path`. Will
  3687. * always follow symlinks.
  3688. *
  3689. * ```ts
  3690. * import { assert } from "jsr:@std/assert";
  3691. * const fileInfo = await Deno.stat("hello.txt");
  3692. * assert(fileInfo.isFile);
  3693. * ```
  3694. *
  3695. * Requires `allow-read` permission.
  3696. *
  3697. * @tags allow-read
  3698. * @category File System
  3699. */
  3700. export function stat(path: string | URL): Promise<FileInfo>;
  3701. /** Synchronously returns a {@linkcode Deno.FileInfo} for the specified
  3702. * `path`. Will always follow symlinks.
  3703. *
  3704. * ```ts
  3705. * import { assert } from "jsr:@std/assert";
  3706. * const fileInfo = Deno.statSync("hello.txt");
  3707. * assert(fileInfo.isFile);
  3708. * ```
  3709. *
  3710. * Requires `allow-read` permission.
  3711. *
  3712. * @tags allow-read
  3713. * @category File System
  3714. */
  3715. export function statSync(path: string | URL): FileInfo;
  3716. /** Options for writing to a file.
  3717. *
  3718. * @category File System
  3719. */
  3720. export interface WriteFileOptions {
  3721. /** If set to `true`, will append to a file instead of overwriting previous
  3722. * contents.
  3723. *
  3724. * @default {false} */
  3725. append?: boolean;
  3726. /** Sets the option to allow creating a new file, if one doesn't already
  3727. * exist at the specified path.
  3728. *
  3729. * @default {true} */
  3730. create?: boolean;
  3731. /** If set to `true`, no file, directory, or symlink is allowed to exist at
  3732. * the target location. When createNew is set to `true`, `create` is ignored.
  3733. *
  3734. * @default {false} */
  3735. createNew?: boolean;
  3736. /** Permissions always applied to file. */
  3737. mode?: number;
  3738. /** An abort signal to allow cancellation of the file write operation.
  3739. *
  3740. * If the signal becomes aborted the write file operation will be stopped
  3741. * and the promise returned will be rejected with an {@linkcode AbortError}.
  3742. */
  3743. signal?: AbortSignal;
  3744. }
  3745. /** Write `data` to the given `path`, by default creating a new file if
  3746. * needed, else overwriting.
  3747. *
  3748. * ```ts
  3749. * const encoder = new TextEncoder();
  3750. * const data = encoder.encode("Hello world\n");
  3751. * await Deno.writeFile("hello1.txt", data); // overwrite "hello1.txt" or create it
  3752. * await Deno.writeFile("hello2.txt", data, { create: false }); // only works if "hello2.txt" exists
  3753. * await Deno.writeFile("hello3.txt", data, { mode: 0o777 }); // set permissions on new file
  3754. * await Deno.writeFile("hello4.txt", data, { append: true }); // add data to the end of the file
  3755. * ```
  3756. *
  3757. * Requires `allow-write` permission, and `allow-read` if `options.create` is
  3758. * `false`.
  3759. *
  3760. * @tags allow-read, allow-write
  3761. * @category File System
  3762. */
  3763. export function writeFile(
  3764. path: string | URL,
  3765. data: Uint8Array | ReadableStream<Uint8Array>,
  3766. options?: WriteFileOptions,
  3767. ): Promise<void>;
  3768. /** Synchronously write `data` to the given `path`, by default creating a new
  3769. * file if needed, else overwriting.
  3770. *
  3771. * ```ts
  3772. * const encoder = new TextEncoder();
  3773. * const data = encoder.encode("Hello world\n");
  3774. * Deno.writeFileSync("hello1.txt", data); // overwrite "hello1.txt" or create it
  3775. * Deno.writeFileSync("hello2.txt", data, { create: false }); // only works if "hello2.txt" exists
  3776. * Deno.writeFileSync("hello3.txt", data, { mode: 0o777 }); // set permissions on new file
  3777. * Deno.writeFileSync("hello4.txt", data, { append: true }); // add data to the end of the file
  3778. * ```
  3779. *
  3780. * Requires `allow-write` permission, and `allow-read` if `options.create` is
  3781. * `false`.
  3782. *
  3783. * @tags allow-read, allow-write
  3784. * @category File System
  3785. */
  3786. export function writeFileSync(
  3787. path: string | URL,
  3788. data: Uint8Array,
  3789. options?: WriteFileOptions,
  3790. ): void;
  3791. /** Write string `data` to the given `path`, by default creating a new file if
  3792. * needed, else overwriting.
  3793. *
  3794. * ```ts
  3795. * await Deno.writeTextFile("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it
  3796. * ```
  3797. *
  3798. * Requires `allow-write` permission, and `allow-read` if `options.create` is
  3799. * `false`.
  3800. *
  3801. * @tags allow-read, allow-write
  3802. * @category File System
  3803. */
  3804. export function writeTextFile(
  3805. path: string | URL,
  3806. data: string | ReadableStream<string>,
  3807. options?: WriteFileOptions,
  3808. ): Promise<void>;
  3809. /** Synchronously write string `data` to the given `path`, by default creating
  3810. * a new file if needed, else overwriting.
  3811. *
  3812. * ```ts
  3813. * Deno.writeTextFileSync("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it
  3814. * ```
  3815. *
  3816. * Requires `allow-write` permission, and `allow-read` if `options.create` is
  3817. * `false`.
  3818. *
  3819. * @tags allow-read, allow-write
  3820. * @category File System
  3821. */
  3822. export function writeTextFileSync(
  3823. path: string | URL,
  3824. data: string,
  3825. options?: WriteFileOptions,
  3826. ): void;
  3827. /** Truncates (or extends) the specified file, to reach the specified `len`.
  3828. * If `len` is not specified then the entire file contents are truncated.
  3829. *
  3830. * ### Truncate the entire file
  3831. * ```ts
  3832. * await Deno.truncate("my_file.txt");
  3833. * ```
  3834. *
  3835. * ### Truncate part of the file
  3836. *
  3837. * ```ts
  3838. * const file = await Deno.makeTempFile();
  3839. * await Deno.writeTextFile(file, "Hello World");
  3840. * await Deno.truncate(file, 7);
  3841. * const data = await Deno.readFile(file);
  3842. * console.log(new TextDecoder().decode(data)); // "Hello W"
  3843. * ```
  3844. *
  3845. * Requires `allow-write` permission.
  3846. *
  3847. * @tags allow-write
  3848. * @category File System
  3849. */
  3850. export function truncate(name: string, len?: number): Promise<void>;
  3851. /** Synchronously truncates (or extends) the specified file, to reach the
  3852. * specified `len`. If `len` is not specified then the entire file contents
  3853. * are truncated.
  3854. *
  3855. * ### Truncate the entire file
  3856. *
  3857. * ```ts
  3858. * Deno.truncateSync("my_file.txt");
  3859. * ```
  3860. *
  3861. * ### Truncate part of the file
  3862. *
  3863. * ```ts
  3864. * const file = Deno.makeTempFileSync();
  3865. * Deno.writeFileSync(file, new TextEncoder().encode("Hello World"));
  3866. * Deno.truncateSync(file, 7);
  3867. * const data = Deno.readFileSync(file);
  3868. * console.log(new TextDecoder().decode(data));
  3869. * ```
  3870. *
  3871. * Requires `allow-write` permission.
  3872. *
  3873. * @tags allow-write
  3874. * @category File System
  3875. */
  3876. export function truncateSync(name: string, len?: number): void;
  3877. /** @category Runtime
  3878. *
  3879. * @deprecated This will be removed in Deno 2.0.
  3880. */
  3881. export interface OpMetrics {
  3882. opsDispatched: number;
  3883. opsDispatchedSync: number;
  3884. opsDispatchedAsync: number;
  3885. opsDispatchedAsyncUnref: number;
  3886. opsCompleted: number;
  3887. opsCompletedSync: number;
  3888. opsCompletedAsync: number;
  3889. opsCompletedAsyncUnref: number;
  3890. bytesSentControl: number;
  3891. bytesSentData: number;
  3892. bytesReceived: number;
  3893. }
  3894. /** @category Runtime
  3895. *
  3896. * @deprecated This will be removed in Deno 2.0.
  3897. */
  3898. export interface Metrics extends OpMetrics {
  3899. ops: Record<string, OpMetrics>;
  3900. }
  3901. /** Receive metrics from the privileged side of Deno. This is primarily used
  3902. * in the development of Deno. _Ops_, also called _bindings_, are the
  3903. * go-between between Deno JavaScript sandbox and the rest of Deno.
  3904. *
  3905. * ```shell
  3906. * > console.table(Deno.metrics())
  3907. * ┌─────────────────────────┬────────┐
  3908. * │ (index) │ Values │
  3909. * ├─────────────────────────┼────────┤
  3910. * │ opsDispatched │ 3 │
  3911. * │ opsDispatchedSync │ 2 │
  3912. * │ opsDispatchedAsync │ 1 │
  3913. * │ opsDispatchedAsyncUnref │ 0 │
  3914. * │ opsCompleted │ 3 │
  3915. * │ opsCompletedSync │ 2 │
  3916. * │ opsCompletedAsync │ 1 │
  3917. * │ opsCompletedAsyncUnref │ 0 │
  3918. * │ bytesSentControl │ 73 │
  3919. * │ bytesSentData │ 0 │
  3920. * │ bytesReceived │ 375 │
  3921. * └─────────────────────────┴────────┘
  3922. * ```
  3923. *
  3924. * @category Runtime
  3925. *
  3926. * @deprecated This will be removed in Deno 2.0.
  3927. */
  3928. export function metrics(): Metrics;
  3929. /**
  3930. * A map of open resources that Deno is tracking. The key is the resource ID
  3931. * (_rid_) and the value is its representation.
  3932. *
  3933. * @deprecated This will be removed in Deno 2.0.
  3934. *
  3935. * @category Runtime */
  3936. export interface ResourceMap {
  3937. [rid: number]: unknown;
  3938. }
  3939. /** Returns a map of open resource IDs (_rid_) along with their string
  3940. * representations. This is an internal API and as such resource
  3941. * representation has `unknown` type; that means it can change any time and
  3942. * should not be depended upon.
  3943. *
  3944. * ```ts
  3945. * console.log(Deno.resources());
  3946. * // { 0: "stdin", 1: "stdout", 2: "stderr" }
  3947. * Deno.openSync('../test.file');
  3948. * console.log(Deno.resources());
  3949. * // { 0: "stdin", 1: "stdout", 2: "stderr", 3: "fsFile" }
  3950. * ```
  3951. *
  3952. * @deprecated This will be removed in Deno 2.0.
  3953. *
  3954. * @category Runtime
  3955. */
  3956. export function resources(): ResourceMap;
  3957. /**
  3958. * Additional information for FsEvent objects with the "other" kind.
  3959. *
  3960. * - `"rescan"`: rescan notices indicate either a lapse in the events or a
  3961. * change in the filesystem such that events received so far can no longer
  3962. * be relied on to represent the state of the filesystem now. An
  3963. * application that simply reacts to file changes may not care about this.
  3964. * An application that keeps an in-memory representation of the filesystem
  3965. * will need to care, and will need to refresh that representation directly
  3966. * from the filesystem.
  3967. *
  3968. * @category File System
  3969. */
  3970. export type FsEventFlag = "rescan";
  3971. /**
  3972. * Represents a unique file system event yielded by a
  3973. * {@linkcode Deno.FsWatcher}.
  3974. *
  3975. * @category File System */
  3976. export interface FsEvent {
  3977. /** The kind/type of the file system event. */
  3978. kind: "any" | "access" | "create" | "modify" | "remove" | "other";
  3979. /** An array of paths that are associated with the file system event. */
  3980. paths: string[];
  3981. /** Any additional flags associated with the event. */
  3982. flag?: FsEventFlag;
  3983. }
  3984. /**
  3985. * Returned by {@linkcode Deno.watchFs}. It is an async iterator yielding up
  3986. * system events. To stop watching the file system by calling `.close()`
  3987. * method.
  3988. *
  3989. * @category File System
  3990. */
  3991. export interface FsWatcher extends AsyncIterable<FsEvent>, Disposable {
  3992. /**
  3993. * The resource id.
  3994. *
  3995. * @deprecated This will be removed in Deno 2.0. See the
  3996. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  3997. * for migration instructions.
  3998. */
  3999. readonly rid: number;
  4000. /** Stops watching the file system and closes the watcher resource. */
  4001. close(): void;
  4002. /**
  4003. * Stops watching the file system and closes the watcher resource.
  4004. *
  4005. * @deprecated This will be removed in Deno 2.0. See the
  4006. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  4007. * for migration instructions.
  4008. */
  4009. return?(value?: any): Promise<IteratorResult<FsEvent>>;
  4010. [Symbol.asyncIterator](): AsyncIterableIterator<FsEvent>;
  4011. }
  4012. /** Watch for file system events against one or more `paths`, which can be
  4013. * files or directories. These paths must exist already. One user action (e.g.
  4014. * `touch test.file`) can generate multiple file system events. Likewise,
  4015. * one user action can result in multiple file paths in one event (e.g. `mv
  4016. * old_name.txt new_name.txt`).
  4017. *
  4018. * The recursive option is `true` by default and, for directories, will watch
  4019. * the specified directory and all sub directories.
  4020. *
  4021. * Note that the exact ordering of the events can vary between operating
  4022. * systems.
  4023. *
  4024. * ```ts
  4025. * const watcher = Deno.watchFs("/");
  4026. * for await (const event of watcher) {
  4027. * console.log(">>>> event", event);
  4028. * // { kind: "create", paths: [ "/foo.txt" ] }
  4029. * }
  4030. * ```
  4031. *
  4032. * Call `watcher.close()` to stop watching.
  4033. *
  4034. * ```ts
  4035. * const watcher = Deno.watchFs("/");
  4036. *
  4037. * setTimeout(() => {
  4038. * watcher.close();
  4039. * }, 5000);
  4040. *
  4041. * for await (const event of watcher) {
  4042. * console.log(">>>> event", event);
  4043. * }
  4044. * ```
  4045. *
  4046. * Requires `allow-read` permission.
  4047. *
  4048. * @tags allow-read
  4049. * @category File System
  4050. */
  4051. export function watchFs(
  4052. paths: string | string[],
  4053. options?: { recursive: boolean },
  4054. ): FsWatcher;
  4055. /**
  4056. * Options which can be used with {@linkcode Deno.run}.
  4057. *
  4058. * @deprecated This will be removed in Deno 2.0. See the
  4059. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  4060. * for migration instructions.
  4061. *
  4062. * @category Sub Process */
  4063. export interface RunOptions {
  4064. /** Arguments to pass.
  4065. *
  4066. * _Note_: the first element needs to be a path to the executable that is
  4067. * being run. */
  4068. cmd: readonly string[] | [string | URL, ...string[]];
  4069. /** The current working directory that should be used when running the
  4070. * sub-process. */
  4071. cwd?: string;
  4072. /** Any environment variables to be set when running the sub-process. */
  4073. env?: Record<string, string>;
  4074. /** By default subprocess inherits `stdout` of parent process. To change
  4075. * this this option can be set to a resource ID (_rid_) of an open file,
  4076. * `"inherit"`, `"piped"`, or `"null"`:
  4077. *
  4078. * - _number_: the resource ID of an open file/resource. This allows you to
  4079. * write to a file.
  4080. * - `"inherit"`: The default if unspecified. The subprocess inherits from the
  4081. * parent.
  4082. * - `"piped"`: A new pipe should be arranged to connect the parent and child
  4083. * sub-process.
  4084. * - `"null"`: This stream will be ignored. This is the equivalent of attaching
  4085. * the stream to `/dev/null`.
  4086. */
  4087. stdout?: "inherit" | "piped" | "null" | number;
  4088. /** By default subprocess inherits `stderr` of parent process. To change
  4089. * this this option can be set to a resource ID (_rid_) of an open file,
  4090. * `"inherit"`, `"piped"`, or `"null"`:
  4091. *
  4092. * - _number_: the resource ID of an open file/resource. This allows you to
  4093. * write to a file.
  4094. * - `"inherit"`: The default if unspecified. The subprocess inherits from the
  4095. * parent.
  4096. * - `"piped"`: A new pipe should be arranged to connect the parent and child
  4097. * sub-process.
  4098. * - `"null"`: This stream will be ignored. This is the equivalent of attaching
  4099. * the stream to `/dev/null`.
  4100. */
  4101. stderr?: "inherit" | "piped" | "null" | number;
  4102. /** By default subprocess inherits `stdin` of parent process. To change
  4103. * this this option can be set to a resource ID (_rid_) of an open file,
  4104. * `"inherit"`, `"piped"`, or `"null"`:
  4105. *
  4106. * - _number_: the resource ID of an open file/resource. This allows you to
  4107. * read from a file.
  4108. * - `"inherit"`: The default if unspecified. The subprocess inherits from the
  4109. * parent.
  4110. * - `"piped"`: A new pipe should be arranged to connect the parent and child
  4111. * sub-process.
  4112. * - `"null"`: This stream will be ignored. This is the equivalent of attaching
  4113. * the stream to `/dev/null`.
  4114. */
  4115. stdin?: "inherit" | "piped" | "null" | number;
  4116. }
  4117. /**
  4118. * The status resolved from the `.status()` method of a
  4119. * {@linkcode Deno.Process} instance.
  4120. *
  4121. * If `success` is `true`, then `code` will be `0`, but if `success` is
  4122. * `false`, the sub-process exit code will be set in `code`.
  4123. *
  4124. * @deprecated This will be removed in Deno 2.0. See the
  4125. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  4126. * for migration instructions.
  4127. *
  4128. * @category Sub Process */
  4129. export type ProcessStatus =
  4130. | {
  4131. success: true;
  4132. code: 0;
  4133. signal?: undefined;
  4134. }
  4135. | {
  4136. success: false;
  4137. code: number;
  4138. signal?: number;
  4139. };
  4140. /**
  4141. * Represents an instance of a sub process that is returned from
  4142. * {@linkcode Deno.run} which can be used to manage the sub-process.
  4143. *
  4144. * @deprecated This will be removed in Deno 2.0. See the
  4145. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  4146. * for migration instructions.
  4147. *
  4148. * @category Sub Process */
  4149. export class Process<T extends RunOptions = RunOptions> {
  4150. /** The resource ID of the sub-process. */
  4151. readonly rid: number;
  4152. /** The operating system's process ID for the sub-process. */
  4153. readonly pid: number;
  4154. /** A reference to the sub-processes `stdin`, which allows interacting with
  4155. * the sub-process at a low level. */
  4156. readonly stdin: T["stdin"] extends "piped" ? Writer & Closer & {
  4157. writable: WritableStream<Uint8Array>;
  4158. }
  4159. : (Writer & Closer & { writable: WritableStream<Uint8Array> }) | null;
  4160. /** A reference to the sub-processes `stdout`, which allows interacting with
  4161. * the sub-process at a low level. */
  4162. readonly stdout: T["stdout"] extends "piped" ? Reader & Closer & {
  4163. readable: ReadableStream<Uint8Array>;
  4164. }
  4165. : (Reader & Closer & { readable: ReadableStream<Uint8Array> }) | null;
  4166. /** A reference to the sub-processes `stderr`, which allows interacting with
  4167. * the sub-process at a low level. */
  4168. readonly stderr: T["stderr"] extends "piped" ? Reader & Closer & {
  4169. readable: ReadableStream<Uint8Array>;
  4170. }
  4171. : (Reader & Closer & { readable: ReadableStream<Uint8Array> }) | null;
  4172. /** Wait for the process to exit and return its exit status.
  4173. *
  4174. * Calling this function multiple times will return the same status.
  4175. *
  4176. * The `stdin` reference to the process will be closed before waiting to
  4177. * avoid a deadlock.
  4178. *
  4179. * If `stdout` and/or `stderr` were set to `"piped"`, they must be closed
  4180. * manually before the process can exit.
  4181. *
  4182. * To run process to completion and collect output from both `stdout` and
  4183. * `stderr` use:
  4184. *
  4185. * ```ts
  4186. * const p = Deno.run({ cmd: [ "echo", "hello world" ], stderr: 'piped', stdout: 'piped' });
  4187. * const [status, stdout, stderr] = await Promise.all([
  4188. * p.status(),
  4189. * p.output(),
  4190. * p.stderrOutput()
  4191. * ]);
  4192. * p.close();
  4193. * ```
  4194. */
  4195. status(): Promise<ProcessStatus>;
  4196. /** Buffer the stdout until EOF and return it as `Uint8Array`.
  4197. *
  4198. * You must set `stdout` to `"piped"` when creating the process.
  4199. *
  4200. * This calls `close()` on stdout after its done. */
  4201. output(): Promise<Uint8Array>;
  4202. /** Buffer the stderr until EOF and return it as `Uint8Array`.
  4203. *
  4204. * You must set `stderr` to `"piped"` when creating the process.
  4205. *
  4206. * This calls `close()` on stderr after its done. */
  4207. stderrOutput(): Promise<Uint8Array>;
  4208. /** Clean up resources associated with the sub-process instance. */
  4209. close(): void;
  4210. /** Send a signal to process.
  4211. * Default signal is `"SIGTERM"`.
  4212. *
  4213. * ```ts
  4214. * const p = Deno.run({ cmd: [ "sleep", "20" ]});
  4215. * p.kill("SIGTERM");
  4216. * p.close();
  4217. * ```
  4218. */
  4219. kill(signo?: Signal): void;
  4220. }
  4221. /** Operating signals which can be listened for or sent to sub-processes. What
  4222. * signals and what their standard behaviors are OS dependent.
  4223. *
  4224. * @category Runtime */
  4225. export type Signal =
  4226. | "SIGABRT"
  4227. | "SIGALRM"
  4228. | "SIGBREAK"
  4229. | "SIGBUS"
  4230. | "SIGCHLD"
  4231. | "SIGCONT"
  4232. | "SIGEMT"
  4233. | "SIGFPE"
  4234. | "SIGHUP"
  4235. | "SIGILL"
  4236. | "SIGINFO"
  4237. | "SIGINT"
  4238. | "SIGIO"
  4239. | "SIGPOLL"
  4240. | "SIGUNUSED"
  4241. | "SIGKILL"
  4242. | "SIGPIPE"
  4243. | "SIGPROF"
  4244. | "SIGPWR"
  4245. | "SIGQUIT"
  4246. | "SIGSEGV"
  4247. | "SIGSTKFLT"
  4248. | "SIGSTOP"
  4249. | "SIGSYS"
  4250. | "SIGTERM"
  4251. | "SIGTRAP"
  4252. | "SIGTSTP"
  4253. | "SIGTTIN"
  4254. | "SIGTTOU"
  4255. | "SIGURG"
  4256. | "SIGUSR1"
  4257. | "SIGUSR2"
  4258. | "SIGVTALRM"
  4259. | "SIGWINCH"
  4260. | "SIGXCPU"
  4261. | "SIGXFSZ";
  4262. /** Registers the given function as a listener of the given signal event.
  4263. *
  4264. * ```ts
  4265. * Deno.addSignalListener(
  4266. * "SIGTERM",
  4267. * () => {
  4268. * console.log("SIGTERM!")
  4269. * }
  4270. * );
  4271. * ```
  4272. *
  4273. * _Note_: On Windows only `"SIGINT"` (CTRL+C) and `"SIGBREAK"` (CTRL+Break)
  4274. * are supported.
  4275. *
  4276. * @category Runtime
  4277. */
  4278. export function addSignalListener(signal: Signal, handler: () => void): void;
  4279. /** Removes the given signal listener that has been registered with
  4280. * {@linkcode Deno.addSignalListener}.
  4281. *
  4282. * ```ts
  4283. * const listener = () => {
  4284. * console.log("SIGTERM!")
  4285. * };
  4286. * Deno.addSignalListener("SIGTERM", listener);
  4287. * Deno.removeSignalListener("SIGTERM", listener);
  4288. * ```
  4289. *
  4290. * _Note_: On Windows only `"SIGINT"` (CTRL+C) and `"SIGBREAK"` (CTRL+Break)
  4291. * are supported.
  4292. *
  4293. * @category Runtime
  4294. */
  4295. export function removeSignalListener(
  4296. signal: Signal,
  4297. handler: () => void,
  4298. ): void;
  4299. /**
  4300. * Spawns new subprocess. RunOptions must contain at a minimum the `opt.cmd`,
  4301. * an array of program arguments, the first of which is the binary.
  4302. *
  4303. * ```ts
  4304. * const p = Deno.run({
  4305. * cmd: ["curl", "https://example.com"],
  4306. * });
  4307. * const status = await p.status();
  4308. * ```
  4309. *
  4310. * Subprocess uses same working directory as parent process unless `opt.cwd`
  4311. * is specified.
  4312. *
  4313. * Environmental variables from parent process can be cleared using `opt.clearEnv`.
  4314. * Doesn't guarantee that only `opt.env` variables are present,
  4315. * as the OS may set environmental variables for processes.
  4316. *
  4317. * Environmental variables for subprocess can be specified using `opt.env`
  4318. * mapping.
  4319. *
  4320. * `opt.uid` sets the child process’s user ID. This translates to a setuid call
  4321. * in the child process. Failure in the setuid call will cause the spawn to fail.
  4322. *
  4323. * `opt.gid` is similar to `opt.uid`, but sets the group ID of the child process.
  4324. * This has the same semantics as the uid field.
  4325. *
  4326. * By default subprocess inherits stdio of parent process. To change
  4327. * this this, `opt.stdin`, `opt.stdout`, and `opt.stderr` can be set
  4328. * independently to a resource ID (_rid_) of an open file, `"inherit"`,
  4329. * `"piped"`, or `"null"`:
  4330. *
  4331. * - _number_: the resource ID of an open file/resource. This allows you to
  4332. * read or write to a file.
  4333. * - `"inherit"`: The default if unspecified. The subprocess inherits from the
  4334. * parent.
  4335. * - `"piped"`: A new pipe should be arranged to connect the parent and child
  4336. * sub-process.
  4337. * - `"null"`: This stream will be ignored. This is the equivalent of attaching
  4338. * the stream to `/dev/null`.
  4339. *
  4340. * Details of the spawned process are returned as an instance of
  4341. * {@linkcode Deno.Process}.
  4342. *
  4343. * Requires `allow-run` permission.
  4344. *
  4345. * @deprecated This will be soft-removed in Deno 2.0. See the
  4346. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  4347. * for migration instructions.
  4348. *
  4349. * @tags allow-run
  4350. * @category Sub Process
  4351. */
  4352. export function run<T extends RunOptions = RunOptions>(opt: T): Process<T>;
  4353. /** Create a child process.
  4354. *
  4355. * If any stdio options are not set to `"piped"`, accessing the corresponding
  4356. * field on the `Command` or its `CommandOutput` will throw a `TypeError`.
  4357. *
  4358. * If `stdin` is set to `"piped"`, the `stdin` {@linkcode WritableStream}
  4359. * needs to be closed manually.
  4360. *
  4361. * `Command` acts as a builder. Each call to {@linkcode Command.spawn} or
  4362. * {@linkcode Command.output} will spawn a new subprocess.
  4363. *
  4364. * @example Spawn a subprocess and pipe the output to a file
  4365. *
  4366. * ```ts
  4367. * const command = new Deno.Command(Deno.execPath(), {
  4368. * args: [
  4369. * "eval",
  4370. * "console.log('Hello World')",
  4371. * ],
  4372. * stdin: "piped",
  4373. * stdout: "piped",
  4374. * });
  4375. * const child = command.spawn();
  4376. *
  4377. * // open a file and pipe the subprocess output to it.
  4378. * child.stdout.pipeTo(
  4379. * Deno.openSync("output", { write: true, create: true }).writable,
  4380. * );
  4381. *
  4382. * // manually close stdin
  4383. * child.stdin.close();
  4384. * const status = await child.status;
  4385. * ```
  4386. *
  4387. * @example Spawn a subprocess and collect its output
  4388. *
  4389. * ```ts
  4390. * const command = new Deno.Command(Deno.execPath(), {
  4391. * args: [
  4392. * "eval",
  4393. * "console.log('hello'); console.error('world')",
  4394. * ],
  4395. * });
  4396. * const { code, stdout, stderr } = await command.output();
  4397. * console.assert(code === 0);
  4398. * console.assert("hello\n" === new TextDecoder().decode(stdout));
  4399. * console.assert("world\n" === new TextDecoder().decode(stderr));
  4400. * ```
  4401. *
  4402. * @example Spawn a subprocess and collect its output synchronously
  4403. *
  4404. * ```ts
  4405. * const command = new Deno.Command(Deno.execPath(), {
  4406. * args: [
  4407. * "eval",
  4408. * "console.log('hello'); console.error('world')",
  4409. * ],
  4410. * });
  4411. * const { code, stdout, stderr } = command.outputSync();
  4412. * console.assert(code === 0);
  4413. * console.assert("hello\n" === new TextDecoder().decode(stdout));
  4414. * console.assert("world\n" === new TextDecoder().decode(stderr));
  4415. * ```
  4416. *
  4417. * @tags allow-run
  4418. * @category Sub Process
  4419. */
  4420. export class Command {
  4421. constructor(command: string | URL, options?: CommandOptions);
  4422. /**
  4423. * Executes the {@linkcode Deno.Command}, waiting for it to finish and
  4424. * collecting all of its output.
  4425. *
  4426. * Will throw an error if `stdin: "piped"` is set.
  4427. *
  4428. * If options `stdout` or `stderr` are not set to `"piped"`, accessing the
  4429. * corresponding field on {@linkcode Deno.CommandOutput} will throw a `TypeError`.
  4430. */
  4431. output(): Promise<CommandOutput>;
  4432. /**
  4433. * Synchronously executes the {@linkcode Deno.Command}, waiting for it to
  4434. * finish and collecting all of its output.
  4435. *
  4436. * Will throw an error if `stdin: "piped"` is set.
  4437. *
  4438. * If options `stdout` or `stderr` are not set to `"piped"`, accessing the
  4439. * corresponding field on {@linkcode Deno.CommandOutput} will throw a `TypeError`.
  4440. */
  4441. outputSync(): CommandOutput;
  4442. /**
  4443. * Spawns a streamable subprocess, allowing to use the other methods.
  4444. */
  4445. spawn(): ChildProcess;
  4446. }
  4447. /**
  4448. * The interface for handling a child process returned from
  4449. * {@linkcode Deno.Command.spawn}.
  4450. *
  4451. * @category Sub Process
  4452. */
  4453. export class ChildProcess implements AsyncDisposable {
  4454. get stdin(): WritableStream<Uint8Array>;
  4455. get stdout(): ReadableStream<Uint8Array>;
  4456. get stderr(): ReadableStream<Uint8Array>;
  4457. readonly pid: number;
  4458. /** Get the status of the child. */
  4459. readonly status: Promise<CommandStatus>;
  4460. /** Waits for the child to exit completely, returning all its output and
  4461. * status. */
  4462. output(): Promise<CommandOutput>;
  4463. /** Kills the process with given {@linkcode Deno.Signal}.
  4464. *
  4465. * Defaults to `SIGTERM` if no signal is provided.
  4466. *
  4467. * @param [signo="SIGTERM"]
  4468. */
  4469. kill(signo?: Signal): void;
  4470. /** Ensure that the status of the child process prevents the Deno process
  4471. * from exiting. */
  4472. ref(): void;
  4473. /** Ensure that the status of the child process does not block the Deno
  4474. * process from exiting. */
  4475. unref(): void;
  4476. [Symbol.asyncDispose](): Promise<void>;
  4477. }
  4478. /**
  4479. * Options which can be set when calling {@linkcode Deno.Command}.
  4480. *
  4481. * @category Sub Process
  4482. */
  4483. export interface CommandOptions {
  4484. /** Arguments to pass to the process. */
  4485. args?: string[];
  4486. /**
  4487. * The working directory of the process.
  4488. *
  4489. * If not specified, the `cwd` of the parent process is used.
  4490. */
  4491. cwd?: string | URL;
  4492. /**
  4493. * Clear environmental variables from parent process.
  4494. *
  4495. * Doesn't guarantee that only `env` variables are present, as the OS may
  4496. * set environmental variables for processes.
  4497. *
  4498. * @default {false}
  4499. */
  4500. clearEnv?: boolean;
  4501. /** Environmental variables to pass to the subprocess. */
  4502. env?: Record<string, string>;
  4503. /**
  4504. * Sets the child process’s user ID. This translates to a setuid call in the
  4505. * child process. Failure in the set uid call will cause the spawn to fail.
  4506. */
  4507. uid?: number;
  4508. /** Similar to `uid`, but sets the group ID of the child process. */
  4509. gid?: number;
  4510. /**
  4511. * An {@linkcode AbortSignal} that allows closing the process using the
  4512. * corresponding {@linkcode AbortController} by sending the process a
  4513. * SIGTERM signal.
  4514. *
  4515. * Not supported in {@linkcode Deno.Command.outputSync}.
  4516. */
  4517. signal?: AbortSignal;
  4518. /** How `stdin` of the spawned process should be handled.
  4519. *
  4520. * Defaults to `"inherit"` for `output` & `outputSync`,
  4521. * and `"inherit"` for `spawn`. */
  4522. stdin?: "piped" | "inherit" | "null";
  4523. /** How `stdout` of the spawned process should be handled.
  4524. *
  4525. * Defaults to `"piped"` for `output` & `outputSync`,
  4526. * and `"inherit"` for `spawn`. */
  4527. stdout?: "piped" | "inherit" | "null";
  4528. /** How `stderr` of the spawned process should be handled.
  4529. *
  4530. * Defaults to `"piped"` for `output` & `outputSync`,
  4531. * and `"inherit"` for `spawn`. */
  4532. stderr?: "piped" | "inherit" | "null";
  4533. /** Skips quoting and escaping of the arguments on windows. This option
  4534. * is ignored on non-windows platforms.
  4535. *
  4536. * @default {false} */
  4537. windowsRawArguments?: boolean;
  4538. }
  4539. /**
  4540. * @category Sub Process
  4541. */
  4542. export interface CommandStatus {
  4543. /** If the child process exits with a 0 status code, `success` will be set
  4544. * to `true`, otherwise `false`. */
  4545. success: boolean;
  4546. /** The exit code of the child process. */
  4547. code: number;
  4548. /** The signal associated with the child process. */
  4549. signal: Signal | null;
  4550. }
  4551. /**
  4552. * The interface returned from calling {@linkcode Deno.Command.output} or
  4553. * {@linkcode Deno.Command.outputSync} which represents the result of spawning the
  4554. * child process.
  4555. *
  4556. * @category Sub Process
  4557. */
  4558. export interface CommandOutput extends CommandStatus {
  4559. /** The buffered output from the child process' `stdout`. */
  4560. readonly stdout: Uint8Array;
  4561. /** The buffered output from the child process' `stderr`. */
  4562. readonly stderr: Uint8Array;
  4563. }
  4564. /** Option which can be specified when performing {@linkcode Deno.inspect}.
  4565. *
  4566. * @category I/O */
  4567. export interface InspectOptions {
  4568. /** Stylize output with ANSI colors.
  4569. *
  4570. * @default {false} */
  4571. colors?: boolean;
  4572. /** Try to fit more than one entry of a collection on the same line.
  4573. *
  4574. * @default {true} */
  4575. compact?: boolean;
  4576. /** Traversal depth for nested objects.
  4577. *
  4578. * @default {4} */
  4579. depth?: number;
  4580. /** The maximum length for an inspection to take up a single line.
  4581. *
  4582. * @default {80} */
  4583. breakLength?: number;
  4584. /** Whether or not to escape sequences.
  4585. *
  4586. * @default {true} */
  4587. escapeSequences?: boolean;
  4588. /** The maximum number of iterable entries to print.
  4589. *
  4590. * @default {100} */
  4591. iterableLimit?: number;
  4592. /** Show a Proxy's target and handler.
  4593. *
  4594. * @default {false} */
  4595. showProxy?: boolean;
  4596. /** Sort Object, Set and Map entries by key.
  4597. *
  4598. * @default {false} */
  4599. sorted?: boolean;
  4600. /** Add a trailing comma for multiline collections.
  4601. *
  4602. * @default {false} */
  4603. trailingComma?: boolean;
  4604. /** Evaluate the result of calling getters.
  4605. *
  4606. * @default {false} */
  4607. getters?: boolean;
  4608. /** Show an object's non-enumerable properties.
  4609. *
  4610. * @default {false} */
  4611. showHidden?: boolean;
  4612. /** The maximum length of a string before it is truncated with an
  4613. * ellipsis. */
  4614. strAbbreviateSize?: number;
  4615. }
  4616. /** Converts the input into a string that has the same format as printed by
  4617. * `console.log()`.
  4618. *
  4619. * ```ts
  4620. * const obj = {
  4621. * a: 10,
  4622. * b: "hello",
  4623. * };
  4624. * const objAsString = Deno.inspect(obj); // { a: 10, b: "hello" }
  4625. * console.log(obj); // prints same value as objAsString, e.g. { a: 10, b: "hello" }
  4626. * ```
  4627. *
  4628. * A custom inspect functions can be registered on objects, via the symbol
  4629. * `Symbol.for("Deno.customInspect")`, to control and customize the output
  4630. * of `inspect()` or when using `console` logging:
  4631. *
  4632. * ```ts
  4633. * class A {
  4634. * x = 10;
  4635. * y = "hello";
  4636. * [Symbol.for("Deno.customInspect")]() {
  4637. * return `x=${this.x}, y=${this.y}`;
  4638. * }
  4639. * }
  4640. *
  4641. * const inStringFormat = Deno.inspect(new A()); // "x=10, y=hello"
  4642. * console.log(inStringFormat); // prints "x=10, y=hello"
  4643. * ```
  4644. *
  4645. * A depth can be specified by using the `depth` option:
  4646. *
  4647. * ```ts
  4648. * Deno.inspect({a: {b: {c: {d: 'hello'}}}}, {depth: 2}); // { a: { b: [Object] } }
  4649. * ```
  4650. *
  4651. * @category I/O
  4652. */
  4653. export function inspect(value: unknown, options?: InspectOptions): string;
  4654. /** The name of a privileged feature which needs permission.
  4655. *
  4656. * @category Permissions
  4657. */
  4658. export type PermissionName =
  4659. | "run"
  4660. | "read"
  4661. | "write"
  4662. | "net"
  4663. | "env"
  4664. | "sys"
  4665. | "ffi"
  4666. | "hrtime";
  4667. /** The current status of the permission:
  4668. *
  4669. * - `"granted"` - the permission has been granted.
  4670. * - `"denied"` - the permission has been explicitly denied.
  4671. * - `"prompt"` - the permission has not explicitly granted nor denied.
  4672. *
  4673. * @category Permissions
  4674. */
  4675. export type PermissionState =
  4676. | "granted"
  4677. | "denied"
  4678. | "prompt";
  4679. /** The permission descriptor for the `allow-run` and `deny-run` permissions, which controls
  4680. * access to what sub-processes can be executed by Deno. The option `command`
  4681. * allows scoping the permission to a specific executable.
  4682. *
  4683. * **Warning, in practice, `allow-run` is effectively the same as `allow-all`
  4684. * in the sense that malicious code could execute any arbitrary code on the
  4685. * host.**
  4686. *
  4687. * @category Permissions */
  4688. export interface RunPermissionDescriptor {
  4689. name: "run";
  4690. /** An `allow-run` or `deny-run` permission can be scoped to a specific executable,
  4691. * which would be relative to the start-up CWD of the Deno CLI. */
  4692. command?: string | URL;
  4693. }
  4694. /** The permission descriptor for the `allow-read` and `deny-read` permissions, which controls
  4695. * access to reading resources from the local host. The option `path` allows
  4696. * scoping the permission to a specific path (and if the path is a directory
  4697. * any sub paths).
  4698. *
  4699. * Permission granted under `allow-read` only allows runtime code to attempt
  4700. * to read, the underlying operating system may apply additional permissions.
  4701. *
  4702. * @category Permissions */
  4703. export interface ReadPermissionDescriptor {
  4704. name: "read";
  4705. /** An `allow-read` or `deny-read` permission can be scoped to a specific path (and if
  4706. * the path is a directory, any sub paths). */
  4707. path?: string | URL;
  4708. }
  4709. /** The permission descriptor for the `allow-write` and `deny-write` permissions, which
  4710. * controls access to writing to resources from the local host. The option
  4711. * `path` allow scoping the permission to a specific path (and if the path is
  4712. * a directory any sub paths).
  4713. *
  4714. * Permission granted under `allow-write` only allows runtime code to attempt
  4715. * to write, the underlying operating system may apply additional permissions.
  4716. *
  4717. * @category Permissions */
  4718. export interface WritePermissionDescriptor {
  4719. name: "write";
  4720. /** An `allow-write` or `deny-write` permission can be scoped to a specific path (and if
  4721. * the path is a directory, any sub paths). */
  4722. path?: string | URL;
  4723. }
  4724. /** The permission descriptor for the `allow-net` and `deny-net` permissions, which controls
  4725. * access to opening network ports and connecting to remote hosts via the
  4726. * network. The option `host` allows scoping the permission for outbound
  4727. * connection to a specific host and port.
  4728. *
  4729. * @category Permissions */
  4730. export interface NetPermissionDescriptor {
  4731. name: "net";
  4732. /** Optional host string of the form `"<hostname>[:<port>]"`. Examples:
  4733. *
  4734. * "github.com"
  4735. * "deno.land:8080"
  4736. */
  4737. host?: string;
  4738. }
  4739. /** The permission descriptor for the `allow-env` and `deny-env` permissions, which controls
  4740. * access to being able to read and write to the process environment variables
  4741. * as well as access other information about the environment. The option
  4742. * `variable` allows scoping the permission to a specific environment
  4743. * variable.
  4744. *
  4745. * @category Permissions */
  4746. export interface EnvPermissionDescriptor {
  4747. name: "env";
  4748. /** Optional environment variable name (e.g. `PATH`). */
  4749. variable?: string;
  4750. }
  4751. /** The permission descriptor for the `allow-sys` and `deny-sys` permissions, which controls
  4752. * access to sensitive host system information, which malicious code might
  4753. * attempt to exploit. The option `kind` allows scoping the permission to a
  4754. * specific piece of information.
  4755. *
  4756. * @category Permissions */
  4757. export interface SysPermissionDescriptor {
  4758. name: "sys";
  4759. /** The specific information to scope the permission to. */
  4760. kind?:
  4761. | "loadavg"
  4762. | "hostname"
  4763. | "systemMemoryInfo"
  4764. | "networkInterfaces"
  4765. | "osRelease"
  4766. | "osUptime"
  4767. | "uid"
  4768. | "gid"
  4769. | "username"
  4770. | "cpus"
  4771. | "homedir"
  4772. | "statfs"
  4773. | "getPriority"
  4774. | "setPriority";
  4775. }
  4776. /** The permission descriptor for the `allow-ffi` and `deny-ffi` permissions, which controls
  4777. * access to loading _foreign_ code and interfacing with it via the
  4778. * [Foreign Function Interface API](https://deno.land/manual/runtime/ffi_api)
  4779. * available in Deno. The option `path` allows scoping the permission to a
  4780. * specific path on the host.
  4781. *
  4782. * @category Permissions */
  4783. export interface FfiPermissionDescriptor {
  4784. name: "ffi";
  4785. /** Optional path on the local host to scope the permission to. */
  4786. path?: string | URL;
  4787. }
  4788. /** The permission descriptor for the `allow-hrtime` and `deny-hrtime` permissions, which
  4789. * controls if the runtime code has access to high resolution time. High
  4790. * resolution time is considered sensitive information, because it can be used
  4791. * by malicious code to gain information about the host that it might not
  4792. * otherwise have access to.
  4793. *
  4794. * @category Permissions */
  4795. export interface HrtimePermissionDescriptor {
  4796. name: "hrtime";
  4797. }
  4798. /** Permission descriptors which define a permission and can be queried,
  4799. * requested, or revoked.
  4800. *
  4801. * View the specifics of the individual descriptors for more information about
  4802. * each permission kind.
  4803. *
  4804. * @category Permissions
  4805. */
  4806. export type PermissionDescriptor =
  4807. | RunPermissionDescriptor
  4808. | ReadPermissionDescriptor
  4809. | WritePermissionDescriptor
  4810. | NetPermissionDescriptor
  4811. | EnvPermissionDescriptor
  4812. | SysPermissionDescriptor
  4813. | FfiPermissionDescriptor
  4814. | HrtimePermissionDescriptor;
  4815. /** The interface which defines what event types are supported by
  4816. * {@linkcode PermissionStatus} instances.
  4817. *
  4818. * @category Permissions */
  4819. export interface PermissionStatusEventMap {
  4820. "change": Event;
  4821. }
  4822. /** An {@linkcode EventTarget} returned from the {@linkcode Deno.permissions}
  4823. * API which can provide updates to any state changes of the permission.
  4824. *
  4825. * @category Permissions */
  4826. export class PermissionStatus extends EventTarget {
  4827. // deno-lint-ignore no-explicit-any
  4828. onchange: ((this: PermissionStatus, ev: Event) => any) | null;
  4829. readonly state: PermissionState;
  4830. /**
  4831. * Describes if permission is only granted partially, eg. an access
  4832. * might be granted to "/foo" directory, but denied for "/foo/bar".
  4833. * In such case this field will be set to `true` when querying for
  4834. * read permissions of "/foo" directory.
  4835. */
  4836. readonly partial: boolean;
  4837. addEventListener<K extends keyof PermissionStatusEventMap>(
  4838. type: K,
  4839. listener: (
  4840. this: PermissionStatus,
  4841. ev: PermissionStatusEventMap[K],
  4842. ) => any,
  4843. options?: boolean | AddEventListenerOptions,
  4844. ): void;
  4845. addEventListener(
  4846. type: string,
  4847. listener: EventListenerOrEventListenerObject,
  4848. options?: boolean | AddEventListenerOptions,
  4849. ): void;
  4850. removeEventListener<K extends keyof PermissionStatusEventMap>(
  4851. type: K,
  4852. listener: (
  4853. this: PermissionStatus,
  4854. ev: PermissionStatusEventMap[K],
  4855. ) => any,
  4856. options?: boolean | EventListenerOptions,
  4857. ): void;
  4858. removeEventListener(
  4859. type: string,
  4860. listener: EventListenerOrEventListenerObject,
  4861. options?: boolean | EventListenerOptions,
  4862. ): void;
  4863. }
  4864. /**
  4865. * Deno's permission management API.
  4866. *
  4867. * The class which provides the interface for the {@linkcode Deno.permissions}
  4868. * global instance and is based on the web platform
  4869. * [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API),
  4870. * though some proposed parts of the API which are useful in a server side
  4871. * runtime context were removed or abandoned in the web platform specification
  4872. * which is why it was chosen to locate it in the {@linkcode Deno} namespace
  4873. * instead.
  4874. *
  4875. * By default, if the `stdin`/`stdout` is TTY for the Deno CLI (meaning it can
  4876. * send and receive text), then the CLI will prompt the user to grant
  4877. * permission when an un-granted permission is requested. This behavior can
  4878. * be changed by using the `--no-prompt` command at startup. When prompting
  4879. * the CLI will request the narrowest permission possible, potentially making
  4880. * it annoying to the user. The permissions APIs allow the code author to
  4881. * request a wider set of permissions at one time in order to provide a better
  4882. * user experience.
  4883. *
  4884. * @category Permissions */
  4885. export class Permissions {
  4886. /** Resolves to the current status of a permission.
  4887. *
  4888. * Note, if the permission is already granted, `request()` will not prompt
  4889. * the user again, therefore `query()` is only necessary if you are going
  4890. * to react differently existing permissions without wanting to modify them
  4891. * or prompt the user to modify them.
  4892. *
  4893. * ```ts
  4894. * const status = await Deno.permissions.query({ name: "read", path: "/etc" });
  4895. * console.log(status.state);
  4896. * ```
  4897. */
  4898. query(desc: PermissionDescriptor): Promise<PermissionStatus>;
  4899. /** Returns the current status of a permission.
  4900. *
  4901. * Note, if the permission is already granted, `request()` will not prompt
  4902. * the user again, therefore `querySync()` is only necessary if you are going
  4903. * to react differently existing permissions without wanting to modify them
  4904. * or prompt the user to modify them.
  4905. *
  4906. * ```ts
  4907. * const status = Deno.permissions.querySync({ name: "read", path: "/etc" });
  4908. * console.log(status.state);
  4909. * ```
  4910. */
  4911. querySync(desc: PermissionDescriptor): PermissionStatus;
  4912. /** Revokes a permission, and resolves to the state of the permission.
  4913. *
  4914. * ```ts
  4915. * import { assert } from "jsr:@std/assert";
  4916. *
  4917. * const status = await Deno.permissions.revoke({ name: "run" });
  4918. * assert(status.state !== "granted")
  4919. * ```
  4920. */
  4921. revoke(desc: PermissionDescriptor): Promise<PermissionStatus>;
  4922. /** Revokes a permission, and returns the state of the permission.
  4923. *
  4924. * ```ts
  4925. * import { assert } from "jsr:@std/assert";
  4926. *
  4927. * const status = Deno.permissions.revokeSync({ name: "run" });
  4928. * assert(status.state !== "granted")
  4929. * ```
  4930. */
  4931. revokeSync(desc: PermissionDescriptor): PermissionStatus;
  4932. /** Requests the permission, and resolves to the state of the permission.
  4933. *
  4934. * If the permission is already granted, the user will not be prompted to
  4935. * grant the permission again.
  4936. *
  4937. * ```ts
  4938. * const status = await Deno.permissions.request({ name: "env" });
  4939. * if (status.state === "granted") {
  4940. * console.log("'env' permission is granted.");
  4941. * } else {
  4942. * console.log("'env' permission is denied.");
  4943. * }
  4944. * ```
  4945. */
  4946. request(desc: PermissionDescriptor): Promise<PermissionStatus>;
  4947. /** Requests the permission, and returns the state of the permission.
  4948. *
  4949. * If the permission is already granted, the user will not be prompted to
  4950. * grant the permission again.
  4951. *
  4952. * ```ts
  4953. * const status = Deno.permissions.requestSync({ name: "env" });
  4954. * if (status.state === "granted") {
  4955. * console.log("'env' permission is granted.");
  4956. * } else {
  4957. * console.log("'env' permission is denied.");
  4958. * }
  4959. * ```
  4960. */
  4961. requestSync(desc: PermissionDescriptor): PermissionStatus;
  4962. }
  4963. /** Deno's permission management API.
  4964. *
  4965. * It is a singleton instance of the {@linkcode Permissions} object and is
  4966. * based on the web platform
  4967. * [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API),
  4968. * though some proposed parts of the API which are useful in a server side
  4969. * runtime context were removed or abandoned in the web platform specification
  4970. * which is why it was chosen to locate it in the {@linkcode Deno} namespace
  4971. * instead.
  4972. *
  4973. * By default, if the `stdin`/`stdout` is TTY for the Deno CLI (meaning it can
  4974. * send and receive text), then the CLI will prompt the user to grant
  4975. * permission when an un-granted permission is requested. This behavior can
  4976. * be changed by using the `--no-prompt` command at startup. When prompting
  4977. * the CLI will request the narrowest permission possible, potentially making
  4978. * it annoying to the user. The permissions APIs allow the code author to
  4979. * request a wider set of permissions at one time in order to provide a better
  4980. * user experience.
  4981. *
  4982. * Requesting already granted permissions will not prompt the user and will
  4983. * return that the permission was granted.
  4984. *
  4985. * ### Querying
  4986. *
  4987. * ```ts
  4988. * const status = await Deno.permissions.query({ name: "read", path: "/etc" });
  4989. * console.log(status.state);
  4990. * ```
  4991. *
  4992. * ```ts
  4993. * const status = Deno.permissions.querySync({ name: "read", path: "/etc" });
  4994. * console.log(status.state);
  4995. * ```
  4996. *
  4997. * ### Revoking
  4998. *
  4999. * ```ts
  5000. * import { assert } from "jsr:@std/assert";
  5001. *
  5002. * const status = await Deno.permissions.revoke({ name: "run" });
  5003. * assert(status.state !== "granted")
  5004. * ```
  5005. *
  5006. * ```ts
  5007. * import { assert } from "jsr:@std/assert";
  5008. *
  5009. * const status = Deno.permissions.revokeSync({ name: "run" });
  5010. * assert(status.state !== "granted")
  5011. * ```
  5012. *
  5013. * ### Requesting
  5014. *
  5015. * ```ts
  5016. * const status = await Deno.permissions.request({ name: "env" });
  5017. * if (status.state === "granted") {
  5018. * console.log("'env' permission is granted.");
  5019. * } else {
  5020. * console.log("'env' permission is denied.");
  5021. * }
  5022. * ```
  5023. *
  5024. * ```ts
  5025. * const status = Deno.permissions.requestSync({ name: "env" });
  5026. * if (status.state === "granted") {
  5027. * console.log("'env' permission is granted.");
  5028. * } else {
  5029. * console.log("'env' permission is denied.");
  5030. * }
  5031. * ```
  5032. *
  5033. * @category Permissions
  5034. */
  5035. export const permissions: Permissions;
  5036. /** Information related to the build of the current Deno runtime.
  5037. *
  5038. * Users are discouraged from code branching based on this information, as
  5039. * assumptions about what is available in what build environment might change
  5040. * over time. Developers should specifically sniff out the features they
  5041. * intend to use.
  5042. *
  5043. * The intended use for the information is for logging and debugging purposes.
  5044. *
  5045. * @category Runtime
  5046. */
  5047. export const build: {
  5048. /** The [LLVM](https://llvm.org/) target triple, which is the combination
  5049. * of `${arch}-${vendor}-${os}` and represent the specific build target that
  5050. * the current runtime was built for. */
  5051. target: string;
  5052. /** Instruction set architecture that the Deno CLI was built for. */
  5053. arch: "x86_64" | "aarch64";
  5054. /** The operating system that the Deno CLI was built for. `"darwin"` is
  5055. * also known as OSX or MacOS. */
  5056. os:
  5057. | "darwin"
  5058. | "linux"
  5059. | "android"
  5060. | "windows"
  5061. | "freebsd"
  5062. | "netbsd"
  5063. | "aix"
  5064. | "solaris"
  5065. | "illumos";
  5066. /** The computer vendor that the Deno CLI was built for. */
  5067. vendor: string;
  5068. /** Optional environment flags that were set for this build of Deno CLI. */
  5069. env?: string;
  5070. };
  5071. /** Version information related to the current Deno CLI runtime environment.
  5072. *
  5073. * Users are discouraged from code branching based on this information, as
  5074. * assumptions about what is available in what build environment might change
  5075. * over time. Developers should specifically sniff out the features they
  5076. * intend to use.
  5077. *
  5078. * The intended use for the information is for logging and debugging purposes.
  5079. *
  5080. * @category Runtime
  5081. */
  5082. export const version: {
  5083. /** Deno CLI's version. For example: `"1.26.0"`. */
  5084. deno: string;
  5085. /** The V8 version used by Deno. For example: `"10.7.100.0"`.
  5086. *
  5087. * V8 is the underlying JavaScript runtime platform that Deno is built on
  5088. * top of. */
  5089. v8: string;
  5090. /** The TypeScript version used by Deno. For example: `"4.8.3"`.
  5091. *
  5092. * A version of the TypeScript type checker and language server is built-in
  5093. * to the Deno CLI. */
  5094. typescript: string;
  5095. };
  5096. /** Returns the script arguments to the program.
  5097. *
  5098. * Give the following command line invocation of Deno:
  5099. *
  5100. * ```sh
  5101. * deno run --allow-read https://examples.deno.land/command-line-arguments.ts Sushi
  5102. * ```
  5103. *
  5104. * Then `Deno.args` will contain:
  5105. *
  5106. * ```ts
  5107. * [ "Sushi" ]
  5108. * ```
  5109. *
  5110. * If you are looking for a structured way to parse arguments, there is
  5111. * [`parseArgs()`](https://jsr.io/@std/cli/doc/parse-args/~/parseArgs) from
  5112. * the Deno Standard Library.
  5113. *
  5114. * @category Runtime
  5115. */
  5116. export const args: string[];
  5117. /**
  5118. * A symbol which can be used as a key for a custom method which will be
  5119. * called when `Deno.inspect()` is called, or when the object is logged to
  5120. * the console.
  5121. *
  5122. * @deprecated This will be removed in Deno 2.0. See the
  5123. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  5124. * for migration instructions.
  5125. *
  5126. * @category I/O
  5127. */
  5128. export const customInspect: unique symbol;
  5129. /** The URL of the entrypoint module entered from the command-line. It
  5130. * requires read permission to the CWD.
  5131. *
  5132. * Also see {@linkcode ImportMeta} for other related information.
  5133. *
  5134. * @tags allow-read
  5135. * @category Runtime
  5136. */
  5137. export const mainModule: string;
  5138. /** Options that can be used with {@linkcode symlink} and
  5139. * {@linkcode symlinkSync}.
  5140. *
  5141. * @category File System */
  5142. export interface SymlinkOptions {
  5143. /** Specify the symbolic link type as file, directory or NTFS junction. This
  5144. * option only applies to Windows and is ignored on other operating systems. */
  5145. type: "file" | "dir" | "junction";
  5146. }
  5147. /**
  5148. * Creates `newpath` as a symbolic link to `oldpath`.
  5149. *
  5150. * The `options.type` parameter can be set to `"file"`, `"dir"` or `"junction"`.
  5151. * This argument is only available on Windows and ignored on other platforms.
  5152. *
  5153. * ```ts
  5154. * await Deno.symlink("old/name", "new/name");
  5155. * ```
  5156. *
  5157. * Requires full `allow-read` and `allow-write` permissions.
  5158. *
  5159. * @tags allow-read, allow-write
  5160. * @category File System
  5161. */
  5162. export function symlink(
  5163. oldpath: string | URL,
  5164. newpath: string | URL,
  5165. options?: SymlinkOptions,
  5166. ): Promise<void>;
  5167. /**
  5168. * Creates `newpath` as a symbolic link to `oldpath`.
  5169. *
  5170. * The `options.type` parameter can be set to `"file"`, `"dir"` or `"junction"`.
  5171. * This argument is only available on Windows and ignored on other platforms.
  5172. *
  5173. * ```ts
  5174. * Deno.symlinkSync("old/name", "new/name");
  5175. * ```
  5176. *
  5177. * Requires full `allow-read` and `allow-write` permissions.
  5178. *
  5179. * @tags allow-read, allow-write
  5180. * @category File System
  5181. */
  5182. export function symlinkSync(
  5183. oldpath: string | URL,
  5184. newpath: string | URL,
  5185. options?: SymlinkOptions,
  5186. ): void;
  5187. /**
  5188. * Truncates or extends the specified file stream, to reach the specified
  5189. * `len`.
  5190. *
  5191. * If `len` is not specified then the entire file contents are truncated as if
  5192. * `len` was set to `0`.
  5193. *
  5194. * If the file previously was larger than this new length, the extra data is
  5195. * lost.
  5196. *
  5197. * If the file previously was shorter, it is extended, and the extended part
  5198. * reads as null bytes ('\0').
  5199. *
  5200. * ### Truncate the entire file
  5201. *
  5202. * ```ts
  5203. * const file = await Deno.open(
  5204. * "my_file.txt",
  5205. * { read: true, write: true, create: true }
  5206. * );
  5207. * await Deno.ftruncate(file.rid);
  5208. * ```
  5209. *
  5210. * ### Truncate part of the file
  5211. *
  5212. * ```ts
  5213. * const file = await Deno.open(
  5214. * "my_file.txt",
  5215. * { read: true, write: true, create: true }
  5216. * );
  5217. * await file.write(new TextEncoder().encode("Hello World"));
  5218. * await Deno.ftruncate(file.rid, 7);
  5219. * const data = new Uint8Array(32);
  5220. * await Deno.read(file.rid, data);
  5221. * console.log(new TextDecoder().decode(data)); // Hello W
  5222. * ```
  5223. *
  5224. * @deprecated This will be removed in Deno 2.0. See the
  5225. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  5226. * for migration instructions.
  5227. *
  5228. * @category File System
  5229. */
  5230. export function ftruncate(rid: number, len?: number): Promise<void>;
  5231. /**
  5232. * Synchronously truncates or extends the specified file stream, to reach the
  5233. * specified `len`.
  5234. *
  5235. * If `len` is not specified then the entire file contents are truncated as if
  5236. * `len` was set to `0`.
  5237. *
  5238. * If the file previously was larger than this new length, the extra data is
  5239. * lost.
  5240. *
  5241. * If the file previously was shorter, it is extended, and the extended part
  5242. * reads as null bytes ('\0').
  5243. *
  5244. * ### Truncate the entire file
  5245. *
  5246. * ```ts
  5247. * const file = Deno.openSync(
  5248. * "my_file.txt",
  5249. * { read: true, write: true, truncate: true, create: true }
  5250. * );
  5251. * Deno.ftruncateSync(file.rid);
  5252. * ```
  5253. *
  5254. * ### Truncate part of the file
  5255. *
  5256. * ```ts
  5257. * const file = Deno.openSync(
  5258. * "my_file.txt",
  5259. * { read: true, write: true, create: true }
  5260. * );
  5261. * file.writeSync(new TextEncoder().encode("Hello World"));
  5262. * Deno.ftruncateSync(file.rid, 7);
  5263. * Deno.seekSync(file.rid, 0, Deno.SeekMode.Start);
  5264. * const data = new Uint8Array(32);
  5265. * Deno.readSync(file.rid, data);
  5266. * console.log(new TextDecoder().decode(data)); // Hello W
  5267. * ```
  5268. *
  5269. * @deprecated This will be removed in Deno 2.0. See the
  5270. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  5271. * for migration instructions.
  5272. *
  5273. * @category File System
  5274. */
  5275. export function ftruncateSync(rid: number, len?: number): void;
  5276. /**
  5277. * Synchronously changes the access (`atime`) and modification (`mtime`) times
  5278. * of a file stream resource referenced by `rid`. Given times are either in
  5279. * seconds (UNIX epoch time) or as `Date` objects.
  5280. *
  5281. * ```ts
  5282. * const file = Deno.openSync("file.txt", { create: true, write: true });
  5283. * Deno.futimeSync(file.rid, 1556495550, new Date());
  5284. * ```
  5285. *
  5286. * @deprecated This will be removed in Deno 2.0. See the
  5287. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  5288. * for migration instructions.
  5289. *
  5290. * @category File System
  5291. */
  5292. export function futimeSync(
  5293. rid: number,
  5294. atime: number | Date,
  5295. mtime: number | Date,
  5296. ): void;
  5297. /**
  5298. * Changes the access (`atime`) and modification (`mtime`) times of a file
  5299. * stream resource referenced by `rid`. Given times are either in seconds
  5300. * (UNIX epoch time) or as `Date` objects.
  5301. *
  5302. * ```ts
  5303. * const file = await Deno.open("file.txt", { create: true, write: true });
  5304. * await Deno.futime(file.rid, 1556495550, new Date());
  5305. * ```
  5306. *
  5307. * @deprecated This will be removed in Deno 2.0. See the
  5308. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  5309. * for migration instructions.
  5310. *
  5311. * @category File System
  5312. */
  5313. export function futime(
  5314. rid: number,
  5315. atime: number | Date,
  5316. mtime: number | Date,
  5317. ): Promise<void>;
  5318. /**
  5319. * Returns a `Deno.FileInfo` for the given file stream.
  5320. *
  5321. * ```ts
  5322. * import { assert } from "jsr:@std/assert";
  5323. *
  5324. * const file = await Deno.open("file.txt", { read: true });
  5325. * const fileInfo = await Deno.fstat(file.rid);
  5326. * assert(fileInfo.isFile);
  5327. * ```
  5328. *
  5329. * @deprecated This will be removed in Deno 2.0. See the
  5330. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  5331. * for migration instructions.
  5332. *
  5333. * @category File System
  5334. */
  5335. export function fstat(rid: number): Promise<FileInfo>;
  5336. /**
  5337. * Synchronously returns a {@linkcode Deno.FileInfo} for the given file
  5338. * stream.
  5339. *
  5340. * ```ts
  5341. * import { assert } from "jsr:@std/assert";
  5342. *
  5343. * const file = Deno.openSync("file.txt", { read: true });
  5344. * const fileInfo = Deno.fstatSync(file.rid);
  5345. * assert(fileInfo.isFile);
  5346. * ```
  5347. *
  5348. * @deprecated This will be removed in Deno 2.0. See the
  5349. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  5350. * for migration instructions.
  5351. *
  5352. * @category File System
  5353. */
  5354. export function fstatSync(rid: number): FileInfo;
  5355. /**
  5356. * Synchronously changes the access (`atime`) and modification (`mtime`) times
  5357. * of a file system object referenced by `path`. Given times are either in
  5358. * seconds (UNIX epoch time) or as `Date` objects.
  5359. *
  5360. * ```ts
  5361. * Deno.utimeSync("myfile.txt", 1556495550, new Date());
  5362. * ```
  5363. *
  5364. * Requires `allow-write` permission.
  5365. *
  5366. * @tags allow-write
  5367. * @category File System
  5368. */
  5369. export function utimeSync(
  5370. path: string | URL,
  5371. atime: number | Date,
  5372. mtime: number | Date,
  5373. ): void;
  5374. /**
  5375. * Changes the access (`atime`) and modification (`mtime`) times of a file
  5376. * system object referenced by `path`. Given times are either in seconds
  5377. * (UNIX epoch time) or as `Date` objects.
  5378. *
  5379. * ```ts
  5380. * await Deno.utime("myfile.txt", 1556495550, new Date());
  5381. * ```
  5382. *
  5383. * Requires `allow-write` permission.
  5384. *
  5385. * @tags allow-write
  5386. * @category File System
  5387. */
  5388. export function utime(
  5389. path: string | URL,
  5390. atime: number | Date,
  5391. mtime: number | Date,
  5392. ): Promise<void>;
  5393. /** The event yielded from an {@linkcode HttpConn} which represents an HTTP
  5394. * request from a remote client.
  5395. *
  5396. * @category HTTP Server
  5397. *
  5398. * @deprecated This will be removed in Deno 2.0. See the
  5399. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  5400. * for migration instructions.
  5401. */
  5402. export interface RequestEvent {
  5403. /** The request from the client in the form of the web platform
  5404. * {@linkcode Request}. */
  5405. readonly request: Request;
  5406. /** The method to be used to respond to the event. The response needs to
  5407. * either be an instance of {@linkcode Response} or a promise that resolves
  5408. * with an instance of `Response`.
  5409. *
  5410. * When the response is successfully processed then the promise returned
  5411. * will be resolved. If there are any issues with sending the response,
  5412. * the promise will be rejected. */
  5413. respondWith(r: Response | PromiseLike<Response>): Promise<void>;
  5414. }
  5415. /**
  5416. * The async iterable that is returned from {@linkcode serveHttp} which
  5417. * yields up {@linkcode RequestEvent} events, representing individual
  5418. * requests on the HTTP server connection.
  5419. *
  5420. * @category HTTP Server
  5421. *
  5422. * @deprecated This will be removed in Deno 2.0. See the
  5423. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  5424. * for migration instructions.
  5425. */
  5426. export interface HttpConn extends AsyncIterable<RequestEvent>, Disposable {
  5427. /** The resource ID associated with this connection. Generally users do not
  5428. * need to be aware of this identifier. */
  5429. readonly rid: number;
  5430. /** An alternative to the async iterable interface which provides promises
  5431. * which resolve with either a {@linkcode RequestEvent} when there is
  5432. * another request or `null` when the client has closed the connection. */
  5433. nextRequest(): Promise<RequestEvent | null>;
  5434. /** Initiate a server side closure of the connection, indicating to the
  5435. * client that you refuse to accept any more requests on this connection.
  5436. *
  5437. * Typically the client closes the connection, which will result in the
  5438. * async iterable terminating or the `nextRequest()` method returning
  5439. * `null`. */
  5440. close(): void;
  5441. }
  5442. /**
  5443. * Provides an interface to handle HTTP request and responses over TCP or TLS
  5444. * connections. The method returns an {@linkcode HttpConn} which yields up
  5445. * {@linkcode RequestEvent} events, which utilize the web platform standard
  5446. * {@linkcode Request} and {@linkcode Response} objects to handle the request.
  5447. *
  5448. * ```ts
  5449. * const conn = Deno.listen({ port: 80 });
  5450. * const httpConn = Deno.serveHttp(await conn.accept());
  5451. * const e = await httpConn.nextRequest();
  5452. * if (e) {
  5453. * e.respondWith(new Response("Hello World"));
  5454. * }
  5455. * ```
  5456. *
  5457. * Alternatively, you can also use the async iterator approach:
  5458. *
  5459. * ```ts
  5460. * async function handleHttp(conn: Deno.Conn) {
  5461. * for await (const e of Deno.serveHttp(conn)) {
  5462. * e.respondWith(new Response("Hello World"));
  5463. * }
  5464. * }
  5465. *
  5466. * for await (const conn of Deno.listen({ port: 80 })) {
  5467. * handleHttp(conn);
  5468. * }
  5469. * ```
  5470. *
  5471. * If `httpConn.nextRequest()` encounters an error or returns `null` then the
  5472. * underlying {@linkcode HttpConn} resource is closed automatically.
  5473. *
  5474. * Also see the experimental Flash HTTP server {@linkcode Deno.serve} which
  5475. * provides a ground up rewrite of handling of HTTP requests and responses
  5476. * within the Deno CLI.
  5477. *
  5478. * Note that this function *consumes* the given connection passed to it, thus
  5479. * the original connection will be unusable after calling this. Additionally,
  5480. * you need to ensure that the connection is not being used elsewhere when
  5481. * calling this function in order for the connection to be consumed properly.
  5482. *
  5483. * For instance, if there is a `Promise` that is waiting for read operation on
  5484. * the connection to complete, it is considered that the connection is being
  5485. * used elsewhere. In such a case, this function will fail.
  5486. *
  5487. * @category HTTP Server
  5488. * @deprecated This will be soft-removed in Deno 2.0. See the
  5489. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  5490. * for migration instructions.
  5491. */
  5492. export function serveHttp(conn: Conn): HttpConn;
  5493. /** The object that is returned from a {@linkcode Deno.upgradeWebSocket}
  5494. * request.
  5495. *
  5496. * @category Web Sockets */
  5497. export interface WebSocketUpgrade {
  5498. /** The response object that represents the HTTP response to the client,
  5499. * which should be used to the {@linkcode RequestEvent} `.respondWith()` for
  5500. * the upgrade to be successful. */
  5501. response: Response;
  5502. /** The {@linkcode WebSocket} interface to communicate to the client via a
  5503. * web socket. */
  5504. socket: WebSocket;
  5505. }
  5506. /** Options which can be set when performing a
  5507. * {@linkcode Deno.upgradeWebSocket} upgrade of a {@linkcode Request}
  5508. *
  5509. * @category Web Sockets */
  5510. export interface UpgradeWebSocketOptions {
  5511. /** Sets the `.protocol` property on the client side web socket to the
  5512. * value provided here, which should be one of the strings specified in the
  5513. * `protocols` parameter when requesting the web socket. This is intended
  5514. * for clients and servers to specify sub-protocols to use to communicate to
  5515. * each other. */
  5516. protocol?: string;
  5517. /** If the client does not respond to this frame with a
  5518. * `pong` within the timeout specified, the connection is deemed
  5519. * unhealthy and is closed. The `close` and `error` event will be emitted.
  5520. *
  5521. * The unit is seconds, with a default of 30.
  5522. * Set to `0` to disable timeouts. */
  5523. idleTimeout?: number;
  5524. }
  5525. /**
  5526. * Upgrade an incoming HTTP request to a WebSocket.
  5527. *
  5528. * Given a {@linkcode Request}, returns a pair of {@linkcode WebSocket} and
  5529. * {@linkcode Response} instances. The original request must be responded to
  5530. * with the returned response for the websocket upgrade to be successful.
  5531. *
  5532. * ```ts
  5533. * const conn = Deno.listen({ port: 80 });
  5534. * const httpConn = Deno.serveHttp(await conn.accept());
  5535. * const e = await httpConn.nextRequest();
  5536. * if (e) {
  5537. * const { socket, response } = Deno.upgradeWebSocket(e.request);
  5538. * socket.onopen = () => {
  5539. * socket.send("Hello World!");
  5540. * };
  5541. * socket.onmessage = (e) => {
  5542. * console.log(e.data);
  5543. * socket.close();
  5544. * };
  5545. * socket.onclose = () => console.log("WebSocket has been closed.");
  5546. * socket.onerror = (e) => console.error("WebSocket error:", e);
  5547. * e.respondWith(response);
  5548. * }
  5549. * ```
  5550. *
  5551. * If the request body is disturbed (read from) before the upgrade is
  5552. * completed, upgrading fails.
  5553. *
  5554. * This operation does not yet consume the request or open the websocket. This
  5555. * only happens once the returned response has been passed to `respondWith()`.
  5556. *
  5557. * @category Web Sockets
  5558. */
  5559. export function upgradeWebSocket(
  5560. request: Request,
  5561. options?: UpgradeWebSocketOptions,
  5562. ): WebSocketUpgrade;
  5563. /** Send a signal to process under given `pid`. The value and meaning of the
  5564. * `signal` to the process is operating system and process dependant.
  5565. * {@linkcode Signal} provides the most common signals. Default signal
  5566. * is `"SIGTERM"`.
  5567. *
  5568. * The term `kill` is adopted from the UNIX-like command line command `kill`
  5569. * which also signals processes.
  5570. *
  5571. * If `pid` is negative, the signal will be sent to the process group
  5572. * identified by `pid`. An error will be thrown if a negative `pid` is used on
  5573. * Windows.
  5574. *
  5575. * ```ts
  5576. * const p = Deno.run({
  5577. * cmd: ["sleep", "10000"]
  5578. * });
  5579. *
  5580. * Deno.kill(p.pid, "SIGINT");
  5581. * ```
  5582. *
  5583. * Requires `allow-run` permission.
  5584. *
  5585. * @tags allow-run
  5586. * @category Sub Process
  5587. */
  5588. export function kill(pid: number, signo?: Signal): void;
  5589. /** The type of the resource record to resolve via DNS using
  5590. * {@linkcode Deno.resolveDns}.
  5591. *
  5592. * Only the listed types are supported currently.
  5593. *
  5594. * @category Network
  5595. */
  5596. export type RecordType =
  5597. | "A"
  5598. | "AAAA"
  5599. | "ANAME"
  5600. | "CAA"
  5601. | "CNAME"
  5602. | "MX"
  5603. | "NAPTR"
  5604. | "NS"
  5605. | "PTR"
  5606. | "SOA"
  5607. | "SRV"
  5608. | "TXT";
  5609. /**
  5610. * Options which can be set when using {@linkcode Deno.resolveDns}.
  5611. *
  5612. * @category Network */
  5613. export interface ResolveDnsOptions {
  5614. /** The name server to be used for lookups.
  5615. *
  5616. * If not specified, defaults to the system configuration. For example
  5617. * `/etc/resolv.conf` on Unix-like systems. */
  5618. nameServer?: {
  5619. /** The IP address of the name server. */
  5620. ipAddr: string;
  5621. /** The port number the query will be sent to.
  5622. *
  5623. * @default {53} */
  5624. port?: number;
  5625. };
  5626. /**
  5627. * An abort signal to allow cancellation of the DNS resolution operation.
  5628. * If the signal becomes aborted the resolveDns operation will be stopped
  5629. * and the promise returned will be rejected with an AbortError.
  5630. */
  5631. signal?: AbortSignal;
  5632. }
  5633. /** If {@linkcode Deno.resolveDns} is called with `"CAA"` record type
  5634. * specified, it will resolve with an array of objects with this interface.
  5635. *
  5636. * @category Network
  5637. */
  5638. export interface CAARecord {
  5639. /** If `true`, indicates that the corresponding property tag **must** be
  5640. * understood if the semantics of the CAA record are to be correctly
  5641. * interpreted by an issuer.
  5642. *
  5643. * Issuers **must not** issue certificates for a domain if the relevant CAA
  5644. * Resource Record set contains unknown property tags that have `critical`
  5645. * set. */
  5646. critical: boolean;
  5647. /** An string that represents the identifier of the property represented by
  5648. * the record. */
  5649. tag: string;
  5650. /** The value associated with the tag. */
  5651. value: string;
  5652. }
  5653. /** If {@linkcode Deno.resolveDns} is called with `"MX"` record type
  5654. * specified, it will return an array of objects with this interface.
  5655. *
  5656. * @category Network */
  5657. export interface MXRecord {
  5658. /** A priority value, which is a relative value compared to the other
  5659. * preferences of MX records for the domain. */
  5660. preference: number;
  5661. /** The server that mail should be delivered to. */
  5662. exchange: string;
  5663. }
  5664. /** If {@linkcode Deno.resolveDns} is called with `"NAPTR"` record type
  5665. * specified, it will return an array of objects with this interface.
  5666. *
  5667. * @category Network */
  5668. export interface NAPTRRecord {
  5669. order: number;
  5670. preference: number;
  5671. flags: string;
  5672. services: string;
  5673. regexp: string;
  5674. replacement: string;
  5675. }
  5676. /** If {@linkcode Deno.resolveDns} is called with `"SOA"` record type
  5677. * specified, it will return an array of objects with this interface.
  5678. *
  5679. * @category Network */
  5680. export interface SOARecord {
  5681. mname: string;
  5682. rname: string;
  5683. serial: number;
  5684. refresh: number;
  5685. retry: number;
  5686. expire: number;
  5687. minimum: number;
  5688. }
  5689. /** If {@linkcode Deno.resolveDns} is called with `"SRV"` record type
  5690. * specified, it will return an array of objects with this interface.
  5691. *
  5692. * @category Network
  5693. */
  5694. export interface SRVRecord {
  5695. priority: number;
  5696. weight: number;
  5697. port: number;
  5698. target: string;
  5699. }
  5700. /**
  5701. * Performs DNS resolution against the given query, returning resolved
  5702. * records.
  5703. *
  5704. * Fails in the cases such as:
  5705. *
  5706. * - the query is in invalid format.
  5707. * - the options have an invalid parameter. For example `nameServer.port` is
  5708. * beyond the range of 16-bit unsigned integer.
  5709. * - the request timed out.
  5710. *
  5711. * ```ts
  5712. * const a = await Deno.resolveDns("example.com", "A");
  5713. *
  5714. * const aaaa = await Deno.resolveDns("example.com", "AAAA", {
  5715. * nameServer: { ipAddr: "8.8.8.8", port: 53 },
  5716. * });
  5717. * ```
  5718. *
  5719. * Requires `allow-net` permission.
  5720. *
  5721. * @tags allow-net
  5722. * @category Network
  5723. */
  5724. export function resolveDns(
  5725. query: string,
  5726. recordType: "A" | "AAAA" | "ANAME" | "CNAME" | "NS" | "PTR",
  5727. options?: ResolveDnsOptions,
  5728. ): Promise<string[]>;
  5729. /**
  5730. * Performs DNS resolution against the given query, returning resolved
  5731. * records.
  5732. *
  5733. * Fails in the cases such as:
  5734. *
  5735. * - the query is in invalid format.
  5736. * - the options have an invalid parameter. For example `nameServer.port` is
  5737. * beyond the range of 16-bit unsigned integer.
  5738. * - the request timed out.
  5739. *
  5740. * ```ts
  5741. * const a = await Deno.resolveDns("example.com", "A");
  5742. *
  5743. * const aaaa = await Deno.resolveDns("example.com", "AAAA", {
  5744. * nameServer: { ipAddr: "8.8.8.8", port: 53 },
  5745. * });
  5746. * ```
  5747. *
  5748. * Requires `allow-net` permission.
  5749. *
  5750. * @tags allow-net
  5751. * @category Network
  5752. */
  5753. export function resolveDns(
  5754. query: string,
  5755. recordType: "CAA",
  5756. options?: ResolveDnsOptions,
  5757. ): Promise<CAARecord[]>;
  5758. /**
  5759. * Performs DNS resolution against the given query, returning resolved
  5760. * records.
  5761. *
  5762. * Fails in the cases such as:
  5763. *
  5764. * - the query is in invalid format.
  5765. * - the options have an invalid parameter. For example `nameServer.port` is
  5766. * beyond the range of 16-bit unsigned integer.
  5767. * - the request timed out.
  5768. *
  5769. * ```ts
  5770. * const a = await Deno.resolveDns("example.com", "A");
  5771. *
  5772. * const aaaa = await Deno.resolveDns("example.com", "AAAA", {
  5773. * nameServer: { ipAddr: "8.8.8.8", port: 53 },
  5774. * });
  5775. * ```
  5776. *
  5777. * Requires `allow-net` permission.
  5778. *
  5779. * @tags allow-net
  5780. * @category Network
  5781. */
  5782. export function resolveDns(
  5783. query: string,
  5784. recordType: "MX",
  5785. options?: ResolveDnsOptions,
  5786. ): Promise<MXRecord[]>;
  5787. /**
  5788. * Performs DNS resolution against the given query, returning resolved
  5789. * records.
  5790. *
  5791. * Fails in the cases such as:
  5792. *
  5793. * - the query is in invalid format.
  5794. * - the options have an invalid parameter. For example `nameServer.port` is
  5795. * beyond the range of 16-bit unsigned integer.
  5796. * - the request timed out.
  5797. *
  5798. * ```ts
  5799. * const a = await Deno.resolveDns("example.com", "A");
  5800. *
  5801. * const aaaa = await Deno.resolveDns("example.com", "AAAA", {
  5802. * nameServer: { ipAddr: "8.8.8.8", port: 53 },
  5803. * });
  5804. * ```
  5805. *
  5806. * Requires `allow-net` permission.
  5807. *
  5808. * @tags allow-net
  5809. * @category Network
  5810. */
  5811. export function resolveDns(
  5812. query: string,
  5813. recordType: "NAPTR",
  5814. options?: ResolveDnsOptions,
  5815. ): Promise<NAPTRRecord[]>;
  5816. /**
  5817. * Performs DNS resolution against the given query, returning resolved
  5818. * records.
  5819. *
  5820. * Fails in the cases such as:
  5821. *
  5822. * - the query is in invalid format.
  5823. * - the options have an invalid parameter. For example `nameServer.port` is
  5824. * beyond the range of 16-bit unsigned integer.
  5825. * - the request timed out.
  5826. *
  5827. * ```ts
  5828. * const a = await Deno.resolveDns("example.com", "A");
  5829. *
  5830. * const aaaa = await Deno.resolveDns("example.com", "AAAA", {
  5831. * nameServer: { ipAddr: "8.8.8.8", port: 53 },
  5832. * });
  5833. * ```
  5834. *
  5835. * Requires `allow-net` permission.
  5836. *
  5837. * @tags allow-net
  5838. * @category Network
  5839. */
  5840. export function resolveDns(
  5841. query: string,
  5842. recordType: "SOA",
  5843. options?: ResolveDnsOptions,
  5844. ): Promise<SOARecord[]>;
  5845. /**
  5846. * Performs DNS resolution against the given query, returning resolved
  5847. * records.
  5848. *
  5849. * Fails in the cases such as:
  5850. *
  5851. * - the query is in invalid format.
  5852. * - the options have an invalid parameter. For example `nameServer.port` is
  5853. * beyond the range of 16-bit unsigned integer.
  5854. * - the request timed out.
  5855. *
  5856. * ```ts
  5857. * const a = await Deno.resolveDns("example.com", "A");
  5858. *
  5859. * const aaaa = await Deno.resolveDns("example.com", "AAAA", {
  5860. * nameServer: { ipAddr: "8.8.8.8", port: 53 },
  5861. * });
  5862. * ```
  5863. *
  5864. * Requires `allow-net` permission.
  5865. *
  5866. * @tags allow-net
  5867. * @category Network
  5868. */
  5869. export function resolveDns(
  5870. query: string,
  5871. recordType: "SRV",
  5872. options?: ResolveDnsOptions,
  5873. ): Promise<SRVRecord[]>;
  5874. /**
  5875. * Performs DNS resolution against the given query, returning resolved
  5876. * records.
  5877. *
  5878. * Fails in the cases such as:
  5879. *
  5880. * - the query is in invalid format.
  5881. * - the options have an invalid parameter. For example `nameServer.port` is
  5882. * beyond the range of 16-bit unsigned integer.
  5883. * - the request timed out.
  5884. *
  5885. * ```ts
  5886. * const a = await Deno.resolveDns("example.com", "A");
  5887. *
  5888. * const aaaa = await Deno.resolveDns("example.com", "AAAA", {
  5889. * nameServer: { ipAddr: "8.8.8.8", port: 53 },
  5890. * });
  5891. * ```
  5892. *
  5893. * Requires `allow-net` permission.
  5894. *
  5895. * @tags allow-net
  5896. * @category Network
  5897. */
  5898. export function resolveDns(
  5899. query: string,
  5900. recordType: "TXT",
  5901. options?: ResolveDnsOptions,
  5902. ): Promise<string[][]>;
  5903. /**
  5904. * Performs DNS resolution against the given query, returning resolved
  5905. * records.
  5906. *
  5907. * Fails in the cases such as:
  5908. *
  5909. * - the query is in invalid format.
  5910. * - the options have an invalid parameter. For example `nameServer.port` is
  5911. * beyond the range of 16-bit unsigned integer.
  5912. * - the request timed out.
  5913. *
  5914. * ```ts
  5915. * const a = await Deno.resolveDns("example.com", "A");
  5916. *
  5917. * const aaaa = await Deno.resolveDns("example.com", "AAAA", {
  5918. * nameServer: { ipAddr: "8.8.8.8", port: 53 },
  5919. * });
  5920. * ```
  5921. *
  5922. * Requires `allow-net` permission.
  5923. *
  5924. * @tags allow-net
  5925. * @category Network
  5926. */
  5927. export function resolveDns(
  5928. query: string,
  5929. recordType: RecordType,
  5930. options?: ResolveDnsOptions,
  5931. ): Promise<
  5932. | string[]
  5933. | CAARecord[]
  5934. | MXRecord[]
  5935. | NAPTRRecord[]
  5936. | SOARecord[]
  5937. | SRVRecord[]
  5938. | string[][]
  5939. >;
  5940. /**
  5941. * Make the timer of the given `id` block the event loop from finishing.
  5942. *
  5943. * @category Runtime
  5944. */
  5945. export function refTimer(id: number): void;
  5946. /**
  5947. * Make the timer of the given `id` not block the event loop from finishing.
  5948. *
  5949. * @category Runtime
  5950. */
  5951. export function unrefTimer(id: number): void;
  5952. /**
  5953. * Returns the user id of the process on POSIX platforms. Returns null on Windows.
  5954. *
  5955. * ```ts
  5956. * console.log(Deno.uid());
  5957. * ```
  5958. *
  5959. * Requires `allow-sys` permission.
  5960. *
  5961. * @tags allow-sys
  5962. * @category Runtime
  5963. */
  5964. export function uid(): number | null;
  5965. /**
  5966. * Returns the group id of the process on POSIX platforms. Returns null on windows.
  5967. *
  5968. * ```ts
  5969. * console.log(Deno.gid());
  5970. * ```
  5971. *
  5972. * Requires `allow-sys` permission.
  5973. *
  5974. * @tags allow-sys
  5975. * @category Runtime
  5976. */
  5977. export function gid(): number | null;
  5978. /** Additional information for an HTTP request and its connection.
  5979. *
  5980. * @category HTTP Server
  5981. */
  5982. export interface ServeHandlerInfo {
  5983. /** The remote address of the connection. */
  5984. remoteAddr: Deno.NetAddr;
  5985. }
  5986. /** A handler for HTTP requests. Consumes a request and returns a response.
  5987. *
  5988. * If a handler throws, the server calling the handler will assume the impact
  5989. * of the error is isolated to the individual request. It will catch the error
  5990. * and if necessary will close the underlying connection.
  5991. *
  5992. * @category HTTP Server
  5993. */
  5994. export type ServeHandler = (
  5995. request: Request,
  5996. info: ServeHandlerInfo,
  5997. ) => Response | Promise<Response>;
  5998. /** Options which can be set when calling {@linkcode Deno.serve}.
  5999. *
  6000. * @category HTTP Server
  6001. */
  6002. export interface ServeOptions {
  6003. /** The port to listen on.
  6004. *
  6005. * Set to `0` to listen on any available port.
  6006. *
  6007. * @default {8000} */
  6008. port?: number;
  6009. /** A literal IP address or host name that can be resolved to an IP address.
  6010. *
  6011. * __Note about `0.0.0.0`__ While listening `0.0.0.0` works on all platforms,
  6012. * the browsers on Windows don't work with the address `0.0.0.0`.
  6013. * You should show the message like `server running on localhost:8080` instead of
  6014. * `server running on 0.0.0.0:8080` if your program supports Windows.
  6015. *
  6016. * @default {"0.0.0.0"} */
  6017. hostname?: string;
  6018. /** An {@linkcode AbortSignal} to close the server and all connections. */
  6019. signal?: AbortSignal;
  6020. /** Sets `SO_REUSEPORT` on POSIX systems. */
  6021. reusePort?: boolean;
  6022. /** The handler to invoke when route handlers throw an error. */
  6023. onError?: (error: unknown) => Response | Promise<Response>;
  6024. /** The callback which is called when the server starts listening. */
  6025. onListen?: (localAddr: Deno.NetAddr) => void;
  6026. }
  6027. /** Additional options which are used when opening a TLS (HTTPS) server.
  6028. *
  6029. * @category HTTP Server
  6030. */
  6031. export interface ServeTlsOptions extends ServeOptions {
  6032. /**
  6033. * Server private key in PEM format. Use {@linkcode TlsCertifiedKeyOptions} instead.
  6034. *
  6035. * @deprecated This will be removed in Deno 2.0. See the
  6036. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  6037. * for migration instructions.
  6038. */
  6039. cert?: string;
  6040. /**
  6041. * Cert chain in PEM format. Use {@linkcode TlsCertifiedKeyOptions} instead.
  6042. *
  6043. * @deprecated This will be removed in Deno 2.0. See the
  6044. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  6045. * for migration instructions.
  6046. */
  6047. key?: string;
  6048. }
  6049. /**
  6050. * @category HTTP Server
  6051. */
  6052. export interface ServeInit {
  6053. /** The handler to invoke to process each incoming request. */
  6054. handler: ServeHandler;
  6055. }
  6056. /**
  6057. * @category HTTP Server
  6058. */
  6059. export interface ServeTlsInit {
  6060. /** The handler to invoke to process each incoming request. */
  6061. handler: ServeHandler;
  6062. }
  6063. /** @category HTTP Server */
  6064. export interface ServeUnixOptions {
  6065. /** The unix domain socket path to listen on. */
  6066. path: string;
  6067. /** An {@linkcode AbortSignal} to close the server and all connections. */
  6068. signal?: AbortSignal;
  6069. /** The handler to invoke when route handlers throw an error. */
  6070. onError?: (error: unknown) => Response | Promise<Response>;
  6071. /** The callback which is called when the server starts listening. */
  6072. onListen?: (localAddr: Deno.UnixAddr) => void;
  6073. }
  6074. /** Information for a unix domain socket HTTP request.
  6075. *
  6076. * @category HTTP Server
  6077. */
  6078. export interface ServeUnixHandlerInfo {
  6079. /** The remote address of the connection. */
  6080. remoteAddr: Deno.UnixAddr;
  6081. }
  6082. /** A handler for unix domain socket HTTP requests. Consumes a request and returns a response.
  6083. *
  6084. * If a handler throws, the server calling the handler will assume the impact
  6085. * of the error is isolated to the individual request. It will catch the error
  6086. * and if necessary will close the underlying connection.
  6087. *
  6088. * @category HTTP Server
  6089. */
  6090. export type ServeUnixHandler = (
  6091. request: Request,
  6092. info: ServeUnixHandlerInfo,
  6093. ) => Response | Promise<Response>;
  6094. /**
  6095. * @category HTTP Server
  6096. */
  6097. export interface ServeUnixInit {
  6098. /** The handler to invoke to process each incoming request. */
  6099. handler: ServeUnixHandler;
  6100. }
  6101. /** An instance of the server created using `Deno.serve()` API.
  6102. *
  6103. * @category HTTP Server
  6104. */
  6105. export interface HttpServer<A extends Deno.Addr = Deno.Addr>
  6106. extends AsyncDisposable {
  6107. /** A promise that resolves once server finishes - eg. when aborted using
  6108. * the signal passed to {@linkcode ServeOptions.signal}.
  6109. */
  6110. finished: Promise<void>;
  6111. /** The local address this server is listening on. */
  6112. addr: A;
  6113. /**
  6114. * Make the server block the event loop from finishing.
  6115. *
  6116. * Note: the server blocks the event loop from finishing by default.
  6117. * This method is only meaningful after `.unref()` is called.
  6118. */
  6119. ref(): void;
  6120. /** Make the server not block the event loop from finishing. */
  6121. unref(): void;
  6122. /** Gracefully close the server. No more new connections will be accepted,
  6123. * while pending requests will be allowed to finish.
  6124. */
  6125. shutdown(): Promise<void>;
  6126. }
  6127. /**
  6128. * @category HTTP Server
  6129. *
  6130. * @deprecated This will be removed in Deno 2.0. See the
  6131. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  6132. * for migration instructions.
  6133. */
  6134. export type Server = HttpServer;
  6135. /** Serves HTTP requests with the given handler.
  6136. *
  6137. * The below example serves with the port `8000` on hostname `"127.0.0.1"`.
  6138. *
  6139. * ```ts
  6140. * Deno.serve((_req) => new Response("Hello, world"));
  6141. * ```
  6142. *
  6143. * @category HTTP Server
  6144. */
  6145. export function serve(handler: ServeHandler): HttpServer<Deno.NetAddr>;
  6146. /** Serves HTTP requests with the given option bag and handler.
  6147. *
  6148. * You can specify the socket path with `path` option.
  6149. *
  6150. * ```ts
  6151. * Deno.serve(
  6152. * { path: "path/to/socket" },
  6153. * (_req) => new Response("Hello, world")
  6154. * );
  6155. * ```
  6156. *
  6157. * You can stop the server with an {@linkcode AbortSignal}. The abort signal
  6158. * needs to be passed as the `signal` option in the options bag. The server
  6159. * aborts when the abort signal is aborted. To wait for the server to close,
  6160. * await the promise returned from the `Deno.serve` API.
  6161. *
  6162. * ```ts
  6163. * const ac = new AbortController();
  6164. *
  6165. * const server = Deno.serve(
  6166. * { signal: ac.signal, path: "path/to/socket" },
  6167. * (_req) => new Response("Hello, world")
  6168. * );
  6169. * server.finished.then(() => console.log("Server closed"));
  6170. *
  6171. * console.log("Closing server...");
  6172. * ac.abort();
  6173. * ```
  6174. *
  6175. * By default `Deno.serve` prints the message
  6176. * `Listening on path/to/socket` on listening. If you like to
  6177. * change this behavior, you can specify a custom `onListen` callback.
  6178. *
  6179. * ```ts
  6180. * Deno.serve({
  6181. * onListen({ path }) {
  6182. * console.log(`Server started at ${path}`);
  6183. * // ... more info specific to your server ..
  6184. * },
  6185. * path: "path/to/socket",
  6186. * }, (_req) => new Response("Hello, world"));
  6187. * ```
  6188. *
  6189. * @category HTTP Server
  6190. */
  6191. export function serve(
  6192. options: ServeUnixOptions,
  6193. handler: ServeUnixHandler,
  6194. ): HttpServer<Deno.UnixAddr>;
  6195. /** Serves HTTP requests with the given option bag and handler.
  6196. *
  6197. * You can specify an object with a port and hostname option, which is the
  6198. * address to listen on. The default is port `8000` on hostname `"127.0.0.1"`.
  6199. *
  6200. * You can change the address to listen on using the `hostname` and `port`
  6201. * options. The below example serves on port `3000` and hostname `"0.0.0.0"`.
  6202. *
  6203. * ```ts
  6204. * Deno.serve(
  6205. * { port: 3000, hostname: "0.0.0.0" },
  6206. * (_req) => new Response("Hello, world")
  6207. * );
  6208. * ```
  6209. *
  6210. * You can stop the server with an {@linkcode AbortSignal}. The abort signal
  6211. * needs to be passed as the `signal` option in the options bag. The server
  6212. * aborts when the abort signal is aborted. To wait for the server to close,
  6213. * await the promise returned from the `Deno.serve` API.
  6214. *
  6215. * ```ts
  6216. * const ac = new AbortController();
  6217. *
  6218. * const server = Deno.serve(
  6219. * { signal: ac.signal },
  6220. * (_req) => new Response("Hello, world")
  6221. * );
  6222. * server.finished.then(() => console.log("Server closed"));
  6223. *
  6224. * console.log("Closing server...");
  6225. * ac.abort();
  6226. * ```
  6227. *
  6228. * By default `Deno.serve` prints the message
  6229. * `Listening on http://<hostname>:<port>/` on listening. If you like to
  6230. * change this behavior, you can specify a custom `onListen` callback.
  6231. *
  6232. * ```ts
  6233. * Deno.serve({
  6234. * onListen({ port, hostname }) {
  6235. * console.log(`Server started at http://${hostname}:${port}`);
  6236. * // ... more info specific to your server ..
  6237. * },
  6238. * }, (_req) => new Response("Hello, world"));
  6239. * ```
  6240. *
  6241. * To enable TLS you must specify the `key` and `cert` options.
  6242. *
  6243. * ```ts
  6244. * const cert = "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n";
  6245. * const key = "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n";
  6246. * Deno.serve({ cert, key }, (_req) => new Response("Hello, world"));
  6247. * ```
  6248. *
  6249. * @category HTTP Server
  6250. */
  6251. export function serve(
  6252. options: ServeOptions,
  6253. handler: ServeHandler,
  6254. ): HttpServer<Deno.NetAddr>;
  6255. /** Serves HTTP requests with the given option bag and handler.
  6256. *
  6257. * You can specify an object with a port and hostname option, which is the
  6258. * address to listen on. The default is port `8000` on hostname `"127.0.0.1"`.
  6259. *
  6260. * You can change the address to listen on using the `hostname` and `port`
  6261. * options. The below example serves on port `3000` and hostname `"0.0.0.0"`.
  6262. *
  6263. * ```ts
  6264. * Deno.serve(
  6265. * { port: 3000, hostname: "0.0.0.0" },
  6266. * (_req) => new Response("Hello, world")
  6267. * );
  6268. * ```
  6269. *
  6270. * You can stop the server with an {@linkcode AbortSignal}. The abort signal
  6271. * needs to be passed as the `signal` option in the options bag. The server
  6272. * aborts when the abort signal is aborted. To wait for the server to close,
  6273. * await the promise returned from the `Deno.serve` API.
  6274. *
  6275. * ```ts
  6276. * const ac = new AbortController();
  6277. *
  6278. * const server = Deno.serve(
  6279. * { signal: ac.signal },
  6280. * (_req) => new Response("Hello, world")
  6281. * );
  6282. * server.finished.then(() => console.log("Server closed"));
  6283. *
  6284. * console.log("Closing server...");
  6285. * ac.abort();
  6286. * ```
  6287. *
  6288. * By default `Deno.serve` prints the message
  6289. * `Listening on http://<hostname>:<port>/` on listening. If you like to
  6290. * change this behavior, you can specify a custom `onListen` callback.
  6291. *
  6292. * ```ts
  6293. * Deno.serve({
  6294. * onListen({ port, hostname }) {
  6295. * console.log(`Server started at http://${hostname}:${port}`);
  6296. * // ... more info specific to your server ..
  6297. * },
  6298. * }, (_req) => new Response("Hello, world"));
  6299. * ```
  6300. *
  6301. * To enable TLS you must specify the `key` and `cert` options.
  6302. *
  6303. * ```ts
  6304. * const cert = "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n";
  6305. * const key = "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n";
  6306. * Deno.serve({ cert, key }, (_req) => new Response("Hello, world"));
  6307. * ```
  6308. *
  6309. * @category HTTP Server
  6310. */
  6311. export function serve(
  6312. options:
  6313. | ServeTlsOptions
  6314. | (ServeTlsOptions & TlsCertifiedKeyOptions),
  6315. handler: ServeHandler,
  6316. ): HttpServer<Deno.NetAddr>;
  6317. /** Serves HTTP requests with the given option bag.
  6318. *
  6319. * You can specify an object with the path option, which is the
  6320. * unix domain socket to listen on.
  6321. *
  6322. * ```ts
  6323. * const ac = new AbortController();
  6324. *
  6325. * const server = Deno.serve({
  6326. * path: "path/to/socket",
  6327. * handler: (_req) => new Response("Hello, world"),
  6328. * signal: ac.signal,
  6329. * onListen({ path }) {
  6330. * console.log(`Server started at ${path}`);
  6331. * },
  6332. * });
  6333. * server.finished.then(() => console.log("Server closed"));
  6334. *
  6335. * console.log("Closing server...");
  6336. * ac.abort();
  6337. * ```
  6338. *
  6339. * @category HTTP Server
  6340. */
  6341. export function serve(
  6342. options: ServeUnixInit & ServeUnixOptions,
  6343. ): HttpServer<Deno.UnixAddr>;
  6344. /** Serves HTTP requests with the given option bag.
  6345. *
  6346. * You can specify an object with a port and hostname option, which is the
  6347. * address to listen on. The default is port `8000` on hostname `"127.0.0.1"`.
  6348. *
  6349. * ```ts
  6350. * const ac = new AbortController();
  6351. *
  6352. * const server = Deno.serve({
  6353. * port: 3000,
  6354. * hostname: "0.0.0.0",
  6355. * handler: (_req) => new Response("Hello, world"),
  6356. * signal: ac.signal,
  6357. * onListen({ port, hostname }) {
  6358. * console.log(`Server started at http://${hostname}:${port}`);
  6359. * },
  6360. * });
  6361. * server.finished.then(() => console.log("Server closed"));
  6362. *
  6363. * console.log("Closing server...");
  6364. * ac.abort();
  6365. * ```
  6366. *
  6367. * @category HTTP Server
  6368. */
  6369. export function serve(
  6370. options:
  6371. & ServeInit
  6372. & ServeOptions,
  6373. ): HttpServer<Deno.NetAddr>;
  6374. /** Serves HTTP requests with the given option bag.
  6375. *
  6376. * You can specify an object with a port and hostname option, which is the
  6377. * address to listen on. The default is port `8000` on hostname `"127.0.0.1"`.
  6378. *
  6379. * ```ts
  6380. * const ac = new AbortController();
  6381. *
  6382. * const server = Deno.serve({
  6383. * port: 3000,
  6384. * hostname: "0.0.0.0",
  6385. * handler: (_req) => new Response("Hello, world"),
  6386. * signal: ac.signal,
  6387. * onListen({ port, hostname }) {
  6388. * console.log(`Server started at http://${hostname}:${port}`);
  6389. * },
  6390. * });
  6391. * server.finished.then(() => console.log("Server closed"));
  6392. *
  6393. * console.log("Closing server...");
  6394. * ac.abort();
  6395. * ```
  6396. *
  6397. * @category HTTP Server
  6398. */
  6399. export function serve(
  6400. options:
  6401. & ServeTlsInit
  6402. & (
  6403. | ServeTlsOptions
  6404. | (ServeTlsOptions & TlsCertifiedKeyOptions)
  6405. ),
  6406. ): HttpServer<Deno.NetAddr>;
  6407. }
  6408. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  6409. // deno-lint-ignore-file no-explicit-any
  6410. /// <reference no-default-lib="true" />
  6411. /// <reference lib="esnext" />
  6412. /** @category I/O */
  6413. declare interface Console {
  6414. assert(condition?: boolean, ...data: any[]): void;
  6415. clear(): void;
  6416. count(label?: string): void;
  6417. countReset(label?: string): void;
  6418. debug(...data: any[]): void;
  6419. dir(item?: any, options?: any): void;
  6420. dirxml(...data: any[]): void;
  6421. error(...data: any[]): void;
  6422. group(...data: any[]): void;
  6423. groupCollapsed(...data: any[]): void;
  6424. groupEnd(): void;
  6425. info(...data: any[]): void;
  6426. log(...data: any[]): void;
  6427. table(tabularData?: any, properties?: string[]): void;
  6428. time(label?: string): void;
  6429. timeEnd(label?: string): void;
  6430. timeLog(label?: string, ...data: any[]): void;
  6431. trace(...data: any[]): void;
  6432. warn(...data: any[]): void;
  6433. /** This method is a noop, unless used in inspector */
  6434. timeStamp(label?: string): void;
  6435. /** This method is a noop, unless used in inspector */
  6436. profile(label?: string): void;
  6437. /** This method is a noop, unless used in inspector */
  6438. profileEnd(label?: string): void;
  6439. }
  6440. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  6441. // deno-lint-ignore-file no-explicit-any no-var
  6442. /// <reference no-default-lib="true" />
  6443. /// <reference lib="esnext" />
  6444. /** @category URL */
  6445. declare interface URLSearchParams {
  6446. /** Appends a specified key/value pair as a new search parameter.
  6447. *
  6448. * ```ts
  6449. * let searchParams = new URLSearchParams();
  6450. * searchParams.append('name', 'first');
  6451. * searchParams.append('name', 'second');
  6452. * ```
  6453. */
  6454. append(name: string, value: string): void;
  6455. /** Deletes search parameters that match a name, and optional value,
  6456. * from the list of all search parameters.
  6457. *
  6458. * ```ts
  6459. * let searchParams = new URLSearchParams([['name', 'value']]);
  6460. * searchParams.delete('name');
  6461. * searchParams.delete('name', 'value');
  6462. * ```
  6463. */
  6464. delete(name: string, value?: string): void;
  6465. /** Returns all the values associated with a given search parameter
  6466. * as an array.
  6467. *
  6468. * ```ts
  6469. * searchParams.getAll('name');
  6470. * ```
  6471. */
  6472. getAll(name: string): string[];
  6473. /** Returns the first value associated to the given search parameter.
  6474. *
  6475. * ```ts
  6476. * searchParams.get('name');
  6477. * ```
  6478. */
  6479. get(name: string): string | null;
  6480. /** Returns a boolean value indicating if a given parameter,
  6481. * or parameter and value pair, exists.
  6482. *
  6483. * ```ts
  6484. * searchParams.has('name');
  6485. * searchParams.has('name', 'value');
  6486. * ```
  6487. */
  6488. has(name: string, value?: string): boolean;
  6489. /** Sets the value associated with a given search parameter to the
  6490. * given value. If there were several matching values, this method
  6491. * deletes the others. If the search parameter doesn't exist, this
  6492. * method creates it.
  6493. *
  6494. * ```ts
  6495. * searchParams.set('name', 'value');
  6496. * ```
  6497. */
  6498. set(name: string, value: string): void;
  6499. /** Sort all key/value pairs contained in this object in place and
  6500. * return undefined. The sort order is according to Unicode code
  6501. * points of the keys.
  6502. *
  6503. * ```ts
  6504. * searchParams.sort();
  6505. * ```
  6506. */
  6507. sort(): void;
  6508. /** Calls a function for each element contained in this object in
  6509. * place and return undefined. Optionally accepts an object to use
  6510. * as this when executing callback as second argument.
  6511. *
  6512. * ```ts
  6513. * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
  6514. * params.forEach((value, key, parent) => {
  6515. * console.log(value, key, parent);
  6516. * });
  6517. * ```
  6518. */
  6519. forEach(
  6520. callbackfn: (value: string, key: string, parent: this) => void,
  6521. thisArg?: any,
  6522. ): void;
  6523. /** Returns an iterator allowing to go through all keys contained
  6524. * in this object.
  6525. *
  6526. * ```ts
  6527. * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
  6528. * for (const key of params.keys()) {
  6529. * console.log(key);
  6530. * }
  6531. * ```
  6532. */
  6533. keys(): IterableIterator<string>;
  6534. /** Returns an iterator allowing to go through all values contained
  6535. * in this object.
  6536. *
  6537. * ```ts
  6538. * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
  6539. * for (const value of params.values()) {
  6540. * console.log(value);
  6541. * }
  6542. * ```
  6543. */
  6544. values(): IterableIterator<string>;
  6545. /** Returns an iterator allowing to go through all key/value
  6546. * pairs contained in this object.
  6547. *
  6548. * ```ts
  6549. * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
  6550. * for (const [key, value] of params.entries()) {
  6551. * console.log(key, value);
  6552. * }
  6553. * ```
  6554. */
  6555. entries(): IterableIterator<[string, string]>;
  6556. /** Returns an iterator allowing to go through all key/value
  6557. * pairs contained in this object.
  6558. *
  6559. * ```ts
  6560. * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
  6561. * for (const [key, value] of params) {
  6562. * console.log(key, value);
  6563. * }
  6564. * ```
  6565. */
  6566. [Symbol.iterator](): IterableIterator<[string, string]>;
  6567. /** Returns a query string suitable for use in a URL.
  6568. *
  6569. * ```ts
  6570. * searchParams.toString();
  6571. * ```
  6572. */
  6573. toString(): string;
  6574. /** Contains the number of search parameters
  6575. *
  6576. * ```ts
  6577. * searchParams.size
  6578. * ```
  6579. */
  6580. size: number;
  6581. }
  6582. /** @category URL */
  6583. declare var URLSearchParams: {
  6584. readonly prototype: URLSearchParams;
  6585. new (
  6586. init?: Iterable<string[]> | Record<string, string> | string,
  6587. ): URLSearchParams;
  6588. };
  6589. /** The URL interface represents an object providing static methods used for
  6590. * creating object URLs.
  6591. *
  6592. * @category URL
  6593. */
  6594. declare interface URL {
  6595. hash: string;
  6596. host: string;
  6597. hostname: string;
  6598. href: string;
  6599. toString(): string;
  6600. readonly origin: string;
  6601. password: string;
  6602. pathname: string;
  6603. port: string;
  6604. protocol: string;
  6605. search: string;
  6606. readonly searchParams: URLSearchParams;
  6607. username: string;
  6608. toJSON(): string;
  6609. }
  6610. /** The URL interface represents an object providing static methods used for
  6611. * creating object URLs.
  6612. *
  6613. * @category URL
  6614. */
  6615. declare var URL: {
  6616. readonly prototype: URL;
  6617. new (url: string | URL, base?: string | URL): URL;
  6618. parse(url: string | URL, base?: string | URL): URL | null;
  6619. canParse(url: string | URL, base?: string | URL): boolean;
  6620. createObjectURL(blob: Blob): string;
  6621. revokeObjectURL(url: string): void;
  6622. };
  6623. /** @category URL */
  6624. declare interface URLPatternInit {
  6625. protocol?: string;
  6626. username?: string;
  6627. password?: string;
  6628. hostname?: string;
  6629. port?: string;
  6630. pathname?: string;
  6631. search?: string;
  6632. hash?: string;
  6633. baseURL?: string;
  6634. }
  6635. /** @category URL */
  6636. declare type URLPatternInput = string | URLPatternInit;
  6637. /** @category URL */
  6638. declare interface URLPatternComponentResult {
  6639. input: string;
  6640. groups: Record<string, string | undefined>;
  6641. }
  6642. /** `URLPatternResult` is the object returned from `URLPattern.exec`.
  6643. *
  6644. * @category URL
  6645. */
  6646. declare interface URLPatternResult {
  6647. /** The inputs provided when matching. */
  6648. inputs: [URLPatternInit] | [URLPatternInit, string];
  6649. /** The matched result for the `protocol` matcher. */
  6650. protocol: URLPatternComponentResult;
  6651. /** The matched result for the `username` matcher. */
  6652. username: URLPatternComponentResult;
  6653. /** The matched result for the `password` matcher. */
  6654. password: URLPatternComponentResult;
  6655. /** The matched result for the `hostname` matcher. */
  6656. hostname: URLPatternComponentResult;
  6657. /** The matched result for the `port` matcher. */
  6658. port: URLPatternComponentResult;
  6659. /** The matched result for the `pathname` matcher. */
  6660. pathname: URLPatternComponentResult;
  6661. /** The matched result for the `search` matcher. */
  6662. search: URLPatternComponentResult;
  6663. /** The matched result for the `hash` matcher. */
  6664. hash: URLPatternComponentResult;
  6665. }
  6666. /**
  6667. * The URLPattern API provides a web platform primitive for matching URLs based
  6668. * on a convenient pattern syntax.
  6669. *
  6670. * The syntax is based on path-to-regexp. Wildcards, named capture groups,
  6671. * regular groups, and group modifiers are all supported.
  6672. *
  6673. * ```ts
  6674. * // Specify the pattern as structured data.
  6675. * const pattern = new URLPattern({ pathname: "/users/:user" });
  6676. * const match = pattern.exec("https://blog.example.com/users/joe");
  6677. * console.log(match.pathname.groups.user); // joe
  6678. * ```
  6679. *
  6680. * ```ts
  6681. * // Specify a fully qualified string pattern.
  6682. * const pattern = new URLPattern("https://example.com/books/:id");
  6683. * console.log(pattern.test("https://example.com/books/123")); // true
  6684. * console.log(pattern.test("https://deno.land/books/123")); // false
  6685. * ```
  6686. *
  6687. * ```ts
  6688. * // Specify a relative string pattern with a base URL.
  6689. * const pattern = new URLPattern("/article/:id", "https://blog.example.com");
  6690. * console.log(pattern.test("https://blog.example.com/article")); // false
  6691. * console.log(pattern.test("https://blog.example.com/article/123")); // true
  6692. * ```
  6693. *
  6694. * @category URL
  6695. */
  6696. declare interface URLPattern {
  6697. /**
  6698. * Test if the given input matches the stored pattern.
  6699. *
  6700. * The input can either be provided as an absolute URL string with an optional base,
  6701. * relative URL string with a required base, or as individual components
  6702. * in the form of an `URLPatternInit` object.
  6703. *
  6704. * ```ts
  6705. * const pattern = new URLPattern("https://example.com/books/:id");
  6706. *
  6707. * // Test an absolute url string.
  6708. * console.log(pattern.test("https://example.com/books/123")); // true
  6709. *
  6710. * // Test a relative url with a base.
  6711. * console.log(pattern.test("/books/123", "https://example.com")); // true
  6712. *
  6713. * // Test an object of url components.
  6714. * console.log(pattern.test({ pathname: "/books/123" })); // true
  6715. * ```
  6716. */
  6717. test(input: URLPatternInput, baseURL?: string): boolean;
  6718. /**
  6719. * Match the given input against the stored pattern.
  6720. *
  6721. * The input can either be provided as an absolute URL string with an optional base,
  6722. * relative URL string with a required base, or as individual components
  6723. * in the form of an `URLPatternInit` object.
  6724. *
  6725. * ```ts
  6726. * const pattern = new URLPattern("https://example.com/books/:id");
  6727. *
  6728. * // Match an absolute url string.
  6729. * let match = pattern.exec("https://example.com/books/123");
  6730. * console.log(match.pathname.groups.id); // 123
  6731. *
  6732. * // Match a relative url with a base.
  6733. * match = pattern.exec("/books/123", "https://example.com");
  6734. * console.log(match.pathname.groups.id); // 123
  6735. *
  6736. * // Match an object of url components.
  6737. * match = pattern.exec({ pathname: "/books/123" });
  6738. * console.log(match.pathname.groups.id); // 123
  6739. * ```
  6740. */
  6741. exec(input: URLPatternInput, baseURL?: string): URLPatternResult | null;
  6742. /** The pattern string for the `protocol`. */
  6743. readonly protocol: string;
  6744. /** The pattern string for the `username`. */
  6745. readonly username: string;
  6746. /** The pattern string for the `password`. */
  6747. readonly password: string;
  6748. /** The pattern string for the `hostname`. */
  6749. readonly hostname: string;
  6750. /** The pattern string for the `port`. */
  6751. readonly port: string;
  6752. /** The pattern string for the `pathname`. */
  6753. readonly pathname: string;
  6754. /** The pattern string for the `search`. */
  6755. readonly search: string;
  6756. /** The pattern string for the `hash`. */
  6757. readonly hash: string;
  6758. }
  6759. /**
  6760. * The URLPattern API provides a web platform primitive for matching URLs based
  6761. * on a convenient pattern syntax.
  6762. *
  6763. * The syntax is based on path-to-regexp. Wildcards, named capture groups,
  6764. * regular groups, and group modifiers are all supported.
  6765. *
  6766. * ```ts
  6767. * // Specify the pattern as structured data.
  6768. * const pattern = new URLPattern({ pathname: "/users/:user" });
  6769. * const match = pattern.exec("https://blog.example.com/users/joe");
  6770. * console.log(match.pathname.groups.user); // joe
  6771. * ```
  6772. *
  6773. * ```ts
  6774. * // Specify a fully qualified string pattern.
  6775. * const pattern = new URLPattern("https://example.com/books/:id");
  6776. * console.log(pattern.test("https://example.com/books/123")); // true
  6777. * console.log(pattern.test("https://deno.land/books/123")); // false
  6778. * ```
  6779. *
  6780. * ```ts
  6781. * // Specify a relative string pattern with a base URL.
  6782. * const pattern = new URLPattern("/article/:id", "https://blog.example.com");
  6783. * console.log(pattern.test("https://blog.example.com/article")); // false
  6784. * console.log(pattern.test("https://blog.example.com/article/123")); // true
  6785. * ```
  6786. *
  6787. * @category URL
  6788. */
  6789. declare var URLPattern: {
  6790. readonly prototype: URLPattern;
  6791. new (input: URLPatternInput, baseURL?: string): URLPattern;
  6792. };
  6793. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  6794. // deno-lint-ignore-file no-explicit-any no-var
  6795. /// <reference no-default-lib="true" />
  6796. /// <reference lib="esnext" />
  6797. /** @category Platform */
  6798. declare interface DOMException extends Error {
  6799. readonly name: string;
  6800. readonly message: string;
  6801. readonly code: number;
  6802. readonly INDEX_SIZE_ERR: 1;
  6803. readonly DOMSTRING_SIZE_ERR: 2;
  6804. readonly HIERARCHY_REQUEST_ERR: 3;
  6805. readonly WRONG_DOCUMENT_ERR: 4;
  6806. readonly INVALID_CHARACTER_ERR: 5;
  6807. readonly NO_DATA_ALLOWED_ERR: 6;
  6808. readonly NO_MODIFICATION_ALLOWED_ERR: 7;
  6809. readonly NOT_FOUND_ERR: 8;
  6810. readonly NOT_SUPPORTED_ERR: 9;
  6811. readonly INUSE_ATTRIBUTE_ERR: 10;
  6812. readonly INVALID_STATE_ERR: 11;
  6813. readonly SYNTAX_ERR: 12;
  6814. readonly INVALID_MODIFICATION_ERR: 13;
  6815. readonly NAMESPACE_ERR: 14;
  6816. readonly INVALID_ACCESS_ERR: 15;
  6817. readonly VALIDATION_ERR: 16;
  6818. readonly TYPE_MISMATCH_ERR: 17;
  6819. readonly SECURITY_ERR: 18;
  6820. readonly NETWORK_ERR: 19;
  6821. readonly ABORT_ERR: 20;
  6822. readonly URL_MISMATCH_ERR: 21;
  6823. readonly QUOTA_EXCEEDED_ERR: 22;
  6824. readonly TIMEOUT_ERR: 23;
  6825. readonly INVALID_NODE_TYPE_ERR: 24;
  6826. readonly DATA_CLONE_ERR: 25;
  6827. }
  6828. /** @category Platform */
  6829. declare var DOMException: {
  6830. readonly prototype: DOMException;
  6831. new (message?: string, name?: string): DOMException;
  6832. readonly INDEX_SIZE_ERR: 1;
  6833. readonly DOMSTRING_SIZE_ERR: 2;
  6834. readonly HIERARCHY_REQUEST_ERR: 3;
  6835. readonly WRONG_DOCUMENT_ERR: 4;
  6836. readonly INVALID_CHARACTER_ERR: 5;
  6837. readonly NO_DATA_ALLOWED_ERR: 6;
  6838. readonly NO_MODIFICATION_ALLOWED_ERR: 7;
  6839. readonly NOT_FOUND_ERR: 8;
  6840. readonly NOT_SUPPORTED_ERR: 9;
  6841. readonly INUSE_ATTRIBUTE_ERR: 10;
  6842. readonly INVALID_STATE_ERR: 11;
  6843. readonly SYNTAX_ERR: 12;
  6844. readonly INVALID_MODIFICATION_ERR: 13;
  6845. readonly NAMESPACE_ERR: 14;
  6846. readonly INVALID_ACCESS_ERR: 15;
  6847. readonly VALIDATION_ERR: 16;
  6848. readonly TYPE_MISMATCH_ERR: 17;
  6849. readonly SECURITY_ERR: 18;
  6850. readonly NETWORK_ERR: 19;
  6851. readonly ABORT_ERR: 20;
  6852. readonly URL_MISMATCH_ERR: 21;
  6853. readonly QUOTA_EXCEEDED_ERR: 22;
  6854. readonly TIMEOUT_ERR: 23;
  6855. readonly INVALID_NODE_TYPE_ERR: 24;
  6856. readonly DATA_CLONE_ERR: 25;
  6857. };
  6858. /** @category Events */
  6859. declare interface EventInit {
  6860. bubbles?: boolean;
  6861. cancelable?: boolean;
  6862. composed?: boolean;
  6863. }
  6864. /** An event which takes place in the DOM.
  6865. *
  6866. * @category Events
  6867. */
  6868. declare interface Event {
  6869. /** Returns true or false depending on how event was initialized. True if
  6870. * event goes through its target's ancestors in reverse tree order, and
  6871. * false otherwise. */
  6872. readonly bubbles: boolean;
  6873. cancelBubble: boolean;
  6874. /** Returns true or false depending on how event was initialized. Its return
  6875. * value does not always carry meaning, but true can indicate that part of the
  6876. * operation during which event was dispatched, can be canceled by invoking
  6877. * the preventDefault() method. */
  6878. readonly cancelable: boolean;
  6879. /** Returns true or false depending on how event was initialized. True if
  6880. * event invokes listeners past a ShadowRoot node that is the root of its
  6881. * target, and false otherwise. */
  6882. readonly composed: boolean;
  6883. /** Returns the object whose event listener's callback is currently being
  6884. * invoked. */
  6885. readonly currentTarget: EventTarget | null;
  6886. /** Returns true if preventDefault() was invoked successfully to indicate
  6887. * cancellation, and false otherwise. */
  6888. readonly defaultPrevented: boolean;
  6889. /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE,
  6890. * AT_TARGET, and BUBBLING_PHASE. */
  6891. readonly eventPhase: number;
  6892. /** Returns true if event was dispatched by the user agent, and false
  6893. * otherwise. */
  6894. readonly isTrusted: boolean;
  6895. /** Returns the object to which event is dispatched (its target). */
  6896. readonly target: EventTarget | null;
  6897. /** Returns the event's timestamp as the number of milliseconds measured
  6898. * relative to the time origin. */
  6899. readonly timeStamp: number;
  6900. /** Returns the type of event, e.g. "click", "hashchange", or "submit". */
  6901. readonly type: string;
  6902. /** Returns the invocation target objects of event's path (objects on which
  6903. * listeners will be invoked), except for any nodes in shadow trees of which
  6904. * the shadow root's mode is "closed" that are not reachable from event's
  6905. * currentTarget. */
  6906. composedPath(): EventTarget[];
  6907. /** If invoked when the cancelable attribute value is true, and while
  6908. * executing a listener for the event with passive set to false, signals to
  6909. * the operation that caused event to be dispatched that it needs to be
  6910. * canceled. */
  6911. preventDefault(): void;
  6912. /** Invoking this method prevents event from reaching any registered event
  6913. * listeners after the current one finishes running and, when dispatched in a
  6914. * tree, also prevents event from reaching any other objects. */
  6915. stopImmediatePropagation(): void;
  6916. /** When dispatched in a tree, invoking this method prevents event from
  6917. * reaching any objects other than the current object. */
  6918. stopPropagation(): void;
  6919. readonly AT_TARGET: number;
  6920. readonly BUBBLING_PHASE: number;
  6921. readonly CAPTURING_PHASE: number;
  6922. readonly NONE: number;
  6923. }
  6924. /** An event which takes place in the DOM.
  6925. *
  6926. * @category Events
  6927. */
  6928. declare var Event: {
  6929. readonly prototype: Event;
  6930. new (type: string, eventInitDict?: EventInit): Event;
  6931. readonly AT_TARGET: number;
  6932. readonly BUBBLING_PHASE: number;
  6933. readonly CAPTURING_PHASE: number;
  6934. readonly NONE: number;
  6935. };
  6936. /**
  6937. * EventTarget is a DOM interface implemented by objects that can receive events
  6938. * and may have listeners for them.
  6939. *
  6940. * @category Events
  6941. */
  6942. declare interface EventTarget {
  6943. /** Appends an event listener for events whose type attribute value is type.
  6944. * The callback argument sets the callback that will be invoked when the event
  6945. * is dispatched.
  6946. *
  6947. * The options argument sets listener-specific options. For compatibility this
  6948. * can be a boolean, in which case the method behaves exactly as if the value
  6949. * was specified as options's capture.
  6950. *
  6951. * When set to true, options's capture prevents callback from being invoked
  6952. * when the event's eventPhase attribute value is BUBBLING_PHASE. When false
  6953. * (or not present), callback will not be invoked when event's eventPhase
  6954. * attribute value is CAPTURING_PHASE. Either way, callback will be invoked if
  6955. * event's eventPhase attribute value is AT_TARGET.
  6956. *
  6957. * When set to true, options's passive indicates that the callback will not
  6958. * cancel the event by invoking preventDefault(). This is used to enable
  6959. * performance optimizations described in § 2.8 Observing event listeners.
  6960. *
  6961. * When set to true, options's once indicates that the callback will only be
  6962. * invoked once after which the event listener will be removed.
  6963. *
  6964. * The event listener is appended to target's event listener list and is not
  6965. * appended if it has the same type, callback, and capture. */
  6966. addEventListener(
  6967. type: string,
  6968. listener: EventListenerOrEventListenerObject | null,
  6969. options?: boolean | AddEventListenerOptions,
  6970. ): void;
  6971. /** Dispatches a synthetic event to event target and returns true if either
  6972. * event's cancelable attribute value is false or its preventDefault() method
  6973. * was not invoked, and false otherwise. */
  6974. dispatchEvent(event: Event): boolean;
  6975. /** Removes the event listener in target's event listener list with the same
  6976. * type, callback, and options. */
  6977. removeEventListener(
  6978. type: string,
  6979. callback: EventListenerOrEventListenerObject | null,
  6980. options?: EventListenerOptions | boolean,
  6981. ): void;
  6982. }
  6983. /**
  6984. * EventTarget is a DOM interface implemented by objects that can receive events
  6985. * and may have listeners for them.
  6986. *
  6987. * @category Events
  6988. */
  6989. declare var EventTarget: {
  6990. readonly prototype: EventTarget;
  6991. new (): EventTarget;
  6992. };
  6993. /** @category Events */
  6994. declare interface EventListener {
  6995. (evt: Event): void | Promise<void>;
  6996. }
  6997. /** @category Events */
  6998. declare interface EventListenerObject {
  6999. handleEvent(evt: Event): void | Promise<void>;
  7000. }
  7001. /** @category Events */
  7002. declare type EventListenerOrEventListenerObject =
  7003. | EventListener
  7004. | EventListenerObject;
  7005. /** @category Events */
  7006. declare interface AddEventListenerOptions extends EventListenerOptions {
  7007. once?: boolean;
  7008. passive?: boolean;
  7009. signal?: AbortSignal;
  7010. }
  7011. /** @category Events */
  7012. declare interface EventListenerOptions {
  7013. capture?: boolean;
  7014. }
  7015. /** @category Events */
  7016. declare interface ProgressEventInit extends EventInit {
  7017. lengthComputable?: boolean;
  7018. loaded?: number;
  7019. total?: number;
  7020. }
  7021. /** Events measuring progress of an underlying process, like an HTTP request
  7022. * (for an XMLHttpRequest, or the loading of the underlying resource of an
  7023. * <img>, <audio>, <video>, <style> or <link>).
  7024. *
  7025. * @category Events
  7026. */
  7027. declare interface ProgressEvent<T extends EventTarget = EventTarget>
  7028. extends Event {
  7029. readonly lengthComputable: boolean;
  7030. readonly loaded: number;
  7031. readonly target: T | null;
  7032. readonly total: number;
  7033. }
  7034. /** Events measuring progress of an underlying process, like an HTTP request
  7035. * (for an XMLHttpRequest, or the loading of the underlying resource of an
  7036. * <img>, <audio>, <video>, <style> or <link>).
  7037. *
  7038. * @category Events
  7039. */
  7040. declare var ProgressEvent: {
  7041. readonly prototype: ProgressEvent;
  7042. new (type: string, eventInitDict?: ProgressEventInit): ProgressEvent;
  7043. };
  7044. /** Decodes a string of data which has been encoded using base-64 encoding.
  7045. *
  7046. * ```
  7047. * console.log(atob("aGVsbG8gd29ybGQ=")); // outputs 'hello world'
  7048. * ```
  7049. *
  7050. * @category Encoding
  7051. */
  7052. declare function atob(s: string): string;
  7053. /** Creates a base-64 ASCII encoded string from the input string.
  7054. *
  7055. * ```
  7056. * console.log(btoa("hello world")); // outputs "aGVsbG8gd29ybGQ="
  7057. * ```
  7058. *
  7059. * @category Encoding
  7060. */
  7061. declare function btoa(s: string): string;
  7062. /** @category Encoding */
  7063. declare interface TextDecoderOptions {
  7064. fatal?: boolean;
  7065. ignoreBOM?: boolean;
  7066. }
  7067. /** @category Encoding */
  7068. declare interface TextDecodeOptions {
  7069. stream?: boolean;
  7070. }
  7071. /** @category Encoding */
  7072. declare interface TextDecoder {
  7073. /** Returns encoding's name, lowercased. */
  7074. readonly encoding: string;
  7075. /** Returns `true` if error mode is "fatal", and `false` otherwise. */
  7076. readonly fatal: boolean;
  7077. /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */
  7078. readonly ignoreBOM: boolean;
  7079. /** Returns the result of running encoding's decoder. */
  7080. decode(input?: BufferSource, options?: TextDecodeOptions): string;
  7081. }
  7082. /** @category Encoding */
  7083. declare var TextDecoder: {
  7084. readonly prototype: TextDecoder;
  7085. new (label?: string, options?: TextDecoderOptions): TextDecoder;
  7086. };
  7087. /** @category Encoding */
  7088. declare interface TextEncoderEncodeIntoResult {
  7089. read: number;
  7090. written: number;
  7091. }
  7092. /** @category Encoding */
  7093. declare interface TextEncoder {
  7094. /** Returns "utf-8". */
  7095. readonly encoding: "utf-8";
  7096. /** Returns the result of running UTF-8's encoder. */
  7097. encode(input?: string): Uint8Array;
  7098. encodeInto(input: string, dest: Uint8Array): TextEncoderEncodeIntoResult;
  7099. }
  7100. /** @category Encoding */
  7101. declare var TextEncoder: {
  7102. readonly prototype: TextEncoder;
  7103. new (): TextEncoder;
  7104. };
  7105. /** @category Encoding */
  7106. declare interface TextDecoderStream {
  7107. /** Returns encoding's name, lowercased. */
  7108. readonly encoding: string;
  7109. /** Returns `true` if error mode is "fatal", and `false` otherwise. */
  7110. readonly fatal: boolean;
  7111. /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */
  7112. readonly ignoreBOM: boolean;
  7113. readonly readable: ReadableStream<string>;
  7114. readonly writable: WritableStream<BufferSource>;
  7115. readonly [Symbol.toStringTag]: string;
  7116. }
  7117. /** @category Encoding */
  7118. declare var TextDecoderStream: {
  7119. readonly prototype: TextDecoderStream;
  7120. new (label?: string, options?: TextDecoderOptions): TextDecoderStream;
  7121. };
  7122. /** @category Encoding */
  7123. declare interface TextEncoderStream {
  7124. /** Returns "utf-8". */
  7125. readonly encoding: "utf-8";
  7126. readonly readable: ReadableStream<Uint8Array>;
  7127. readonly writable: WritableStream<string>;
  7128. readonly [Symbol.toStringTag]: string;
  7129. }
  7130. /** @category Encoding */
  7131. declare var TextEncoderStream: {
  7132. readonly prototype: TextEncoderStream;
  7133. new (): TextEncoderStream;
  7134. };
  7135. /** A controller object that allows you to abort one or more DOM requests as and
  7136. * when desired.
  7137. *
  7138. * @category Platform
  7139. */
  7140. declare interface AbortController {
  7141. /** Returns the AbortSignal object associated with this object. */
  7142. readonly signal: AbortSignal;
  7143. /** Invoking this method will set this object's AbortSignal's aborted flag and
  7144. * signal to any observers that the associated activity is to be aborted. */
  7145. abort(reason?: any): void;
  7146. }
  7147. /** A controller object that allows you to abort one or more DOM requests as and
  7148. * when desired.
  7149. *
  7150. * @category Platform
  7151. */
  7152. declare var AbortController: {
  7153. readonly prototype: AbortController;
  7154. new (): AbortController;
  7155. };
  7156. /** @category Platform */
  7157. declare interface AbortSignalEventMap {
  7158. abort: Event;
  7159. }
  7160. /** A signal object that allows you to communicate with a DOM request (such as a
  7161. * Fetch) and abort it if required via an AbortController object.
  7162. *
  7163. * @category Platform
  7164. */
  7165. declare interface AbortSignal extends EventTarget {
  7166. /** Returns true if this AbortSignal's AbortController has signaled to abort,
  7167. * and false otherwise. */
  7168. readonly aborted: boolean;
  7169. readonly reason: any;
  7170. onabort: ((this: AbortSignal, ev: Event) => any) | null;
  7171. addEventListener<K extends keyof AbortSignalEventMap>(
  7172. type: K,
  7173. listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any,
  7174. options?: boolean | AddEventListenerOptions,
  7175. ): void;
  7176. addEventListener(
  7177. type: string,
  7178. listener: EventListenerOrEventListenerObject,
  7179. options?: boolean | AddEventListenerOptions,
  7180. ): void;
  7181. removeEventListener<K extends keyof AbortSignalEventMap>(
  7182. type: K,
  7183. listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any,
  7184. options?: boolean | EventListenerOptions,
  7185. ): void;
  7186. removeEventListener(
  7187. type: string,
  7188. listener: EventListenerOrEventListenerObject,
  7189. options?: boolean | EventListenerOptions,
  7190. ): void;
  7191. /** Throws this AbortSignal's abort reason, if its AbortController has
  7192. * signaled to abort; otherwise, does nothing. */
  7193. throwIfAborted(): void;
  7194. }
  7195. /** @category Platform */
  7196. declare var AbortSignal: {
  7197. readonly prototype: AbortSignal;
  7198. new (): never;
  7199. abort(reason?: any): AbortSignal;
  7200. any(signals: AbortSignal[]): AbortSignal;
  7201. timeout(milliseconds: number): AbortSignal;
  7202. };
  7203. /** @category File */
  7204. declare interface FileReaderEventMap {
  7205. "abort": ProgressEvent<FileReader>;
  7206. "error": ProgressEvent<FileReader>;
  7207. "load": ProgressEvent<FileReader>;
  7208. "loadend": ProgressEvent<FileReader>;
  7209. "loadstart": ProgressEvent<FileReader>;
  7210. "progress": ProgressEvent<FileReader>;
  7211. }
  7212. /** Lets web applications asynchronously read the contents of files (or raw data
  7213. * buffers) stored on the user's computer, using File or Blob objects to specify
  7214. * the file or data to read.
  7215. *
  7216. * @category File
  7217. */
  7218. declare interface FileReader extends EventTarget {
  7219. readonly error: DOMException | null;
  7220. onabort: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null;
  7221. onerror: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null;
  7222. onload: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null;
  7223. onloadend: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null;
  7224. onloadstart:
  7225. | ((this: FileReader, ev: ProgressEvent<FileReader>) => any)
  7226. | null;
  7227. onprogress: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null;
  7228. readonly readyState: number;
  7229. readonly result: string | ArrayBuffer | null;
  7230. abort(): void;
  7231. readAsArrayBuffer(blob: Blob): void;
  7232. readAsBinaryString(blob: Blob): void;
  7233. readAsDataURL(blob: Blob): void;
  7234. readAsText(blob: Blob, encoding?: string): void;
  7235. readonly DONE: number;
  7236. readonly EMPTY: number;
  7237. readonly LOADING: number;
  7238. addEventListener<K extends keyof FileReaderEventMap>(
  7239. type: K,
  7240. listener: (this: FileReader, ev: FileReaderEventMap[K]) => any,
  7241. options?: boolean | AddEventListenerOptions,
  7242. ): void;
  7243. addEventListener(
  7244. type: string,
  7245. listener: EventListenerOrEventListenerObject,
  7246. options?: boolean | AddEventListenerOptions,
  7247. ): void;
  7248. removeEventListener<K extends keyof FileReaderEventMap>(
  7249. type: K,
  7250. listener: (this: FileReader, ev: FileReaderEventMap[K]) => any,
  7251. options?: boolean | EventListenerOptions,
  7252. ): void;
  7253. removeEventListener(
  7254. type: string,
  7255. listener: EventListenerOrEventListenerObject,
  7256. options?: boolean | EventListenerOptions,
  7257. ): void;
  7258. }
  7259. /** @category File */
  7260. declare var FileReader: {
  7261. readonly prototype: FileReader;
  7262. new (): FileReader;
  7263. readonly DONE: number;
  7264. readonly EMPTY: number;
  7265. readonly LOADING: number;
  7266. };
  7267. /** @category File */
  7268. declare type BlobPart = BufferSource | Blob | string;
  7269. /** @category File */
  7270. declare interface BlobPropertyBag {
  7271. type?: string;
  7272. endings?: "transparent" | "native";
  7273. }
  7274. /** A file-like object of immutable, raw data. Blobs represent data that isn't
  7275. * necessarily in a JavaScript-native format. The File interface is based on
  7276. * Blob, inheriting blob functionality and expanding it to support files on the
  7277. * user's system.
  7278. *
  7279. * @category File
  7280. */
  7281. declare interface Blob {
  7282. readonly size: number;
  7283. readonly type: string;
  7284. arrayBuffer(): Promise<ArrayBuffer>;
  7285. bytes(): Promise<Uint8Array>;
  7286. slice(start?: number, end?: number, contentType?: string): Blob;
  7287. stream(): ReadableStream<Uint8Array>;
  7288. text(): Promise<string>;
  7289. }
  7290. /** A file-like object of immutable, raw data. Blobs represent data that isn't
  7291. * necessarily in a JavaScript-native format. The File interface is based on
  7292. * Blob, inheriting blob functionality and expanding it to support files on the
  7293. * user's system.
  7294. *
  7295. * @category File
  7296. */
  7297. declare var Blob: {
  7298. readonly prototype: Blob;
  7299. new (blobParts?: BlobPart[], options?: BlobPropertyBag): Blob;
  7300. };
  7301. /** @category File */
  7302. declare interface FilePropertyBag extends BlobPropertyBag {
  7303. lastModified?: number;
  7304. }
  7305. /** Provides information about files and allows JavaScript in a web page to
  7306. * access their content.
  7307. *
  7308. * @category File
  7309. */
  7310. declare interface File extends Blob {
  7311. readonly lastModified: number;
  7312. readonly name: string;
  7313. }
  7314. /** Provides information about files and allows JavaScript in a web page to
  7315. * access their content.
  7316. *
  7317. * @category File
  7318. */
  7319. declare var File: {
  7320. readonly prototype: File;
  7321. new (fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File;
  7322. };
  7323. /** @category Streams */
  7324. declare interface ReadableStreamDefaultReadDoneResult {
  7325. done: true;
  7326. value?: undefined;
  7327. }
  7328. /** @category Streams */
  7329. declare interface ReadableStreamDefaultReadValueResult<T> {
  7330. done: false;
  7331. value: T;
  7332. }
  7333. /** @category Streams */
  7334. declare type ReadableStreamDefaultReadResult<T> =
  7335. | ReadableStreamDefaultReadValueResult<T>
  7336. | ReadableStreamDefaultReadDoneResult;
  7337. /** @category Streams */
  7338. declare interface ReadableStreamDefaultReader<R = any> {
  7339. readonly closed: Promise<void>;
  7340. cancel(reason?: any): Promise<void>;
  7341. read(): Promise<ReadableStreamDefaultReadResult<R>>;
  7342. releaseLock(): void;
  7343. }
  7344. /** @category Streams */
  7345. declare var ReadableStreamDefaultReader: {
  7346. readonly prototype: ReadableStreamDefaultReader;
  7347. new <R>(stream: ReadableStream<R>): ReadableStreamDefaultReader<R>;
  7348. };
  7349. /** @category Streams */
  7350. declare interface ReadableStreamBYOBReadDoneResult<V extends ArrayBufferView> {
  7351. done: true;
  7352. value?: V;
  7353. }
  7354. /** @category Streams */
  7355. declare interface ReadableStreamBYOBReadValueResult<V extends ArrayBufferView> {
  7356. done: false;
  7357. value: V;
  7358. }
  7359. /** @category Streams */
  7360. declare type ReadableStreamBYOBReadResult<V extends ArrayBufferView> =
  7361. | ReadableStreamBYOBReadDoneResult<V>
  7362. | ReadableStreamBYOBReadValueResult<V>;
  7363. /** @category Streams */
  7364. declare interface ReadableStreamBYOBReaderReadOptions {
  7365. min?: number;
  7366. }
  7367. /** @category Streams */
  7368. declare interface ReadableStreamBYOBReader {
  7369. readonly closed: Promise<void>;
  7370. cancel(reason?: any): Promise<void>;
  7371. read<V extends ArrayBufferView>(
  7372. view: V,
  7373. options?: ReadableStreamBYOBReaderReadOptions,
  7374. ): Promise<ReadableStreamBYOBReadResult<V>>;
  7375. releaseLock(): void;
  7376. }
  7377. /** @category Streams */
  7378. declare var ReadableStreamBYOBReader: {
  7379. readonly prototype: ReadableStreamBYOBReader;
  7380. new (stream: ReadableStream<Uint8Array>): ReadableStreamBYOBReader;
  7381. };
  7382. /** @category Streams */
  7383. declare interface ReadableStreamBYOBRequest {
  7384. readonly view: ArrayBufferView | null;
  7385. respond(bytesWritten: number): void;
  7386. respondWithNewView(view: ArrayBufferView): void;
  7387. }
  7388. /** @category Streams */
  7389. declare var ReadableStreamBYOBRequest: {
  7390. readonly prototype: ReadableStreamBYOBRequest;
  7391. new (): never;
  7392. };
  7393. /** @category Streams */
  7394. declare interface ReadableByteStreamControllerCallback {
  7395. (controller: ReadableByteStreamController): void | PromiseLike<void>;
  7396. }
  7397. /** @category Streams */
  7398. declare interface UnderlyingByteSource {
  7399. autoAllocateChunkSize?: number;
  7400. cancel?: ReadableStreamErrorCallback;
  7401. pull?: ReadableByteStreamControllerCallback;
  7402. start?: ReadableByteStreamControllerCallback;
  7403. type: "bytes";
  7404. }
  7405. /** @category Streams */
  7406. declare interface UnderlyingSink<W = any> {
  7407. abort?: WritableStreamErrorCallback;
  7408. close?: WritableStreamDefaultControllerCloseCallback;
  7409. start?: WritableStreamDefaultControllerStartCallback;
  7410. type?: undefined;
  7411. write?: WritableStreamDefaultControllerWriteCallback<W>;
  7412. }
  7413. /** @category Streams */
  7414. declare interface UnderlyingSource<R = any> {
  7415. cancel?: ReadableStreamErrorCallback;
  7416. pull?: ReadableStreamDefaultControllerCallback<R>;
  7417. start?: ReadableStreamDefaultControllerCallback<R>;
  7418. type?: undefined;
  7419. }
  7420. /** @category Streams */
  7421. declare interface ReadableStreamErrorCallback {
  7422. (reason: any): void | PromiseLike<void>;
  7423. }
  7424. /** @category Streams */
  7425. declare interface ReadableStreamDefaultControllerCallback<R> {
  7426. (controller: ReadableStreamDefaultController<R>): void | PromiseLike<void>;
  7427. }
  7428. /** @category Streams */
  7429. declare interface ReadableStreamDefaultController<R = any> {
  7430. readonly desiredSize: number | null;
  7431. close(): void;
  7432. enqueue(chunk: R): void;
  7433. error(error?: any): void;
  7434. }
  7435. /** @category Streams */
  7436. declare var ReadableStreamDefaultController: {
  7437. readonly prototype: ReadableStreamDefaultController;
  7438. new (): never;
  7439. };
  7440. /** @category Streams */
  7441. declare interface ReadableByteStreamController {
  7442. readonly byobRequest: ReadableStreamBYOBRequest | null;
  7443. readonly desiredSize: number | null;
  7444. close(): void;
  7445. enqueue(chunk: ArrayBufferView): void;
  7446. error(error?: any): void;
  7447. }
  7448. /** @category Streams */
  7449. declare var ReadableByteStreamController: {
  7450. readonly prototype: ReadableByteStreamController;
  7451. new (): never;
  7452. };
  7453. /** @category Streams */
  7454. declare interface PipeOptions {
  7455. preventAbort?: boolean;
  7456. preventCancel?: boolean;
  7457. preventClose?: boolean;
  7458. signal?: AbortSignal;
  7459. }
  7460. /** @category Streams */
  7461. declare interface QueuingStrategySizeCallback<T = any> {
  7462. (chunk: T): number;
  7463. }
  7464. /** @category Streams */
  7465. declare interface QueuingStrategy<T = any> {
  7466. highWaterMark?: number;
  7467. size?: QueuingStrategySizeCallback<T>;
  7468. }
  7469. /** This Streams API interface provides a built-in byte length queuing strategy
  7470. * that can be used when constructing streams.
  7471. *
  7472. * @category Streams
  7473. */
  7474. declare interface CountQueuingStrategy extends QueuingStrategy {
  7475. highWaterMark: number;
  7476. size(chunk: any): 1;
  7477. }
  7478. /** @category Streams */
  7479. declare var CountQueuingStrategy: {
  7480. readonly prototype: CountQueuingStrategy;
  7481. new (options: { highWaterMark: number }): CountQueuingStrategy;
  7482. };
  7483. /** @category Streams */
  7484. declare interface ByteLengthQueuingStrategy
  7485. extends QueuingStrategy<ArrayBufferView> {
  7486. highWaterMark: number;
  7487. size(chunk: ArrayBufferView): number;
  7488. }
  7489. /** @category Streams */
  7490. declare var ByteLengthQueuingStrategy: {
  7491. readonly prototype: ByteLengthQueuingStrategy;
  7492. new (options: { highWaterMark: number }): ByteLengthQueuingStrategy;
  7493. };
  7494. /** This Streams API interface represents a readable stream of byte data. The
  7495. * Fetch API offers a concrete instance of a ReadableStream through the body
  7496. * property of a Response object.
  7497. *
  7498. * @category Streams
  7499. */
  7500. declare interface ReadableStream<R = any> {
  7501. readonly locked: boolean;
  7502. cancel(reason?: any): Promise<void>;
  7503. getReader(options: { mode: "byob" }): ReadableStreamBYOBReader;
  7504. getReader(options?: { mode?: undefined }): ReadableStreamDefaultReader<R>;
  7505. pipeThrough<T>(transform: {
  7506. writable: WritableStream<R>;
  7507. readable: ReadableStream<T>;
  7508. }, options?: PipeOptions): ReadableStream<T>;
  7509. pipeTo(dest: WritableStream<R>, options?: PipeOptions): Promise<void>;
  7510. tee(): [ReadableStream<R>, ReadableStream<R>];
  7511. values(options?: {
  7512. preventCancel?: boolean;
  7513. }): AsyncIterableIterator<R>;
  7514. [Symbol.asyncIterator](options?: {
  7515. preventCancel?: boolean;
  7516. }): AsyncIterableIterator<R>;
  7517. }
  7518. /** @category Streams */
  7519. declare var ReadableStream: {
  7520. readonly prototype: ReadableStream;
  7521. new (
  7522. underlyingSource: UnderlyingByteSource,
  7523. strategy?: { highWaterMark?: number; size?: undefined },
  7524. ): ReadableStream<Uint8Array>;
  7525. new <R = any>(
  7526. underlyingSource?: UnderlyingSource<R>,
  7527. strategy?: QueuingStrategy<R>,
  7528. ): ReadableStream<R>;
  7529. from<R>(
  7530. asyncIterable: AsyncIterable<R> | Iterable<R | PromiseLike<R>>,
  7531. ): ReadableStream<R>;
  7532. };
  7533. /** @category Streams */
  7534. declare interface WritableStreamDefaultControllerCloseCallback {
  7535. (): void | PromiseLike<void>;
  7536. }
  7537. /** @category Streams */
  7538. declare interface WritableStreamDefaultControllerStartCallback {
  7539. (controller: WritableStreamDefaultController): void | PromiseLike<void>;
  7540. }
  7541. /** @category Streams */
  7542. declare interface WritableStreamDefaultControllerWriteCallback<W> {
  7543. (chunk: W, controller: WritableStreamDefaultController):
  7544. | void
  7545. | PromiseLike<
  7546. void
  7547. >;
  7548. }
  7549. /** @category Streams */
  7550. declare interface WritableStreamErrorCallback {
  7551. (reason: any): void | PromiseLike<void>;
  7552. }
  7553. /** This Streams API interface provides a standard abstraction for writing
  7554. * streaming data to a destination, known as a sink. This object comes with
  7555. * built-in backpressure and queuing.
  7556. *
  7557. * @category Streams
  7558. */
  7559. declare interface WritableStream<W = any> {
  7560. readonly locked: boolean;
  7561. abort(reason?: any): Promise<void>;
  7562. close(): Promise<void>;
  7563. getWriter(): WritableStreamDefaultWriter<W>;
  7564. }
  7565. /** @category Streams */
  7566. declare var WritableStream: {
  7567. readonly prototype: WritableStream;
  7568. new <W = any>(
  7569. underlyingSink?: UnderlyingSink<W>,
  7570. strategy?: QueuingStrategy<W>,
  7571. ): WritableStream<W>;
  7572. };
  7573. /** This Streams API interface represents a controller allowing control of a
  7574. * WritableStream's state. When constructing a WritableStream, the underlying
  7575. * sink is given a corresponding WritableStreamDefaultController instance to
  7576. * manipulate.
  7577. *
  7578. * @category Streams
  7579. */
  7580. declare interface WritableStreamDefaultController {
  7581. signal: AbortSignal;
  7582. error(error?: any): void;
  7583. }
  7584. /** @category Streams */
  7585. declare var WritableStreamDefaultController: {
  7586. readonly prototype: WritableStreamDefaultController;
  7587. new (): never;
  7588. };
  7589. /** This Streams API interface is the object returned by
  7590. * WritableStream.getWriter() and once created locks the < writer to the
  7591. * WritableStream ensuring that no other streams can write to the underlying
  7592. * sink.
  7593. *
  7594. * @category Streams
  7595. */
  7596. declare interface WritableStreamDefaultWriter<W = any> {
  7597. readonly closed: Promise<void>;
  7598. readonly desiredSize: number | null;
  7599. readonly ready: Promise<void>;
  7600. abort(reason?: any): Promise<void>;
  7601. close(): Promise<void>;
  7602. releaseLock(): void;
  7603. write(chunk: W): Promise<void>;
  7604. }
  7605. /** @category Streams */
  7606. declare var WritableStreamDefaultWriter: {
  7607. readonly prototype: WritableStreamDefaultWriter;
  7608. new <W>(stream: WritableStream<W>): WritableStreamDefaultWriter<W>;
  7609. };
  7610. /** @category Streams */
  7611. declare interface TransformStream<I = any, O = any> {
  7612. readonly readable: ReadableStream<O>;
  7613. readonly writable: WritableStream<I>;
  7614. }
  7615. /** @category Streams */
  7616. declare var TransformStream: {
  7617. readonly prototype: TransformStream;
  7618. new <I = any, O = any>(
  7619. transformer?: Transformer<I, O>,
  7620. writableStrategy?: QueuingStrategy<I>,
  7621. readableStrategy?: QueuingStrategy<O>,
  7622. ): TransformStream<I, O>;
  7623. };
  7624. /** @category Streams */
  7625. declare interface TransformStreamDefaultController<O = any> {
  7626. readonly desiredSize: number | null;
  7627. enqueue(chunk: O): void;
  7628. error(reason?: any): void;
  7629. terminate(): void;
  7630. }
  7631. /** @category Streams */
  7632. declare var TransformStreamDefaultController: {
  7633. readonly prototype: TransformStreamDefaultController;
  7634. new (): never;
  7635. };
  7636. /** @category Streams */
  7637. declare interface Transformer<I = any, O = any> {
  7638. flush?: TransformStreamDefaultControllerCallback<O>;
  7639. readableType?: undefined;
  7640. start?: TransformStreamDefaultControllerCallback<O>;
  7641. transform?: TransformStreamDefaultControllerTransformCallback<I, O>;
  7642. cancel?: (reason: any) => Promise<void>;
  7643. writableType?: undefined;
  7644. }
  7645. /** @category Streams */
  7646. declare interface TransformStreamDefaultControllerCallback<O> {
  7647. (controller: TransformStreamDefaultController<O>): void | PromiseLike<void>;
  7648. }
  7649. /** @category Streams */
  7650. declare interface TransformStreamDefaultControllerTransformCallback<I, O> {
  7651. (
  7652. chunk: I,
  7653. controller: TransformStreamDefaultController<O>,
  7654. ): void | PromiseLike<void>;
  7655. }
  7656. /** @category Events */
  7657. declare interface MessageEventInit<T = any> extends EventInit {
  7658. data?: T;
  7659. origin?: string;
  7660. lastEventId?: string;
  7661. }
  7662. /** @category Events */
  7663. declare interface MessageEvent<T = any> extends Event {
  7664. /**
  7665. * Returns the data of the message.
  7666. */
  7667. readonly data: T;
  7668. /**
  7669. * Returns the origin of the message, for server-sent events.
  7670. */
  7671. readonly origin: string;
  7672. /**
  7673. * Returns the last event ID string, for server-sent events.
  7674. */
  7675. readonly lastEventId: string;
  7676. readonly source: null;
  7677. /**
  7678. * Returns transferred ports.
  7679. */
  7680. readonly ports: ReadonlyArray<MessagePort>;
  7681. }
  7682. /** @category Events */
  7683. declare var MessageEvent: {
  7684. readonly prototype: MessageEvent;
  7685. new <T>(type: string, eventInitDict?: MessageEventInit<T>): MessageEvent<T>;
  7686. };
  7687. /** @category Events */
  7688. declare type Transferable = ArrayBuffer | MessagePort;
  7689. /**
  7690. * This type has been renamed to StructuredSerializeOptions. Use that type for
  7691. * new code.
  7692. *
  7693. * @deprecated use `StructuredSerializeOptions` instead.
  7694. * @category Events
  7695. */
  7696. declare type PostMessageOptions = StructuredSerializeOptions;
  7697. /** @category Platform */
  7698. declare interface StructuredSerializeOptions {
  7699. transfer?: Transferable[];
  7700. }
  7701. /** The MessageChannel interface of the Channel Messaging API allows us to
  7702. * create a new message channel and send data through it via its two MessagePort
  7703. * properties.
  7704. *
  7705. * @category Messaging
  7706. */
  7707. declare interface MessageChannel {
  7708. readonly port1: MessagePort;
  7709. readonly port2: MessagePort;
  7710. }
  7711. /** The MessageChannel interface of the Channel Messaging API allows us to
  7712. * create a new message channel and send data through it via its two MessagePort
  7713. * properties.
  7714. *
  7715. * @category Messaging
  7716. */
  7717. declare var MessageChannel: {
  7718. readonly prototype: MessageChannel;
  7719. new (): MessageChannel;
  7720. };
  7721. /** @category Messaging */
  7722. declare interface MessagePortEventMap {
  7723. "message": MessageEvent;
  7724. "messageerror": MessageEvent;
  7725. }
  7726. /** The MessagePort interface of the Channel Messaging API represents one of the
  7727. * two ports of a MessageChannel, allowing messages to be sent from one port and
  7728. * listening out for them arriving at the other.
  7729. *
  7730. * @category Messaging
  7731. */
  7732. declare interface MessagePort extends EventTarget {
  7733. onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null;
  7734. onmessageerror: ((this: MessagePort, ev: MessageEvent) => any) | null;
  7735. /**
  7736. * Disconnects the port, so that it is no longer active.
  7737. */
  7738. close(): void;
  7739. /**
  7740. * Posts a message through the channel. Objects listed in transfer are
  7741. * transferred, not just cloned, meaning that they are no longer usable on the
  7742. * sending side.
  7743. *
  7744. * Throws a "DataCloneError" DOMException if transfer contains duplicate
  7745. * objects or port, or if message could not be cloned.
  7746. */
  7747. postMessage(message: any, transfer: Transferable[]): void;
  7748. postMessage(message: any, options?: StructuredSerializeOptions): void;
  7749. /**
  7750. * Begins dispatching messages received on the port. This is implicitly called
  7751. * when assigning a value to `this.onmessage`.
  7752. */
  7753. start(): void;
  7754. addEventListener<K extends keyof MessagePortEventMap>(
  7755. type: K,
  7756. listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any,
  7757. options?: boolean | AddEventListenerOptions,
  7758. ): void;
  7759. addEventListener(
  7760. type: string,
  7761. listener: EventListenerOrEventListenerObject,
  7762. options?: boolean | AddEventListenerOptions,
  7763. ): void;
  7764. removeEventListener<K extends keyof MessagePortEventMap>(
  7765. type: K,
  7766. listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any,
  7767. options?: boolean | EventListenerOptions,
  7768. ): void;
  7769. removeEventListener(
  7770. type: string,
  7771. listener: EventListenerOrEventListenerObject,
  7772. options?: boolean | EventListenerOptions,
  7773. ): void;
  7774. }
  7775. /** The MessagePort interface of the Channel Messaging API represents one of the
  7776. * two ports of a MessageChannel, allowing messages to be sent from one port and
  7777. * listening out for them arriving at the other.
  7778. *
  7779. * @category Messaging
  7780. */
  7781. declare var MessagePort: {
  7782. readonly prototype: MessagePort;
  7783. new (): never;
  7784. };
  7785. /**
  7786. * Creates a deep copy of a given value using the structured clone algorithm.
  7787. *
  7788. * Unlike a shallow copy, a deep copy does not hold the same references as the
  7789. * source object, meaning its properties can be changed without affecting the
  7790. * source. For more details, see
  7791. * [MDN](https://developer.mozilla.org/en-US/docs/Glossary/Deep_copy).
  7792. *
  7793. * Throws a `DataCloneError` if any part of the input value is not
  7794. * serializable.
  7795. *
  7796. * @example
  7797. * ```ts
  7798. * const object = { x: 0, y: 1 };
  7799. *
  7800. * const deepCopy = structuredClone(object);
  7801. * deepCopy.x = 1;
  7802. * console.log(deepCopy.x, object.x); // 1 0
  7803. *
  7804. * const shallowCopy = object;
  7805. * shallowCopy.x = 1;
  7806. * // shallowCopy.x is pointing to the same location in memory as object.x
  7807. * console.log(shallowCopy.x, object.x); // 1 1
  7808. * ```
  7809. *
  7810. * @category Platform
  7811. */
  7812. declare function structuredClone<T = any>(
  7813. value: T,
  7814. options?: StructuredSerializeOptions,
  7815. ): T;
  7816. /**
  7817. * An API for compressing a stream of data.
  7818. *
  7819. * @example
  7820. * ```ts
  7821. * await Deno.stdin.readable
  7822. * .pipeThrough(new CompressionStream("gzip"))
  7823. * .pipeTo(Deno.stdout.writable);
  7824. * ```
  7825. *
  7826. * @category Streams
  7827. */
  7828. declare interface CompressionStream {
  7829. readonly readable: ReadableStream<Uint8Array>;
  7830. readonly writable: WritableStream<Uint8Array>;
  7831. }
  7832. /**
  7833. * An API for compressing a stream of data.
  7834. *
  7835. * @example
  7836. * ```ts
  7837. * await Deno.stdin.readable
  7838. * .pipeThrough(new CompressionStream("gzip"))
  7839. * .pipeTo(Deno.stdout.writable);
  7840. * ```
  7841. *
  7842. * @category Streams
  7843. */
  7844. declare var CompressionStream: {
  7845. readonly prototype: CompressionStream;
  7846. /**
  7847. * Creates a new `CompressionStream` object which compresses a stream of
  7848. * data.
  7849. *
  7850. * Throws a `TypeError` if the format passed to the constructor is not
  7851. * supported.
  7852. */
  7853. new (format: string): CompressionStream;
  7854. };
  7855. /**
  7856. * An API for decompressing a stream of data.
  7857. *
  7858. * @example
  7859. * ```ts
  7860. * const input = await Deno.open("./file.txt.gz");
  7861. * const output = await Deno.create("./file.txt");
  7862. *
  7863. * await input.readable
  7864. * .pipeThrough(new DecompressionStream("gzip"))
  7865. * .pipeTo(output.writable);
  7866. * ```
  7867. *
  7868. * @category Streams
  7869. */
  7870. declare interface DecompressionStream {
  7871. readonly readable: ReadableStream<Uint8Array>;
  7872. readonly writable: WritableStream<Uint8Array>;
  7873. }
  7874. /**
  7875. * An API for decompressing a stream of data.
  7876. *
  7877. * @example
  7878. * ```ts
  7879. * const input = await Deno.open("./file.txt.gz");
  7880. * const output = await Deno.create("./file.txt");
  7881. *
  7882. * await input.readable
  7883. * .pipeThrough(new DecompressionStream("gzip"))
  7884. * .pipeTo(output.writable);
  7885. * ```
  7886. *
  7887. * @category Streams
  7888. */
  7889. declare var DecompressionStream: {
  7890. readonly prototype: DecompressionStream;
  7891. /**
  7892. * Creates a new `DecompressionStream` object which decompresses a stream of
  7893. * data.
  7894. *
  7895. * Throws a `TypeError` if the format passed to the constructor is not
  7896. * supported.
  7897. */
  7898. new (format: string): DecompressionStream;
  7899. };
  7900. /** Dispatch an uncaught exception. Similar to a synchronous version of:
  7901. * ```ts
  7902. * setTimeout(() => { throw error; }, 0);
  7903. * ```
  7904. * The error can not be caught with a `try/catch` block. An error event will
  7905. * be dispatched to the global scope. You can prevent the error from being
  7906. * reported to the console with `Event.prototype.preventDefault()`:
  7907. * ```ts
  7908. * addEventListener("error", (event) => {
  7909. * event.preventDefault();
  7910. * });
  7911. * reportError(new Error("foo")); // Will not be reported.
  7912. * ```
  7913. * In Deno, this error will terminate the process if not intercepted like above.
  7914. *
  7915. * @category Platform
  7916. */
  7917. declare function reportError(
  7918. error: any,
  7919. ): void;
  7920. /** @category Platform */
  7921. declare type PredefinedColorSpace = "srgb" | "display-p3";
  7922. /** @category Platform */
  7923. declare interface ImageDataSettings {
  7924. readonly colorSpace?: PredefinedColorSpace;
  7925. }
  7926. /** @category Platform */
  7927. declare interface ImageData {
  7928. readonly colorSpace: PredefinedColorSpace;
  7929. readonly data: Uint8ClampedArray;
  7930. readonly height: number;
  7931. readonly width: number;
  7932. }
  7933. /** @category Platform */
  7934. declare var ImageData: {
  7935. prototype: ImageData;
  7936. new (sw: number, sh: number, settings?: ImageDataSettings): ImageData;
  7937. new (
  7938. data: Uint8ClampedArray,
  7939. sw: number,
  7940. sh?: number,
  7941. settings?: ImageDataSettings,
  7942. ): ImageData;
  7943. };
  7944. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  7945. // deno-lint-ignore-file no-explicit-any no-var
  7946. /// <reference no-default-lib="true" />
  7947. /// <reference lib="esnext" />
  7948. /** @category Platform */
  7949. declare interface DomIterable<K, V> {
  7950. keys(): IterableIterator<K>;
  7951. values(): IterableIterator<V>;
  7952. entries(): IterableIterator<[K, V]>;
  7953. [Symbol.iterator](): IterableIterator<[K, V]>;
  7954. forEach(
  7955. callback: (value: V, key: K, parent: this) => void,
  7956. thisArg?: any,
  7957. ): void;
  7958. }
  7959. /** @category Fetch */
  7960. declare type FormDataEntryValue = File | string;
  7961. /** Provides a way to easily construct a set of key/value pairs representing
  7962. * form fields and their values, which can then be easily sent using the
  7963. * XMLHttpRequest.send() method. It uses the same format a form would use if the
  7964. * encoding type were set to "multipart/form-data".
  7965. *
  7966. * @category Fetch
  7967. */
  7968. declare interface FormData extends DomIterable<string, FormDataEntryValue> {
  7969. append(name: string, value: string | Blob, fileName?: string): void;
  7970. delete(name: string): void;
  7971. get(name: string): FormDataEntryValue | null;
  7972. getAll(name: string): FormDataEntryValue[];
  7973. has(name: string): boolean;
  7974. set(name: string, value: string | Blob, fileName?: string): void;
  7975. }
  7976. /** @category Fetch */
  7977. declare var FormData: {
  7978. readonly prototype: FormData;
  7979. new (): FormData;
  7980. };
  7981. /** @category Fetch */
  7982. declare interface Body {
  7983. /** A simple getter used to expose a `ReadableStream` of the body contents. */
  7984. readonly body: ReadableStream<Uint8Array> | null;
  7985. /** Stores a `Boolean` that declares whether the body has been used in a
  7986. * response yet.
  7987. */
  7988. readonly bodyUsed: boolean;
  7989. /** Takes a `Response` stream and reads it to completion. It returns a promise
  7990. * that resolves with an `ArrayBuffer`.
  7991. */
  7992. arrayBuffer(): Promise<ArrayBuffer>;
  7993. /** Takes a `Response` stream and reads it to completion. It returns a promise
  7994. * that resolves with a `Blob`.
  7995. */
  7996. blob(): Promise<Blob>;
  7997. /** Takes a `Response` stream and reads it to completion. It returns a promise
  7998. * that resolves with a `Uint8Array`.
  7999. */
  8000. bytes(): Promise<Uint8Array>;
  8001. /** Takes a `Response` stream and reads it to completion. It returns a promise
  8002. * that resolves with a `FormData` object.
  8003. */
  8004. formData(): Promise<FormData>;
  8005. /** Takes a `Response` stream and reads it to completion. It returns a promise
  8006. * that resolves with the result of parsing the body text as JSON.
  8007. */
  8008. json(): Promise<any>;
  8009. /** Takes a `Response` stream and reads it to completion. It returns a promise
  8010. * that resolves with a `USVString` (text).
  8011. */
  8012. text(): Promise<string>;
  8013. }
  8014. /** @category Fetch */
  8015. declare type HeadersInit = Iterable<string[]> | Record<string, string>;
  8016. /** This Fetch API interface allows you to perform various actions on HTTP
  8017. * request and response headers. These actions include retrieving, setting,
  8018. * adding to, and removing. A Headers object has an associated header list,
  8019. * which is initially empty and consists of zero or more name and value pairs.
  8020. * You can add to this using methods like append() (see Examples). In all
  8021. * methods of this interface, header names are matched by case-insensitive byte
  8022. * sequence.
  8023. *
  8024. * @category Fetch
  8025. */
  8026. declare interface Headers extends DomIterable<string, string> {
  8027. /** Appends a new value onto an existing header inside a `Headers` object, or
  8028. * adds the header if it does not already exist.
  8029. */
  8030. append(name: string, value: string): void;
  8031. /** Deletes a header from a `Headers` object. */
  8032. delete(name: string): void;
  8033. /** Returns a `ByteString` sequence of all the values of a header within a
  8034. * `Headers` object with a given name.
  8035. */
  8036. get(name: string): string | null;
  8037. /** Returns a boolean stating whether a `Headers` object contains a certain
  8038. * header.
  8039. */
  8040. has(name: string): boolean;
  8041. /** Sets a new value for an existing header inside a Headers object, or adds
  8042. * the header if it does not already exist.
  8043. */
  8044. set(name: string, value: string): void;
  8045. /** Returns an array containing the values of all `Set-Cookie` headers
  8046. * associated with a response.
  8047. */
  8048. getSetCookie(): string[];
  8049. }
  8050. /** This Fetch API interface allows you to perform various actions on HTTP
  8051. * request and response headers. These actions include retrieving, setting,
  8052. * adding to, and removing. A Headers object has an associated header list,
  8053. * which is initially empty and consists of zero or more name and value pairs.
  8054. * You can add to this using methods like append() (see Examples). In all
  8055. * methods of this interface, header names are matched by case-insensitive byte
  8056. * sequence.
  8057. *
  8058. * @category Fetch
  8059. */
  8060. declare var Headers: {
  8061. readonly prototype: Headers;
  8062. new (init?: HeadersInit): Headers;
  8063. };
  8064. /** @category Fetch */
  8065. declare type RequestInfo = Request | string;
  8066. /** @category Fetch */
  8067. declare type RequestCache =
  8068. | "default"
  8069. | "force-cache"
  8070. | "no-cache"
  8071. | "no-store"
  8072. | "only-if-cached"
  8073. | "reload";
  8074. /** @category Fetch */
  8075. declare type RequestCredentials = "include" | "omit" | "same-origin";
  8076. /** @category Fetch */
  8077. declare type RequestMode = "cors" | "navigate" | "no-cors" | "same-origin";
  8078. /** @category Fetch */
  8079. declare type RequestRedirect = "error" | "follow" | "manual";
  8080. /** @category Fetch */
  8081. declare type ReferrerPolicy =
  8082. | ""
  8083. | "no-referrer"
  8084. | "no-referrer-when-downgrade"
  8085. | "origin"
  8086. | "origin-when-cross-origin"
  8087. | "same-origin"
  8088. | "strict-origin"
  8089. | "strict-origin-when-cross-origin"
  8090. | "unsafe-url";
  8091. /** @category Fetch */
  8092. declare type BodyInit =
  8093. | Blob
  8094. | BufferSource
  8095. | FormData
  8096. | URLSearchParams
  8097. | ReadableStream<Uint8Array>
  8098. | string;
  8099. /** @category Fetch */
  8100. declare type RequestDestination =
  8101. | ""
  8102. | "audio"
  8103. | "audioworklet"
  8104. | "document"
  8105. | "embed"
  8106. | "font"
  8107. | "image"
  8108. | "manifest"
  8109. | "object"
  8110. | "paintworklet"
  8111. | "report"
  8112. | "script"
  8113. | "sharedworker"
  8114. | "style"
  8115. | "track"
  8116. | "video"
  8117. | "worker"
  8118. | "xslt";
  8119. /** @category Fetch */
  8120. declare interface RequestInit {
  8121. /**
  8122. * A BodyInit object or null to set request's body.
  8123. */
  8124. body?: BodyInit | null;
  8125. /**
  8126. * A string indicating how the request will interact with the browser's cache
  8127. * to set request's cache.
  8128. */
  8129. cache?: RequestCache;
  8130. /**
  8131. * A string indicating whether credentials will be sent with the request
  8132. * always, never, or only when sent to a same-origin URL. Sets request's
  8133. * credentials.
  8134. */
  8135. credentials?: RequestCredentials;
  8136. /**
  8137. * A Headers object, an object literal, or an array of two-item arrays to set
  8138. * request's headers.
  8139. */
  8140. headers?: HeadersInit;
  8141. /**
  8142. * A cryptographic hash of the resource to be fetched by request. Sets
  8143. * request's integrity.
  8144. */
  8145. integrity?: string;
  8146. /**
  8147. * A boolean to set request's keepalive.
  8148. */
  8149. keepalive?: boolean;
  8150. /**
  8151. * A string to set request's method.
  8152. */
  8153. method?: string;
  8154. /**
  8155. * A string to indicate whether the request will use CORS, or will be
  8156. * restricted to same-origin URLs. Sets request's mode.
  8157. */
  8158. mode?: RequestMode;
  8159. /**
  8160. * A string indicating whether request follows redirects, results in an error
  8161. * upon encountering a redirect, or returns the redirect (in an opaque
  8162. * fashion). Sets request's redirect.
  8163. */
  8164. redirect?: RequestRedirect;
  8165. /**
  8166. * A string whose value is a same-origin URL, "about:client", or the empty
  8167. * string, to set request's referrer.
  8168. */
  8169. referrer?: string;
  8170. /**
  8171. * A referrer policy to set request's referrerPolicy.
  8172. */
  8173. referrerPolicy?: ReferrerPolicy;
  8174. /**
  8175. * An AbortSignal to set request's signal.
  8176. */
  8177. signal?: AbortSignal | null;
  8178. /**
  8179. * Can only be null. Used to disassociate request from any Window.
  8180. */
  8181. window?: any;
  8182. }
  8183. /** This Fetch API interface represents a resource request.
  8184. *
  8185. * @category Fetch
  8186. */
  8187. declare interface Request extends Body {
  8188. /**
  8189. * Returns the cache mode associated with request, which is a string
  8190. * indicating how the request will interact with the browser's cache when
  8191. * fetching.
  8192. */
  8193. readonly cache: RequestCache;
  8194. /**
  8195. * Returns the credentials mode associated with request, which is a string
  8196. * indicating whether credentials will be sent with the request always, never,
  8197. * or only when sent to a same-origin URL.
  8198. */
  8199. readonly credentials: RequestCredentials;
  8200. /**
  8201. * Returns the kind of resource requested by request, e.g., "document" or "script".
  8202. */
  8203. readonly destination: RequestDestination;
  8204. /**
  8205. * Returns a Headers object consisting of the headers associated with request.
  8206. * Note that headers added in the network layer by the user agent will not be
  8207. * accounted for in this object, e.g., the "Host" header.
  8208. */
  8209. readonly headers: Headers;
  8210. /**
  8211. * Returns request's subresource integrity metadata, which is a cryptographic
  8212. * hash of the resource being fetched. Its value consists of multiple hashes
  8213. * separated by whitespace. [SRI]
  8214. */
  8215. readonly integrity: string;
  8216. /**
  8217. * Returns a boolean indicating whether or not request is for a history
  8218. * navigation (a.k.a. back-forward navigation).
  8219. */
  8220. readonly isHistoryNavigation: boolean;
  8221. /**
  8222. * Returns a boolean indicating whether or not request is for a reload
  8223. * navigation.
  8224. */
  8225. readonly isReloadNavigation: boolean;
  8226. /**
  8227. * Returns a boolean indicating whether or not request can outlive the global
  8228. * in which it was created.
  8229. */
  8230. readonly keepalive: boolean;
  8231. /**
  8232. * Returns request's HTTP method, which is "GET" by default.
  8233. */
  8234. readonly method: string;
  8235. /**
  8236. * Returns the mode associated with request, which is a string indicating
  8237. * whether the request will use CORS, or will be restricted to same-origin
  8238. * URLs.
  8239. */
  8240. readonly mode: RequestMode;
  8241. /**
  8242. * Returns the redirect mode associated with request, which is a string
  8243. * indicating how redirects for the request will be handled during fetching. A
  8244. * request will follow redirects by default.
  8245. */
  8246. readonly redirect: RequestRedirect;
  8247. /**
  8248. * Returns the referrer of request. Its value can be a same-origin URL if
  8249. * explicitly set in init, the empty string to indicate no referrer, and
  8250. * "about:client" when defaulting to the global's default. This is used during
  8251. * fetching to determine the value of the `Referer` header of the request
  8252. * being made.
  8253. */
  8254. readonly referrer: string;
  8255. /**
  8256. * Returns the referrer policy associated with request. This is used during
  8257. * fetching to compute the value of the request's referrer.
  8258. */
  8259. readonly referrerPolicy: ReferrerPolicy;
  8260. /**
  8261. * Returns the signal associated with request, which is an AbortSignal object
  8262. * indicating whether or not request has been aborted, and its abort event
  8263. * handler.
  8264. */
  8265. readonly signal: AbortSignal;
  8266. /**
  8267. * Returns the URL of request as a string.
  8268. */
  8269. readonly url: string;
  8270. clone(): Request;
  8271. }
  8272. /** This Fetch API interface represents a resource request.
  8273. *
  8274. * @category Fetch
  8275. */
  8276. declare var Request: {
  8277. readonly prototype: Request;
  8278. new (input: RequestInfo | URL, init?: RequestInit): Request;
  8279. };
  8280. /** @category Fetch */
  8281. declare interface ResponseInit {
  8282. headers?: HeadersInit;
  8283. status?: number;
  8284. statusText?: string;
  8285. }
  8286. /** @category Fetch */
  8287. declare type ResponseType =
  8288. | "basic"
  8289. | "cors"
  8290. | "default"
  8291. | "error"
  8292. | "opaque"
  8293. | "opaqueredirect";
  8294. /** This Fetch API interface represents the response to a request.
  8295. *
  8296. * @category Fetch
  8297. */
  8298. declare interface Response extends Body {
  8299. readonly headers: Headers;
  8300. readonly ok: boolean;
  8301. readonly redirected: boolean;
  8302. readonly status: number;
  8303. readonly statusText: string;
  8304. readonly type: ResponseType;
  8305. readonly url: string;
  8306. clone(): Response;
  8307. }
  8308. /** This Fetch API interface represents the response to a request.
  8309. *
  8310. * @category Fetch
  8311. */
  8312. declare var Response: {
  8313. readonly prototype: Response;
  8314. new (body?: BodyInit | null, init?: ResponseInit): Response;
  8315. json(data: unknown, init?: ResponseInit): Response;
  8316. error(): Response;
  8317. redirect(url: string | URL, status?: number): Response;
  8318. };
  8319. /** Fetch a resource from the network. It returns a `Promise` that resolves to the
  8320. * `Response` to that `Request`, whether it is successful or not.
  8321. *
  8322. * ```ts
  8323. * const response = await fetch("http://my.json.host/data.json");
  8324. * console.log(response.status); // e.g. 200
  8325. * console.log(response.statusText); // e.g. "OK"
  8326. * const jsonData = await response.json();
  8327. * ```
  8328. *
  8329. * @tags allow-net, allow-read
  8330. * @category Fetch
  8331. */
  8332. declare function fetch(
  8333. input: URL | Request | string,
  8334. init?: RequestInit,
  8335. ): Promise<Response>;
  8336. /**
  8337. * @category Fetch
  8338. */
  8339. declare interface EventSourceInit {
  8340. withCredentials?: boolean;
  8341. }
  8342. /**
  8343. * @category Fetch
  8344. */
  8345. declare interface EventSourceEventMap {
  8346. "error": Event;
  8347. "message": MessageEvent;
  8348. "open": Event;
  8349. }
  8350. /**
  8351. * @category Fetch
  8352. */
  8353. declare interface EventSource extends EventTarget {
  8354. onerror: ((this: EventSource, ev: Event) => any) | null;
  8355. onmessage: ((this: EventSource, ev: MessageEvent) => any) | null;
  8356. onopen: ((this: EventSource, ev: Event) => any) | null;
  8357. /**
  8358. * Returns the state of this EventSource object's connection. It can have the values described below.
  8359. */
  8360. readonly readyState: number;
  8361. /**
  8362. * Returns the URL providing the event stream.
  8363. */
  8364. readonly url: string;
  8365. /**
  8366. * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
  8367. */
  8368. readonly withCredentials: boolean;
  8369. /**
  8370. * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
  8371. */
  8372. close(): void;
  8373. readonly CONNECTING: 0;
  8374. readonly OPEN: 1;
  8375. readonly CLOSED: 2;
  8376. addEventListener<K extends keyof EventSourceEventMap>(
  8377. type: K,
  8378. listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,
  8379. options?: boolean | AddEventListenerOptions,
  8380. ): void;
  8381. addEventListener(
  8382. type: string,
  8383. listener: (this: EventSource, event: MessageEvent) => any,
  8384. options?: boolean | AddEventListenerOptions,
  8385. ): void;
  8386. addEventListener(
  8387. type: string,
  8388. listener: EventListenerOrEventListenerObject,
  8389. options?: boolean | AddEventListenerOptions,
  8390. ): void;
  8391. removeEventListener<K extends keyof EventSourceEventMap>(
  8392. type: K,
  8393. listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,
  8394. options?: boolean | EventListenerOptions,
  8395. ): void;
  8396. removeEventListener(
  8397. type: string,
  8398. listener: (this: EventSource, event: MessageEvent) => any,
  8399. options?: boolean | EventListenerOptions,
  8400. ): void;
  8401. removeEventListener(
  8402. type: string,
  8403. listener: EventListenerOrEventListenerObject,
  8404. options?: boolean | EventListenerOptions,
  8405. ): void;
  8406. }
  8407. /**
  8408. * @category Fetch
  8409. */
  8410. declare var EventSource: {
  8411. prototype: EventSource;
  8412. new (url: string | URL, eventSourceInitDict?: EventSourceInit): EventSource;
  8413. readonly CONNECTING: 0;
  8414. readonly OPEN: 1;
  8415. readonly CLOSED: 2;
  8416. };
  8417. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  8418. // deno-lint-ignore-file no-explicit-any no-empty-interface
  8419. /// <reference no-default-lib="true" />
  8420. /// <reference lib="esnext" />
  8421. /**
  8422. * @category GPU
  8423. * @experimental
  8424. */
  8425. declare interface GPUObjectBase {
  8426. label: string;
  8427. }
  8428. /**
  8429. * @category GPU
  8430. * @experimental
  8431. */
  8432. declare interface GPUObjectDescriptorBase {
  8433. label?: string;
  8434. }
  8435. /**
  8436. * @category GPU
  8437. * @experimental
  8438. */
  8439. declare class GPUSupportedLimits {
  8440. maxTextureDimension1D?: number;
  8441. maxTextureDimension2D?: number;
  8442. maxTextureDimension3D?: number;
  8443. maxTextureArrayLayers?: number;
  8444. maxBindGroups?: number;
  8445. maxBindingsPerBindGroup?: number;
  8446. maxDynamicUniformBuffersPerPipelineLayout?: number;
  8447. maxDynamicStorageBuffersPerPipelineLayout?: number;
  8448. maxSampledTexturesPerShaderStage?: number;
  8449. maxSamplersPerShaderStage?: number;
  8450. maxStorageBuffersPerShaderStage?: number;
  8451. maxStorageTexturesPerShaderStage?: number;
  8452. maxUniformBuffersPerShaderStage?: number;
  8453. maxUniformBufferBindingSize?: number;
  8454. maxStorageBufferBindingSize?: number;
  8455. minUniformBufferOffsetAlignment?: number;
  8456. minStorageBufferOffsetAlignment?: number;
  8457. maxVertexBuffers?: number;
  8458. maxBufferSize?: number;
  8459. maxVertexAttributes?: number;
  8460. maxVertexBufferArrayStride?: number;
  8461. maxInterStageShaderComponents?: number;
  8462. maxColorAttachments?: number;
  8463. maxColorAttachmentBytesPerSample?: number;
  8464. maxComputeWorkgroupStorageSize?: number;
  8465. maxComputeInvocationsPerWorkgroup?: number;
  8466. maxComputeWorkgroupSizeX?: number;
  8467. maxComputeWorkgroupSizeY?: number;
  8468. maxComputeWorkgroupSizeZ?: number;
  8469. maxComputeWorkgroupsPerDimension?: number;
  8470. }
  8471. /**
  8472. * @category GPU
  8473. * @experimental
  8474. */
  8475. declare class GPUSupportedFeatures {
  8476. forEach(
  8477. callbackfn: (
  8478. value: GPUFeatureName,
  8479. value2: GPUFeatureName,
  8480. set: Set<GPUFeatureName>,
  8481. ) => void,
  8482. thisArg?: any,
  8483. ): void;
  8484. has(value: GPUFeatureName): boolean;
  8485. size: number;
  8486. [Symbol.iterator](): IterableIterator<GPUFeatureName>;
  8487. entries(): IterableIterator<[GPUFeatureName, GPUFeatureName]>;
  8488. keys(): IterableIterator<GPUFeatureName>;
  8489. values(): IterableIterator<GPUFeatureName>;
  8490. }
  8491. /**
  8492. * @category GPU
  8493. * @experimental
  8494. */
  8495. declare class GPUAdapterInfo {
  8496. readonly vendor: string;
  8497. readonly architecture: string;
  8498. readonly device: string;
  8499. readonly description: string;
  8500. }
  8501. /**
  8502. * @category GPU
  8503. * @experimental
  8504. */
  8505. declare class GPU {
  8506. requestAdapter(
  8507. options?: GPURequestAdapterOptions,
  8508. ): Promise<GPUAdapter | null>;
  8509. getPreferredCanvasFormat(): GPUTextureFormat;
  8510. }
  8511. /**
  8512. * @category GPU
  8513. * @experimental
  8514. */
  8515. declare interface GPURequestAdapterOptions {
  8516. powerPreference?: GPUPowerPreference;
  8517. forceFallbackAdapter?: boolean;
  8518. }
  8519. /**
  8520. * @category GPU
  8521. * @experimental
  8522. */
  8523. declare type GPUPowerPreference = "low-power" | "high-performance";
  8524. /**
  8525. * @category GPU
  8526. * @experimental
  8527. */
  8528. declare class GPUAdapter {
  8529. readonly features: GPUSupportedFeatures;
  8530. readonly limits: GPUSupportedLimits;
  8531. readonly isFallbackAdapter: boolean;
  8532. requestDevice(descriptor?: GPUDeviceDescriptor): Promise<GPUDevice>;
  8533. requestAdapterInfo(): Promise<GPUAdapterInfo>;
  8534. }
  8535. /**
  8536. * @category GPU
  8537. * @experimental
  8538. */
  8539. declare interface GPUDeviceDescriptor extends GPUObjectDescriptorBase {
  8540. requiredFeatures?: GPUFeatureName[];
  8541. requiredLimits?: Record<string, number>;
  8542. }
  8543. /**
  8544. * @category GPU
  8545. * @experimental
  8546. */
  8547. declare type GPUFeatureName =
  8548. | "depth-clip-control"
  8549. | "depth32float-stencil8"
  8550. | "pipeline-statistics-query"
  8551. | "texture-compression-bc"
  8552. | "texture-compression-etc2"
  8553. | "texture-compression-astc"
  8554. | "timestamp-query"
  8555. | "indirect-first-instance"
  8556. | "shader-f16"
  8557. | "rg11b10ufloat-renderable"
  8558. | "bgra8unorm-storage"
  8559. | "float32-filterable"
  8560. // extended from spec
  8561. | "mappable-primary-buffers"
  8562. | "sampled-texture-binding-array"
  8563. | "sampled-texture-array-dynamic-indexing"
  8564. | "sampled-texture-array-non-uniform-indexing"
  8565. | "unsized-binding-array"
  8566. | "multi-draw-indirect"
  8567. | "multi-draw-indirect-count"
  8568. | "push-constants"
  8569. | "address-mode-clamp-to-border"
  8570. | "texture-adapter-specific-format-features"
  8571. | "shader-float64"
  8572. | "vertex-attribute-64bit";
  8573. /**
  8574. * @category GPU
  8575. * @experimental
  8576. */
  8577. declare class GPUDevice extends EventTarget implements GPUObjectBase {
  8578. label: string;
  8579. readonly lost: Promise<GPUDeviceLostInfo>;
  8580. pushErrorScope(filter: GPUErrorFilter): undefined;
  8581. popErrorScope(): Promise<GPUError | null>;
  8582. readonly features: GPUSupportedFeatures;
  8583. readonly limits: GPUSupportedLimits;
  8584. readonly queue: GPUQueue;
  8585. destroy(): undefined;
  8586. createBuffer(descriptor: GPUBufferDescriptor): GPUBuffer;
  8587. createTexture(descriptor: GPUTextureDescriptor): GPUTexture;
  8588. createSampler(descriptor?: GPUSamplerDescriptor): GPUSampler;
  8589. createBindGroupLayout(
  8590. descriptor: GPUBindGroupLayoutDescriptor,
  8591. ): GPUBindGroupLayout;
  8592. createPipelineLayout(
  8593. descriptor: GPUPipelineLayoutDescriptor,
  8594. ): GPUPipelineLayout;
  8595. createBindGroup(descriptor: GPUBindGroupDescriptor): GPUBindGroup;
  8596. createShaderModule(descriptor: GPUShaderModuleDescriptor): GPUShaderModule;
  8597. createComputePipeline(
  8598. descriptor: GPUComputePipelineDescriptor,
  8599. ): GPUComputePipeline;
  8600. createRenderPipeline(
  8601. descriptor: GPURenderPipelineDescriptor,
  8602. ): GPURenderPipeline;
  8603. createComputePipelineAsync(
  8604. descriptor: GPUComputePipelineDescriptor,
  8605. ): Promise<GPUComputePipeline>;
  8606. createRenderPipelineAsync(
  8607. descriptor: GPURenderPipelineDescriptor,
  8608. ): Promise<GPURenderPipeline>;
  8609. createCommandEncoder(
  8610. descriptor?: GPUCommandEncoderDescriptor,
  8611. ): GPUCommandEncoder;
  8612. createRenderBundleEncoder(
  8613. descriptor: GPURenderBundleEncoderDescriptor,
  8614. ): GPURenderBundleEncoder;
  8615. createQuerySet(descriptor: GPUQuerySetDescriptor): GPUQuerySet;
  8616. }
  8617. /**
  8618. * @category GPU
  8619. * @experimental
  8620. */
  8621. declare class GPUBuffer implements GPUObjectBase {
  8622. label: string;
  8623. readonly size: number;
  8624. readonly usage: GPUFlagsConstant;
  8625. readonly mapState: GPUBufferMapState;
  8626. mapAsync(
  8627. mode: GPUMapModeFlags,
  8628. offset?: number,
  8629. size?: number,
  8630. ): Promise<undefined>;
  8631. getMappedRange(offset?: number, size?: number): ArrayBuffer;
  8632. unmap(): undefined;
  8633. destroy(): undefined;
  8634. }
  8635. /**
  8636. * @category GPU
  8637. * @experimental
  8638. */
  8639. declare type GPUBufferMapState = "unmapped" | "pending" | "mapped";
  8640. /**
  8641. * @category GPU
  8642. * @experimental
  8643. */
  8644. declare interface GPUBufferDescriptor extends GPUObjectDescriptorBase {
  8645. size: number;
  8646. usage: GPUBufferUsageFlags;
  8647. mappedAtCreation?: boolean;
  8648. }
  8649. /**
  8650. * @category GPU
  8651. * @experimental
  8652. */
  8653. declare type GPUBufferUsageFlags = number;
  8654. /**
  8655. * @category GPU
  8656. * @experimental
  8657. */
  8658. declare type GPUFlagsConstant = number;
  8659. /**
  8660. * @category GPU
  8661. * @experimental
  8662. */
  8663. declare class GPUBufferUsage {
  8664. static MAP_READ: 0x0001;
  8665. static MAP_WRITE: 0x0002;
  8666. static COPY_SRC: 0x0004;
  8667. static COPY_DST: 0x0008;
  8668. static INDEX: 0x0010;
  8669. static VERTEX: 0x0020;
  8670. static UNIFORM: 0x0040;
  8671. static STORAGE: 0x0080;
  8672. static INDIRECT: 0x0100;
  8673. static QUERY_RESOLVE: 0x0200;
  8674. }
  8675. /**
  8676. * @category GPU
  8677. * @experimental
  8678. */
  8679. declare type GPUMapModeFlags = number;
  8680. /**
  8681. * @category GPU
  8682. * @experimental
  8683. */
  8684. declare class GPUMapMode {
  8685. static READ: 0x0001;
  8686. static WRITE: 0x0002;
  8687. }
  8688. /**
  8689. * @category GPU
  8690. * @experimental
  8691. */
  8692. declare class GPUTexture implements GPUObjectBase {
  8693. label: string;
  8694. createView(descriptor?: GPUTextureViewDescriptor): GPUTextureView;
  8695. destroy(): undefined;
  8696. readonly width: number;
  8697. readonly height: number;
  8698. readonly depthOrArrayLayers: number;
  8699. readonly mipLevelCount: number;
  8700. readonly sampleCount: number;
  8701. readonly dimension: GPUTextureDimension;
  8702. readonly format: GPUTextureFormat;
  8703. readonly usage: GPUFlagsConstant;
  8704. }
  8705. /**
  8706. * @category GPU
  8707. * @experimental
  8708. */
  8709. declare interface GPUTextureDescriptor extends GPUObjectDescriptorBase {
  8710. size: GPUExtent3D;
  8711. mipLevelCount?: number;
  8712. sampleCount?: number;
  8713. dimension?: GPUTextureDimension;
  8714. format: GPUTextureFormat;
  8715. usage: GPUTextureUsageFlags;
  8716. viewFormats?: GPUTextureFormat[];
  8717. }
  8718. /**
  8719. * @category GPU
  8720. * @experimental
  8721. */
  8722. declare type GPUTextureDimension = "1d" | "2d" | "3d";
  8723. /**
  8724. * @category GPU
  8725. * @experimental
  8726. */
  8727. declare type GPUTextureUsageFlags = number;
  8728. /**
  8729. * @category GPU
  8730. * @experimental
  8731. */
  8732. declare class GPUTextureUsage {
  8733. static COPY_SRC: 0x01;
  8734. static COPY_DST: 0x02;
  8735. static TEXTURE_BINDING: 0x04;
  8736. static STORAGE_BINDING: 0x08;
  8737. static RENDER_ATTACHMENT: 0x10;
  8738. }
  8739. /**
  8740. * @category GPU
  8741. * @experimental
  8742. */
  8743. declare class GPUTextureView implements GPUObjectBase {
  8744. label: string;
  8745. }
  8746. /**
  8747. * @category GPU
  8748. * @experimental
  8749. */
  8750. declare interface GPUTextureViewDescriptor extends GPUObjectDescriptorBase {
  8751. format?: GPUTextureFormat;
  8752. dimension?: GPUTextureViewDimension;
  8753. aspect?: GPUTextureAspect;
  8754. baseMipLevel?: number;
  8755. mipLevelCount?: number;
  8756. baseArrayLayer?: number;
  8757. arrayLayerCount?: number;
  8758. }
  8759. /**
  8760. * @category GPU
  8761. * @experimental
  8762. */
  8763. declare type GPUTextureViewDimension =
  8764. | "1d"
  8765. | "2d"
  8766. | "2d-array"
  8767. | "cube"
  8768. | "cube-array"
  8769. | "3d";
  8770. /**
  8771. * @category GPU
  8772. * @experimental
  8773. */
  8774. declare type GPUTextureAspect = "all" | "stencil-only" | "depth-only";
  8775. /**
  8776. * @category GPU
  8777. * @experimental
  8778. */
  8779. declare type GPUTextureFormat =
  8780. | "r8unorm"
  8781. | "r8snorm"
  8782. | "r8uint"
  8783. | "r8sint"
  8784. | "r16uint"
  8785. | "r16sint"
  8786. | "r16float"
  8787. | "rg8unorm"
  8788. | "rg8snorm"
  8789. | "rg8uint"
  8790. | "rg8sint"
  8791. | "r32uint"
  8792. | "r32sint"
  8793. | "r32float"
  8794. | "rg16uint"
  8795. | "rg16sint"
  8796. | "rg16float"
  8797. | "rgba8unorm"
  8798. | "rgba8unorm-srgb"
  8799. | "rgba8snorm"
  8800. | "rgba8uint"
  8801. | "rgba8sint"
  8802. | "bgra8unorm"
  8803. | "bgra8unorm-srgb"
  8804. | "rgb9e5ufloat"
  8805. | "rgb10a2uint"
  8806. | "rgb10a2unorm"
  8807. | "rg11b10ufloat"
  8808. | "rg32uint"
  8809. | "rg32sint"
  8810. | "rg32float"
  8811. | "rgba16uint"
  8812. | "rgba16sint"
  8813. | "rgba16float"
  8814. | "rgba32uint"
  8815. | "rgba32sint"
  8816. | "rgba32float"
  8817. | "stencil8"
  8818. | "depth16unorm"
  8819. | "depth24plus"
  8820. | "depth24plus-stencil8"
  8821. | "depth32float"
  8822. | "depth32float-stencil8"
  8823. | "bc1-rgba-unorm"
  8824. | "bc1-rgba-unorm-srgb"
  8825. | "bc2-rgba-unorm"
  8826. | "bc2-rgba-unorm-srgb"
  8827. | "bc3-rgba-unorm"
  8828. | "bc3-rgba-unorm-srgb"
  8829. | "bc4-r-unorm"
  8830. | "bc4-r-snorm"
  8831. | "bc5-rg-unorm"
  8832. | "bc5-rg-snorm"
  8833. | "bc6h-rgb-ufloat"
  8834. | "bc6h-rgb-float"
  8835. | "bc7-rgba-unorm"
  8836. | "bc7-rgba-unorm-srgb"
  8837. | "etc2-rgb8unorm"
  8838. | "etc2-rgb8unorm-srgb"
  8839. | "etc2-rgb8a1unorm"
  8840. | "etc2-rgb8a1unorm-srgb"
  8841. | "etc2-rgba8unorm"
  8842. | "etc2-rgba8unorm-srgb"
  8843. | "eac-r11unorm"
  8844. | "eac-r11snorm"
  8845. | "eac-rg11unorm"
  8846. | "eac-rg11snorm"
  8847. | "astc-4x4-unorm"
  8848. | "astc-4x4-unorm-srgb"
  8849. | "astc-5x4-unorm"
  8850. | "astc-5x4-unorm-srgb"
  8851. | "astc-5x5-unorm"
  8852. | "astc-5x5-unorm-srgb"
  8853. | "astc-6x5-unorm"
  8854. | "astc-6x5-unorm-srgb"
  8855. | "astc-6x6-unorm"
  8856. | "astc-6x6-unorm-srgb"
  8857. | "astc-8x5-unorm"
  8858. | "astc-8x5-unorm-srgb"
  8859. | "astc-8x6-unorm"
  8860. | "astc-8x6-unorm-srgb"
  8861. | "astc-8x8-unorm"
  8862. | "astc-8x8-unorm-srgb"
  8863. | "astc-10x5-unorm"
  8864. | "astc-10x5-unorm-srgb"
  8865. | "astc-10x6-unorm"
  8866. | "astc-10x6-unorm-srgb"
  8867. | "astc-10x8-unorm"
  8868. | "astc-10x8-unorm-srgb"
  8869. | "astc-10x10-unorm"
  8870. | "astc-10x10-unorm-srgb"
  8871. | "astc-12x10-unorm"
  8872. | "astc-12x10-unorm-srgb"
  8873. | "astc-12x12-unorm"
  8874. | "astc-12x12-unorm-srgb";
  8875. /**
  8876. * @category GPU
  8877. * @experimental
  8878. */
  8879. declare class GPUSampler implements GPUObjectBase {
  8880. label: string;
  8881. }
  8882. /**
  8883. * @category GPU
  8884. * @experimental
  8885. */
  8886. declare interface GPUSamplerDescriptor extends GPUObjectDescriptorBase {
  8887. addressModeU?: GPUAddressMode;
  8888. addressModeV?: GPUAddressMode;
  8889. addressModeW?: GPUAddressMode;
  8890. magFilter?: GPUFilterMode;
  8891. minFilter?: GPUFilterMode;
  8892. mipmapFilter?: GPUMipmapFilterMode;
  8893. lodMinClamp?: number;
  8894. lodMaxClamp?: number;
  8895. compare?: GPUCompareFunction;
  8896. maxAnisotropy?: number;
  8897. }
  8898. /**
  8899. * @category GPU
  8900. * @experimental
  8901. */
  8902. declare type GPUAddressMode = "clamp-to-edge" | "repeat" | "mirror-repeat";
  8903. /**
  8904. * @category GPU
  8905. * @experimental
  8906. */
  8907. declare type GPUFilterMode = "nearest" | "linear";
  8908. /**
  8909. * @category GPU
  8910. * @experimental
  8911. */
  8912. declare type GPUMipmapFilterMode = "nearest" | "linear";
  8913. /**
  8914. * @category GPU
  8915. * @experimental
  8916. */
  8917. declare type GPUCompareFunction =
  8918. | "never"
  8919. | "less"
  8920. | "equal"
  8921. | "less-equal"
  8922. | "greater"
  8923. | "not-equal"
  8924. | "greater-equal"
  8925. | "always";
  8926. /**
  8927. * @category GPU
  8928. * @experimental
  8929. */
  8930. declare class GPUBindGroupLayout implements GPUObjectBase {
  8931. label: string;
  8932. }
  8933. /**
  8934. * @category GPU
  8935. * @experimental
  8936. */
  8937. declare interface GPUBindGroupLayoutDescriptor extends GPUObjectDescriptorBase {
  8938. entries: GPUBindGroupLayoutEntry[];
  8939. }
  8940. /**
  8941. * @category GPU
  8942. * @experimental
  8943. */
  8944. declare interface GPUBindGroupLayoutEntry {
  8945. binding: number;
  8946. visibility: GPUShaderStageFlags;
  8947. buffer?: GPUBufferBindingLayout;
  8948. sampler?: GPUSamplerBindingLayout;
  8949. texture?: GPUTextureBindingLayout;
  8950. storageTexture?: GPUStorageTextureBindingLayout;
  8951. }
  8952. /**
  8953. * @category GPU
  8954. * @experimental
  8955. */
  8956. declare type GPUShaderStageFlags = number;
  8957. /**
  8958. * @category GPU
  8959. * @experimental
  8960. */
  8961. declare class GPUShaderStage {
  8962. static VERTEX: 0x1;
  8963. static FRAGMENT: 0x2;
  8964. static COMPUTE: 0x4;
  8965. }
  8966. /**
  8967. * @category GPU
  8968. * @experimental
  8969. */
  8970. declare interface GPUBufferBindingLayout {
  8971. type?: GPUBufferBindingType;
  8972. hasDynamicOffset?: boolean;
  8973. minBindingSize?: number;
  8974. }
  8975. /**
  8976. * @category GPU
  8977. * @experimental
  8978. */
  8979. declare type GPUBufferBindingType = "uniform" | "storage" | "read-only-storage";
  8980. /**
  8981. * @category GPU
  8982. * @experimental
  8983. */
  8984. declare interface GPUSamplerBindingLayout {
  8985. type?: GPUSamplerBindingType;
  8986. }
  8987. /**
  8988. * @category GPU
  8989. * @experimental
  8990. */
  8991. declare type GPUSamplerBindingType =
  8992. | "filtering"
  8993. | "non-filtering"
  8994. | "comparison";
  8995. /**
  8996. * @category GPU
  8997. * @experimental
  8998. */
  8999. declare interface GPUTextureBindingLayout {
  9000. sampleType?: GPUTextureSampleType;
  9001. viewDimension?: GPUTextureViewDimension;
  9002. multisampled?: boolean;
  9003. }
  9004. /**
  9005. * @category GPU
  9006. * @experimental
  9007. */
  9008. declare type GPUTextureSampleType =
  9009. | "float"
  9010. | "unfilterable-float"
  9011. | "depth"
  9012. | "sint"
  9013. | "uint";
  9014. /**
  9015. * @category GPU
  9016. * @experimental
  9017. */
  9018. declare type GPUStorageTextureAccess =
  9019. | "write-only"
  9020. | "read-only"
  9021. | "read-write";
  9022. /**
  9023. * @category GPU
  9024. * @experimental
  9025. */
  9026. declare interface GPUStorageTextureBindingLayout {
  9027. access: GPUStorageTextureAccess;
  9028. format: GPUTextureFormat;
  9029. viewDimension?: GPUTextureViewDimension;
  9030. }
  9031. /**
  9032. * @category GPU
  9033. * @experimental
  9034. */
  9035. declare class GPUBindGroup implements GPUObjectBase {
  9036. label: string;
  9037. }
  9038. /**
  9039. * @category GPU
  9040. * @experimental
  9041. */
  9042. declare interface GPUBindGroupDescriptor extends GPUObjectDescriptorBase {
  9043. layout: GPUBindGroupLayout;
  9044. entries: GPUBindGroupEntry[];
  9045. }
  9046. /**
  9047. * @category GPU
  9048. * @experimental
  9049. */
  9050. declare type GPUBindingResource =
  9051. | GPUSampler
  9052. | GPUTextureView
  9053. | GPUBufferBinding;
  9054. /**
  9055. * @category GPU
  9056. * @experimental
  9057. */
  9058. declare interface GPUBindGroupEntry {
  9059. binding: number;
  9060. resource: GPUBindingResource;
  9061. }
  9062. /**
  9063. * @category GPU
  9064. * @experimental
  9065. */
  9066. declare interface GPUBufferBinding {
  9067. buffer: GPUBuffer;
  9068. offset?: number;
  9069. size?: number;
  9070. }
  9071. /**
  9072. * @category GPU
  9073. * @experimental
  9074. */
  9075. declare class GPUPipelineLayout implements GPUObjectBase {
  9076. label: string;
  9077. }
  9078. /**
  9079. * @category GPU
  9080. * @experimental
  9081. */
  9082. declare interface GPUPipelineLayoutDescriptor extends GPUObjectDescriptorBase {
  9083. bindGroupLayouts: GPUBindGroupLayout[];
  9084. }
  9085. /**
  9086. * @category GPU
  9087. * @experimental
  9088. */
  9089. declare type GPUCompilationMessageType = "error" | "warning" | "info";
  9090. /**
  9091. * @category GPU
  9092. * @experimental
  9093. */
  9094. declare interface GPUCompilationMessage {
  9095. readonly message: string;
  9096. readonly type: GPUCompilationMessageType;
  9097. readonly lineNum: number;
  9098. readonly linePos: number;
  9099. }
  9100. /**
  9101. * @category GPU
  9102. * @experimental
  9103. */
  9104. declare interface GPUCompilationInfo {
  9105. readonly messages: ReadonlyArray<GPUCompilationMessage>;
  9106. }
  9107. /**
  9108. * @category GPU
  9109. * @experimental
  9110. */
  9111. declare class GPUPipelineError extends DOMException {
  9112. constructor(message?: string, options?: GPUPipelineErrorInit);
  9113. readonly reason: GPUPipelineErrorReason;
  9114. }
  9115. /**
  9116. * @category GPU
  9117. * @experimental
  9118. */
  9119. declare interface GPUPipelineErrorInit {
  9120. reason: GPUPipelineErrorReason;
  9121. }
  9122. /**
  9123. * @category GPU
  9124. * @experimental
  9125. */
  9126. declare type GPUPipelineErrorReason = "validation" | "internal";
  9127. /**
  9128. * @category GPU
  9129. * @experimental
  9130. */
  9131. declare class GPUShaderModule implements GPUObjectBase {
  9132. label: string;
  9133. }
  9134. /**
  9135. * @category GPU
  9136. * @experimental
  9137. */
  9138. declare interface GPUShaderModuleDescriptor extends GPUObjectDescriptorBase {
  9139. code: string;
  9140. sourceMap?: any;
  9141. }
  9142. /**
  9143. * @category GPU
  9144. * @experimental
  9145. */
  9146. declare type GPUAutoLayoutMode = "auto";
  9147. /**
  9148. * @category GPU
  9149. * @experimental
  9150. */
  9151. declare interface GPUPipelineDescriptorBase extends GPUObjectDescriptorBase {
  9152. layout: GPUPipelineLayout | GPUAutoLayoutMode;
  9153. }
  9154. /**
  9155. * @category GPU
  9156. * @experimental
  9157. */
  9158. declare interface GPUPipelineBase {
  9159. getBindGroupLayout(index: number): GPUBindGroupLayout;
  9160. }
  9161. /**
  9162. * @category GPU
  9163. * @experimental
  9164. */
  9165. declare interface GPUProgrammableStage {
  9166. module: GPUShaderModule;
  9167. entryPoint?: string;
  9168. constants?: Record<string, number>;
  9169. }
  9170. /**
  9171. * @category GPU
  9172. * @experimental
  9173. */
  9174. declare class GPUComputePipeline implements GPUObjectBase, GPUPipelineBase {
  9175. label: string;
  9176. getBindGroupLayout(index: number): GPUBindGroupLayout;
  9177. }
  9178. /**
  9179. * @category GPU
  9180. * @experimental
  9181. */
  9182. declare interface GPUComputePipelineDescriptor
  9183. extends GPUPipelineDescriptorBase {
  9184. compute: GPUProgrammableStage;
  9185. }
  9186. /**
  9187. * @category GPU
  9188. * @experimental
  9189. */
  9190. declare class GPURenderPipeline implements GPUObjectBase, GPUPipelineBase {
  9191. label: string;
  9192. getBindGroupLayout(index: number): GPUBindGroupLayout;
  9193. }
  9194. /**
  9195. * @category GPU
  9196. * @experimental
  9197. */
  9198. declare interface GPURenderPipelineDescriptor
  9199. extends GPUPipelineDescriptorBase {
  9200. vertex: GPUVertexState;
  9201. primitive?: GPUPrimitiveState;
  9202. depthStencil?: GPUDepthStencilState;
  9203. multisample?: GPUMultisampleState;
  9204. fragment?: GPUFragmentState;
  9205. }
  9206. /**
  9207. * @category GPU
  9208. * @experimental
  9209. */
  9210. declare interface GPUPrimitiveState {
  9211. topology?: GPUPrimitiveTopology;
  9212. stripIndexFormat?: GPUIndexFormat;
  9213. frontFace?: GPUFrontFace;
  9214. cullMode?: GPUCullMode;
  9215. unclippedDepth?: boolean;
  9216. }
  9217. /**
  9218. * @category GPU
  9219. * @experimental
  9220. */
  9221. declare type GPUPrimitiveTopology =
  9222. | "point-list"
  9223. | "line-list"
  9224. | "line-strip"
  9225. | "triangle-list"
  9226. | "triangle-strip";
  9227. /**
  9228. * @category GPU
  9229. * @experimental
  9230. */
  9231. declare type GPUFrontFace = "ccw" | "cw";
  9232. /**
  9233. * @category GPU
  9234. * @experimental
  9235. */
  9236. declare type GPUCullMode = "none" | "front" | "back";
  9237. /**
  9238. * @category GPU
  9239. * @experimental
  9240. */
  9241. declare interface GPUMultisampleState {
  9242. count?: number;
  9243. mask?: number;
  9244. alphaToCoverageEnabled?: boolean;
  9245. }
  9246. /**
  9247. * @category GPU
  9248. * @experimental
  9249. */
  9250. declare interface GPUFragmentState extends GPUProgrammableStage {
  9251. targets: (GPUColorTargetState | null)[];
  9252. }
  9253. /**
  9254. * @category GPU
  9255. * @experimental
  9256. */
  9257. declare interface GPUColorTargetState {
  9258. format: GPUTextureFormat;
  9259. blend?: GPUBlendState;
  9260. writeMask?: GPUColorWriteFlags;
  9261. }
  9262. /**
  9263. * @category GPU
  9264. * @experimental
  9265. */
  9266. declare interface GPUBlendState {
  9267. color: GPUBlendComponent;
  9268. alpha: GPUBlendComponent;
  9269. }
  9270. /**
  9271. * @category GPU
  9272. * @experimental
  9273. */
  9274. declare type GPUColorWriteFlags = number;
  9275. /**
  9276. * @category GPU
  9277. * @experimental
  9278. */
  9279. declare class GPUColorWrite {
  9280. static RED: 0x1;
  9281. static GREEN: 0x2;
  9282. static BLUE: 0x4;
  9283. static ALPHA: 0x8;
  9284. static ALL: 0xF;
  9285. }
  9286. /**
  9287. * @category GPU
  9288. * @experimental
  9289. */
  9290. declare interface GPUBlendComponent {
  9291. operation?: GPUBlendOperation;
  9292. srcFactor?: GPUBlendFactor;
  9293. dstFactor?: GPUBlendFactor;
  9294. }
  9295. /**
  9296. * @category GPU
  9297. * @experimental
  9298. */
  9299. declare type GPUBlendFactor =
  9300. | "zero"
  9301. | "one"
  9302. | "src"
  9303. | "one-minus-src"
  9304. | "src-alpha"
  9305. | "one-minus-src-alpha"
  9306. | "dst"
  9307. | "one-minus-dst"
  9308. | "dst-alpha"
  9309. | "one-minus-dst-alpha"
  9310. | "src-alpha-saturated"
  9311. | "constant"
  9312. | "one-minus-constant";
  9313. /**
  9314. * @category GPU
  9315. * @experimental
  9316. */
  9317. declare type GPUBlendOperation =
  9318. | "add"
  9319. | "subtract"
  9320. | "reverse-subtract"
  9321. | "min"
  9322. | "max";
  9323. /**
  9324. * @category GPU
  9325. * @experimental
  9326. */
  9327. declare interface GPUDepthStencilState {
  9328. format: GPUTextureFormat;
  9329. depthWriteEnabled: boolean;
  9330. depthCompare: GPUCompareFunction;
  9331. stencilFront?: GPUStencilFaceState;
  9332. stencilBack?: GPUStencilFaceState;
  9333. stencilReadMask?: number;
  9334. stencilWriteMask?: number;
  9335. depthBias?: number;
  9336. depthBiasSlopeScale?: number;
  9337. depthBiasClamp?: number;
  9338. }
  9339. /**
  9340. * @category GPU
  9341. * @experimental
  9342. */
  9343. declare interface GPUStencilFaceState {
  9344. compare?: GPUCompareFunction;
  9345. failOp?: GPUStencilOperation;
  9346. depthFailOp?: GPUStencilOperation;
  9347. passOp?: GPUStencilOperation;
  9348. }
  9349. /**
  9350. * @category GPU
  9351. * @experimental
  9352. */
  9353. declare type GPUStencilOperation =
  9354. | "keep"
  9355. | "zero"
  9356. | "replace"
  9357. | "invert"
  9358. | "increment-clamp"
  9359. | "decrement-clamp"
  9360. | "increment-wrap"
  9361. | "decrement-wrap";
  9362. /**
  9363. * @category GPU
  9364. * @experimental
  9365. */
  9366. declare type GPUIndexFormat = "uint16" | "uint32";
  9367. /**
  9368. * @category GPU
  9369. * @experimental
  9370. */
  9371. declare type GPUVertexFormat =
  9372. | "uint8x2"
  9373. | "uint8x4"
  9374. | "sint8x2"
  9375. | "sint8x4"
  9376. | "unorm8x2"
  9377. | "unorm8x4"
  9378. | "snorm8x2"
  9379. | "snorm8x4"
  9380. | "uint16x2"
  9381. | "uint16x4"
  9382. | "sint16x2"
  9383. | "sint16x4"
  9384. | "unorm16x2"
  9385. | "unorm16x4"
  9386. | "snorm16x2"
  9387. | "snorm16x4"
  9388. | "float16x2"
  9389. | "float16x4"
  9390. | "float32"
  9391. | "float32x2"
  9392. | "float32x3"
  9393. | "float32x4"
  9394. | "uint32"
  9395. | "uint32x2"
  9396. | "uint32x3"
  9397. | "uint32x4"
  9398. | "sint32"
  9399. | "sint32x2"
  9400. | "sint32x3"
  9401. | "sint32x4"
  9402. | "unorm10-10-10-2";
  9403. /**
  9404. * @category GPU
  9405. * @experimental
  9406. */
  9407. declare type GPUVertexStepMode = "vertex" | "instance";
  9408. /**
  9409. * @category GPU
  9410. * @experimental
  9411. */
  9412. declare interface GPUVertexState extends GPUProgrammableStage {
  9413. buffers?: (GPUVertexBufferLayout | null)[];
  9414. }
  9415. /**
  9416. * @category GPU
  9417. * @experimental
  9418. */
  9419. declare interface GPUVertexBufferLayout {
  9420. arrayStride: number;
  9421. stepMode?: GPUVertexStepMode;
  9422. attributes: GPUVertexAttribute[];
  9423. }
  9424. /**
  9425. * @category GPU
  9426. * @experimental
  9427. */
  9428. declare interface GPUVertexAttribute {
  9429. format: GPUVertexFormat;
  9430. offset: number;
  9431. shaderLocation: number;
  9432. }
  9433. /**
  9434. * @category GPU
  9435. * @experimental
  9436. */
  9437. declare interface GPUImageDataLayout {
  9438. offset?: number;
  9439. bytesPerRow?: number;
  9440. rowsPerImage?: number;
  9441. }
  9442. /**
  9443. * @category GPU
  9444. * @experimental
  9445. */
  9446. declare class GPUCommandBuffer implements GPUObjectBase {
  9447. label: string;
  9448. }
  9449. /**
  9450. * @category GPU
  9451. * @experimental
  9452. */
  9453. declare interface GPUCommandBufferDescriptor extends GPUObjectDescriptorBase {}
  9454. /**
  9455. * @category GPU
  9456. * @experimental
  9457. */
  9458. declare class GPUCommandEncoder implements GPUObjectBase {
  9459. label: string;
  9460. beginRenderPass(descriptor: GPURenderPassDescriptor): GPURenderPassEncoder;
  9461. beginComputePass(
  9462. descriptor?: GPUComputePassDescriptor,
  9463. ): GPUComputePassEncoder;
  9464. copyBufferToBuffer(
  9465. source: GPUBuffer,
  9466. sourceOffset: number,
  9467. destination: GPUBuffer,
  9468. destinationOffset: number,
  9469. size: number,
  9470. ): undefined;
  9471. copyBufferToTexture(
  9472. source: GPUImageCopyBuffer,
  9473. destination: GPUImageCopyTexture,
  9474. copySize: GPUExtent3D,
  9475. ): undefined;
  9476. copyTextureToBuffer(
  9477. source: GPUImageCopyTexture,
  9478. destination: GPUImageCopyBuffer,
  9479. copySize: GPUExtent3D,
  9480. ): undefined;
  9481. copyTextureToTexture(
  9482. source: GPUImageCopyTexture,
  9483. destination: GPUImageCopyTexture,
  9484. copySize: GPUExtent3D,
  9485. ): undefined;
  9486. clearBuffer(
  9487. destination: GPUBuffer,
  9488. destinationOffset?: number,
  9489. size?: number,
  9490. ): undefined;
  9491. pushDebugGroup(groupLabel: string): undefined;
  9492. popDebugGroup(): undefined;
  9493. insertDebugMarker(markerLabel: string): undefined;
  9494. writeTimestamp(querySet: GPUQuerySet, queryIndex: number): undefined;
  9495. resolveQuerySet(
  9496. querySet: GPUQuerySet,
  9497. firstQuery: number,
  9498. queryCount: number,
  9499. destination: GPUBuffer,
  9500. destinationOffset: number,
  9501. ): undefined;
  9502. finish(descriptor?: GPUCommandBufferDescriptor): GPUCommandBuffer;
  9503. }
  9504. /**
  9505. * @category GPU
  9506. * @experimental
  9507. */
  9508. declare interface GPUCommandEncoderDescriptor extends GPUObjectDescriptorBase {}
  9509. /**
  9510. * @category GPU
  9511. * @experimental
  9512. */
  9513. declare interface GPUImageCopyBuffer extends GPUImageDataLayout {
  9514. buffer: GPUBuffer;
  9515. }
  9516. /**
  9517. * @category GPU
  9518. * @experimental
  9519. */
  9520. declare interface GPUImageCopyTexture {
  9521. texture: GPUTexture;
  9522. mipLevel?: number;
  9523. origin?: GPUOrigin3D;
  9524. aspect?: GPUTextureAspect;
  9525. }
  9526. /**
  9527. * @category GPU
  9528. * @experimental
  9529. */
  9530. declare interface GPUProgrammablePassEncoder {
  9531. setBindGroup(
  9532. index: number,
  9533. bindGroup: GPUBindGroup,
  9534. dynamicOffsets?: number[],
  9535. ): undefined;
  9536. setBindGroup(
  9537. index: number,
  9538. bindGroup: GPUBindGroup,
  9539. dynamicOffsetsData: Uint32Array,
  9540. dynamicOffsetsDataStart: number,
  9541. dynamicOffsetsDataLength: number,
  9542. ): undefined;
  9543. pushDebugGroup(groupLabel: string): undefined;
  9544. popDebugGroup(): undefined;
  9545. insertDebugMarker(markerLabel: string): undefined;
  9546. }
  9547. /**
  9548. * @category GPU
  9549. * @experimental
  9550. */
  9551. declare class GPUComputePassEncoder
  9552. implements GPUObjectBase, GPUProgrammablePassEncoder {
  9553. label: string;
  9554. setBindGroup(
  9555. index: number,
  9556. bindGroup: GPUBindGroup,
  9557. dynamicOffsets?: number[],
  9558. ): undefined;
  9559. setBindGroup(
  9560. index: number,
  9561. bindGroup: GPUBindGroup,
  9562. dynamicOffsetsData: Uint32Array,
  9563. dynamicOffsetsDataStart: number,
  9564. dynamicOffsetsDataLength: number,
  9565. ): undefined;
  9566. pushDebugGroup(groupLabel: string): undefined;
  9567. popDebugGroup(): undefined;
  9568. insertDebugMarker(markerLabel: string): undefined;
  9569. setPipeline(pipeline: GPUComputePipeline): undefined;
  9570. dispatchWorkgroups(x: number, y?: number, z?: number): undefined;
  9571. dispatchWorkgroupsIndirect(
  9572. indirectBuffer: GPUBuffer,
  9573. indirectOffset: number,
  9574. ): undefined;
  9575. end(): undefined;
  9576. }
  9577. /**
  9578. * @category GPU
  9579. * @experimental
  9580. */
  9581. declare interface GPUComputePassTimestampWrites {
  9582. querySet: GPUQuerySet;
  9583. beginningOfPassWriteIndex?: number;
  9584. endOfPassWriteIndex?: number;
  9585. }
  9586. /**
  9587. * @category GPU
  9588. * @experimental
  9589. */
  9590. declare interface GPUComputePassDescriptor extends GPUObjectDescriptorBase {
  9591. timestampWrites?: GPUComputePassTimestampWrites;
  9592. }
  9593. /**
  9594. * @category GPU
  9595. * @experimental
  9596. */
  9597. declare interface GPURenderEncoderBase {
  9598. setPipeline(pipeline: GPURenderPipeline): undefined;
  9599. setIndexBuffer(
  9600. buffer: GPUBuffer,
  9601. indexFormat: GPUIndexFormat,
  9602. offset?: number,
  9603. size?: number,
  9604. ): undefined;
  9605. setVertexBuffer(
  9606. slot: number,
  9607. buffer: GPUBuffer,
  9608. offset?: number,
  9609. size?: number,
  9610. ): undefined;
  9611. draw(
  9612. vertexCount: number,
  9613. instanceCount?: number,
  9614. firstVertex?: number,
  9615. firstInstance?: number,
  9616. ): undefined;
  9617. drawIndexed(
  9618. indexCount: number,
  9619. instanceCount?: number,
  9620. firstIndex?: number,
  9621. baseVertex?: number,
  9622. firstInstance?: number,
  9623. ): undefined;
  9624. drawIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): undefined;
  9625. drawIndexedIndirect(
  9626. indirectBuffer: GPUBuffer,
  9627. indirectOffset: number,
  9628. ): undefined;
  9629. }
  9630. /**
  9631. * @category GPU
  9632. * @experimental
  9633. */
  9634. declare class GPURenderPassEncoder
  9635. implements GPUObjectBase, GPUProgrammablePassEncoder, GPURenderEncoderBase {
  9636. label: string;
  9637. setBindGroup(
  9638. index: number,
  9639. bindGroup: GPUBindGroup,
  9640. dynamicOffsets?: number[],
  9641. ): undefined;
  9642. setBindGroup(
  9643. index: number,
  9644. bindGroup: GPUBindGroup,
  9645. dynamicOffsetsData: Uint32Array,
  9646. dynamicOffsetsDataStart: number,
  9647. dynamicOffsetsDataLength: number,
  9648. ): undefined;
  9649. pushDebugGroup(groupLabel: string): undefined;
  9650. popDebugGroup(): undefined;
  9651. insertDebugMarker(markerLabel: string): undefined;
  9652. setPipeline(pipeline: GPURenderPipeline): undefined;
  9653. setIndexBuffer(
  9654. buffer: GPUBuffer,
  9655. indexFormat: GPUIndexFormat,
  9656. offset?: number,
  9657. size?: number,
  9658. ): undefined;
  9659. setVertexBuffer(
  9660. slot: number,
  9661. buffer: GPUBuffer,
  9662. offset?: number,
  9663. size?: number,
  9664. ): undefined;
  9665. draw(
  9666. vertexCount: number,
  9667. instanceCount?: number,
  9668. firstVertex?: number,
  9669. firstInstance?: number,
  9670. ): undefined;
  9671. drawIndexed(
  9672. indexCount: number,
  9673. instanceCount?: number,
  9674. firstIndex?: number,
  9675. baseVertex?: number,
  9676. firstInstance?: number,
  9677. ): undefined;
  9678. drawIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): undefined;
  9679. drawIndexedIndirect(
  9680. indirectBuffer: GPUBuffer,
  9681. indirectOffset: number,
  9682. ): undefined;
  9683. setViewport(
  9684. x: number,
  9685. y: number,
  9686. width: number,
  9687. height: number,
  9688. minDepth: number,
  9689. maxDepth: number,
  9690. ): undefined;
  9691. setScissorRect(
  9692. x: number,
  9693. y: number,
  9694. width: number,
  9695. height: number,
  9696. ): undefined;
  9697. setBlendConstant(color: GPUColor): undefined;
  9698. setStencilReference(reference: number): undefined;
  9699. beginOcclusionQuery(queryIndex: number): undefined;
  9700. endOcclusionQuery(): undefined;
  9701. executeBundles(bundles: GPURenderBundle[]): undefined;
  9702. end(): undefined;
  9703. }
  9704. /**
  9705. * @category GPU
  9706. * @experimental
  9707. */
  9708. declare interface GPURenderPassTimestampWrites {
  9709. querySet: GPUQuerySet;
  9710. beginningOfPassWriteIndex?: number;
  9711. endOfPassWriteIndex?: number;
  9712. }
  9713. /**
  9714. * @category GPU
  9715. * @experimental
  9716. */
  9717. declare interface GPURenderPassDescriptor extends GPUObjectDescriptorBase {
  9718. colorAttachments: (GPURenderPassColorAttachment | null)[];
  9719. depthStencilAttachment?: GPURenderPassDepthStencilAttachment;
  9720. occlusionQuerySet?: GPUQuerySet;
  9721. timestampWrites?: GPURenderPassTimestampWrites;
  9722. }
  9723. /**
  9724. * @category GPU
  9725. * @experimental
  9726. */
  9727. declare interface GPURenderPassColorAttachment {
  9728. view: GPUTextureView;
  9729. resolveTarget?: GPUTextureView;
  9730. clearValue?: GPUColor;
  9731. loadOp: GPULoadOp;
  9732. storeOp: GPUStoreOp;
  9733. }
  9734. /**
  9735. * @category GPU
  9736. * @experimental
  9737. */
  9738. declare interface GPURenderPassDepthStencilAttachment {
  9739. view: GPUTextureView;
  9740. depthClearValue?: number;
  9741. depthLoadOp?: GPULoadOp;
  9742. depthStoreOp?: GPUStoreOp;
  9743. depthReadOnly?: boolean;
  9744. stencilClearValue?: number;
  9745. stencilLoadOp?: GPULoadOp;
  9746. stencilStoreOp?: GPUStoreOp;
  9747. stencilReadOnly?: boolean;
  9748. }
  9749. /**
  9750. * @category GPU
  9751. * @experimental
  9752. */
  9753. declare type GPULoadOp = "load" | "clear";
  9754. /**
  9755. * @category GPU
  9756. * @experimental
  9757. */
  9758. declare type GPUStoreOp = "store" | "discard";
  9759. /**
  9760. * @category GPU
  9761. * @experimental
  9762. */
  9763. declare class GPURenderBundle implements GPUObjectBase {
  9764. label: string;
  9765. }
  9766. /**
  9767. * @category GPU
  9768. * @experimental
  9769. */
  9770. declare interface GPURenderBundleDescriptor extends GPUObjectDescriptorBase {}
  9771. /**
  9772. * @category GPU
  9773. * @experimental
  9774. */
  9775. declare class GPURenderBundleEncoder
  9776. implements GPUObjectBase, GPUProgrammablePassEncoder, GPURenderEncoderBase {
  9777. label: string;
  9778. draw(
  9779. vertexCount: number,
  9780. instanceCount?: number,
  9781. firstVertex?: number,
  9782. firstInstance?: number,
  9783. ): undefined;
  9784. drawIndexed(
  9785. indexCount: number,
  9786. instanceCount?: number,
  9787. firstIndex?: number,
  9788. baseVertex?: number,
  9789. firstInstance?: number,
  9790. ): undefined;
  9791. drawIndexedIndirect(
  9792. indirectBuffer: GPUBuffer,
  9793. indirectOffset: number,
  9794. ): undefined;
  9795. drawIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): undefined;
  9796. insertDebugMarker(markerLabel: string): undefined;
  9797. popDebugGroup(): undefined;
  9798. pushDebugGroup(groupLabel: string): undefined;
  9799. setBindGroup(
  9800. index: number,
  9801. bindGroup: GPUBindGroup,
  9802. dynamicOffsets?: number[],
  9803. ): undefined;
  9804. setBindGroup(
  9805. index: number,
  9806. bindGroup: GPUBindGroup,
  9807. dynamicOffsetsData: Uint32Array,
  9808. dynamicOffsetsDataStart: number,
  9809. dynamicOffsetsDataLength: number,
  9810. ): undefined;
  9811. setIndexBuffer(
  9812. buffer: GPUBuffer,
  9813. indexFormat: GPUIndexFormat,
  9814. offset?: number,
  9815. size?: number,
  9816. ): undefined;
  9817. setPipeline(pipeline: GPURenderPipeline): undefined;
  9818. setVertexBuffer(
  9819. slot: number,
  9820. buffer: GPUBuffer,
  9821. offset?: number,
  9822. size?: number,
  9823. ): undefined;
  9824. finish(descriptor?: GPURenderBundleDescriptor): GPURenderBundle;
  9825. }
  9826. /**
  9827. * @category GPU
  9828. * @experimental
  9829. */
  9830. declare interface GPURenderPassLayout extends GPUObjectDescriptorBase {
  9831. colorFormats: (GPUTextureFormat | null)[];
  9832. depthStencilFormat?: GPUTextureFormat;
  9833. sampleCount?: number;
  9834. }
  9835. /**
  9836. * @category GPU
  9837. * @experimental
  9838. */
  9839. declare interface GPURenderBundleEncoderDescriptor extends GPURenderPassLayout {
  9840. depthReadOnly?: boolean;
  9841. stencilReadOnly?: boolean;
  9842. }
  9843. /**
  9844. * @category GPU
  9845. * @experimental
  9846. */
  9847. declare class GPUQueue implements GPUObjectBase {
  9848. label: string;
  9849. submit(commandBuffers: GPUCommandBuffer[]): undefined;
  9850. onSubmittedWorkDone(): Promise<undefined>;
  9851. writeBuffer(
  9852. buffer: GPUBuffer,
  9853. bufferOffset: number,
  9854. data: BufferSource,
  9855. dataOffset?: number,
  9856. size?: number,
  9857. ): undefined;
  9858. writeTexture(
  9859. destination: GPUImageCopyTexture,
  9860. data: BufferSource,
  9861. dataLayout: GPUImageDataLayout,
  9862. size: GPUExtent3D,
  9863. ): undefined;
  9864. }
  9865. /**
  9866. * @category GPU
  9867. * @experimental
  9868. */
  9869. declare class GPUQuerySet implements GPUObjectBase {
  9870. label: string;
  9871. destroy(): undefined;
  9872. readonly type: GPUQueryType;
  9873. readonly count: number;
  9874. }
  9875. /**
  9876. * @category GPU
  9877. * @experimental
  9878. */
  9879. declare interface GPUQuerySetDescriptor extends GPUObjectDescriptorBase {
  9880. type: GPUQueryType;
  9881. count: number;
  9882. }
  9883. /**
  9884. * @category GPU
  9885. * @experimental
  9886. */
  9887. declare type GPUQueryType = "occlusion" | "timestamp";
  9888. /**
  9889. * @category GPU
  9890. * @experimental
  9891. */
  9892. declare type GPUDeviceLostReason = "destroyed";
  9893. /**
  9894. * @category GPU
  9895. * @experimental
  9896. */
  9897. declare interface GPUDeviceLostInfo {
  9898. readonly reason: GPUDeviceLostReason;
  9899. readonly message: string;
  9900. }
  9901. /**
  9902. * @category GPU
  9903. * @experimental
  9904. */
  9905. declare class GPUError {
  9906. readonly message: string;
  9907. }
  9908. /**
  9909. * @category GPU
  9910. * @experimental
  9911. */
  9912. declare class GPUOutOfMemoryError extends GPUError {
  9913. constructor(message: string);
  9914. }
  9915. /**
  9916. * @category GPU
  9917. * @experimental
  9918. */
  9919. declare class GPUValidationError extends GPUError {
  9920. constructor(message: string);
  9921. }
  9922. /**
  9923. * @category GPU
  9924. * @experimental
  9925. */
  9926. declare class GPUInternalError extends GPUError {
  9927. constructor(message: string);
  9928. }
  9929. /**
  9930. * @category GPU
  9931. * @experimental
  9932. */
  9933. declare type GPUErrorFilter = "out-of-memory" | "validation" | "internal";
  9934. /**
  9935. * @category GPU
  9936. * @experimental
  9937. */
  9938. declare class GPUUncapturedErrorEvent extends Event {
  9939. constructor(
  9940. type: string,
  9941. gpuUncapturedErrorEventInitDict: GPUUncapturedErrorEventInit,
  9942. );
  9943. readonly error: GPUError;
  9944. }
  9945. /**
  9946. * @category GPU
  9947. * @experimental
  9948. */
  9949. declare interface GPUUncapturedErrorEventInit extends EventInit {
  9950. error: GPUError;
  9951. }
  9952. /**
  9953. * @category GPU
  9954. * @experimental
  9955. */
  9956. declare interface GPUColorDict {
  9957. r: number;
  9958. g: number;
  9959. b: number;
  9960. a: number;
  9961. }
  9962. /**
  9963. * @category GPU
  9964. * @experimental
  9965. */
  9966. declare type GPUColor = number[] | GPUColorDict;
  9967. /**
  9968. * @category GPU
  9969. * @experimental
  9970. */
  9971. declare interface GPUOrigin3DDict {
  9972. x?: number;
  9973. y?: number;
  9974. z?: number;
  9975. }
  9976. /**
  9977. * @category GPU
  9978. * @experimental
  9979. */
  9980. declare type GPUOrigin3D = number[] | GPUOrigin3DDict;
  9981. /**
  9982. * @category GPU
  9983. * @experimental
  9984. */
  9985. declare interface GPUExtent3DDict {
  9986. width: number;
  9987. height?: number;
  9988. depthOrArrayLayers?: number;
  9989. }
  9990. /**
  9991. * @category GPU
  9992. * @experimental
  9993. */
  9994. declare type GPUExtent3D = number[] | GPUExtent3DDict;
  9995. /**
  9996. * @category GPU
  9997. * @experimental
  9998. */
  9999. declare type GPUCanvasAlphaMode = "opaque" | "premultiplied";
  10000. /**
  10001. * @category GPU
  10002. * @experimental
  10003. */
  10004. declare interface GPUCanvasConfiguration {
  10005. device: GPUDevice;
  10006. format: GPUTextureFormat;
  10007. usage?: GPUTextureUsageFlags;
  10008. viewFormats?: GPUTextureFormat[];
  10009. colorSpace?: "srgb" | "display-p3";
  10010. alphaMode?: GPUCanvasAlphaMode;
  10011. width: number;
  10012. height: number;
  10013. }
  10014. /**
  10015. * @category GPU
  10016. * @experimental
  10017. */
  10018. declare interface GPUCanvasContext {
  10019. configure(configuration: GPUCanvasConfiguration): undefined;
  10020. unconfigure(): undefined;
  10021. getCurrentTexture(): GPUTexture;
  10022. }
  10023. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  10024. // deno-lint-ignore-file no-explicit-any no-var
  10025. /// <reference no-default-lib="true" />
  10026. /// <reference lib="esnext" />
  10027. /** @category WebSockets */
  10028. declare interface CloseEventInit extends EventInit {
  10029. code?: number;
  10030. reason?: string;
  10031. wasClean?: boolean;
  10032. }
  10033. /** @category WebSockets */
  10034. declare interface CloseEvent extends Event {
  10035. /**
  10036. * Returns the WebSocket connection close code provided by the server.
  10037. */
  10038. readonly code: number;
  10039. /**
  10040. * Returns the WebSocket connection close reason provided by the server.
  10041. */
  10042. readonly reason: string;
  10043. /**
  10044. * Returns true if the connection closed cleanly; false otherwise.
  10045. */
  10046. readonly wasClean: boolean;
  10047. }
  10048. /** @category WebSockets */
  10049. declare var CloseEvent: {
  10050. readonly prototype: CloseEvent;
  10051. new (type: string, eventInitDict?: CloseEventInit): CloseEvent;
  10052. };
  10053. /** @category WebSockets */
  10054. declare interface WebSocketEventMap {
  10055. close: CloseEvent;
  10056. error: Event;
  10057. message: MessageEvent;
  10058. open: Event;
  10059. }
  10060. /**
  10061. * Provides the API for creating and managing a WebSocket connection to a
  10062. * server, as well as for sending and receiving data on the connection.
  10063. *
  10064. * If you are looking to create a WebSocket server, please take a look at
  10065. * `Deno.upgradeWebSocket()`.
  10066. *
  10067. * @tags allow-net
  10068. * @category WebSockets
  10069. */
  10070. declare interface WebSocket extends EventTarget {
  10071. /**
  10072. * Returns a string that indicates how binary data from the WebSocket object is exposed to scripts:
  10073. *
  10074. * Can be set, to change how binary data is returned. The default is "blob".
  10075. */
  10076. binaryType: BinaryType;
  10077. /**
  10078. * Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network.
  10079. *
  10080. * If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.)
  10081. */
  10082. readonly bufferedAmount: number;
  10083. /**
  10084. * Returns the extensions selected by the server, if any.
  10085. */
  10086. readonly extensions: string;
  10087. onclose: ((this: WebSocket, ev: CloseEvent) => any) | null;
  10088. onerror: ((this: WebSocket, ev: Event | ErrorEvent) => any) | null;
  10089. onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null;
  10090. onopen: ((this: WebSocket, ev: Event) => any) | null;
  10091. /**
  10092. * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation.
  10093. */
  10094. readonly protocol: string;
  10095. /**
  10096. * Returns the state of the WebSocket object's connection. It can have the values described below.
  10097. */
  10098. readonly readyState: number;
  10099. /**
  10100. * Returns the URL that was used to establish the WebSocket connection.
  10101. */
  10102. readonly url: string;
  10103. /**
  10104. * Closes the WebSocket connection, optionally using code as the WebSocket connection close code and reason as the WebSocket connection close reason.
  10105. */
  10106. close(code?: number, reason?: string): void;
  10107. /**
  10108. * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.
  10109. */
  10110. send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;
  10111. readonly CLOSED: number;
  10112. readonly CLOSING: number;
  10113. readonly CONNECTING: number;
  10114. readonly OPEN: number;
  10115. addEventListener<K extends keyof WebSocketEventMap>(
  10116. type: K,
  10117. listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,
  10118. options?: boolean | AddEventListenerOptions,
  10119. ): void;
  10120. addEventListener(
  10121. type: string,
  10122. listener: EventListenerOrEventListenerObject,
  10123. options?: boolean | AddEventListenerOptions,
  10124. ): void;
  10125. removeEventListener<K extends keyof WebSocketEventMap>(
  10126. type: K,
  10127. listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,
  10128. options?: boolean | EventListenerOptions,
  10129. ): void;
  10130. removeEventListener(
  10131. type: string,
  10132. listener: EventListenerOrEventListenerObject,
  10133. options?: boolean | EventListenerOptions,
  10134. ): void;
  10135. }
  10136. /** @category WebSockets */
  10137. declare var WebSocket: {
  10138. readonly prototype: WebSocket;
  10139. new (url: string | URL, protocols?: string | string[]): WebSocket;
  10140. readonly CLOSED: number;
  10141. readonly CLOSING: number;
  10142. readonly CONNECTING: number;
  10143. readonly OPEN: number;
  10144. };
  10145. /** @category WebSockets */
  10146. declare type BinaryType = "arraybuffer" | "blob";
  10147. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  10148. // deno-lint-ignore-file no-explicit-any no-var
  10149. /// <reference no-default-lib="true" />
  10150. /// <reference lib="esnext" />
  10151. /** This Web Storage API interface provides access to a particular domain's
  10152. * session or local storage. It allows, for example, the addition, modification,
  10153. * or deletion of stored data items.
  10154. *
  10155. * @category Storage
  10156. */
  10157. declare interface Storage {
  10158. /**
  10159. * Returns the number of key/value pairs currently present in the list associated with the object.
  10160. */
  10161. readonly length: number;
  10162. /**
  10163. * Empties the list associated with the object of all key/value pairs, if there are any.
  10164. */
  10165. clear(): void;
  10166. /**
  10167. * Returns the current value associated with the given key, or null if the given key does not exist in the list associated with the object.
  10168. */
  10169. getItem(key: string): string | null;
  10170. /**
  10171. * Returns the name of the nth key in the list, or null if n is greater than or equal to the number of key/value pairs in the object.
  10172. */
  10173. key(index: number): string | null;
  10174. /**
  10175. * Removes the key/value pair with the given key from the list associated with the object, if a key/value pair with the given key exists.
  10176. */
  10177. removeItem(key: string): void;
  10178. /**
  10179. * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.
  10180. *
  10181. * Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.)
  10182. */
  10183. setItem(key: string, value: string): void;
  10184. [name: string]: any;
  10185. }
  10186. /** @category Storage */
  10187. declare var Storage: {
  10188. readonly prototype: Storage;
  10189. new (): never;
  10190. };
  10191. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  10192. // deno-lint-ignore-file no-var
  10193. /// <reference no-default-lib="true" />
  10194. /// <reference lib="esnext" />
  10195. /** @category Canvas */
  10196. declare type ColorSpaceConversion = "default" | "none";
  10197. /** @category Canvas */
  10198. declare type ImageOrientation = "flipY" | "from-image" | "none";
  10199. /** @category Canvas */
  10200. declare type PremultiplyAlpha = "default" | "none" | "premultiply";
  10201. /** @category Canvas */
  10202. declare type ResizeQuality = "high" | "low" | "medium" | "pixelated";
  10203. /** @category Canvas */
  10204. declare type ImageBitmapSource = Blob | ImageData;
  10205. /** @category Canvas */
  10206. declare interface ImageBitmapOptions {
  10207. colorSpaceConversion?: ColorSpaceConversion;
  10208. imageOrientation?: ImageOrientation;
  10209. premultiplyAlpha?: PremultiplyAlpha;
  10210. resizeHeight?: number;
  10211. resizeQuality?: ResizeQuality;
  10212. resizeWidth?: number;
  10213. }
  10214. /** @category Canvas */
  10215. declare function createImageBitmap(
  10216. image: ImageBitmapSource,
  10217. options?: ImageBitmapOptions,
  10218. ): Promise<ImageBitmap>;
  10219. /** @category Canvas */
  10220. declare function createImageBitmap(
  10221. image: ImageBitmapSource,
  10222. sx: number,
  10223. sy: number,
  10224. sw: number,
  10225. sh: number,
  10226. options?: ImageBitmapOptions,
  10227. ): Promise<ImageBitmap>;
  10228. /** @category Canvas */
  10229. declare interface ImageBitmap {
  10230. readonly height: number;
  10231. readonly width: number;
  10232. close(): void;
  10233. }
  10234. /** @category Canvas */
  10235. declare var ImageBitmap: {
  10236. prototype: ImageBitmap;
  10237. new (): ImageBitmap;
  10238. };
  10239. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  10240. // deno-lint-ignore-file no-var
  10241. /// <reference no-default-lib="true" />
  10242. /// <reference lib="esnext" />
  10243. /** @category Crypto */
  10244. declare var crypto: Crypto;
  10245. /** @category Crypto */
  10246. declare interface Algorithm {
  10247. name: string;
  10248. }
  10249. /** @category Crypto */
  10250. declare interface KeyAlgorithm {
  10251. name: string;
  10252. }
  10253. /** @category Crypto */
  10254. declare type AlgorithmIdentifier = string | Algorithm;
  10255. /** @category Crypto */
  10256. declare type HashAlgorithmIdentifier = AlgorithmIdentifier;
  10257. /** @category Crypto */
  10258. declare type KeyType = "private" | "public" | "secret";
  10259. /** @category Crypto */
  10260. declare type KeyUsage =
  10261. | "decrypt"
  10262. | "deriveBits"
  10263. | "deriveKey"
  10264. | "encrypt"
  10265. | "sign"
  10266. | "unwrapKey"
  10267. | "verify"
  10268. | "wrapKey";
  10269. /** @category Crypto */
  10270. declare type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki";
  10271. /** @category Crypto */
  10272. declare type NamedCurve = string;
  10273. /** @category Crypto */
  10274. declare interface RsaOtherPrimesInfo {
  10275. d?: string;
  10276. r?: string;
  10277. t?: string;
  10278. }
  10279. /** @category Crypto */
  10280. declare interface JsonWebKey {
  10281. alg?: string;
  10282. crv?: string;
  10283. d?: string;
  10284. dp?: string;
  10285. dq?: string;
  10286. e?: string;
  10287. ext?: boolean;
  10288. k?: string;
  10289. key_ops?: string[];
  10290. kty?: string;
  10291. n?: string;
  10292. oth?: RsaOtherPrimesInfo[];
  10293. p?: string;
  10294. q?: string;
  10295. qi?: string;
  10296. use?: string;
  10297. x?: string;
  10298. y?: string;
  10299. }
  10300. /** @category Crypto */
  10301. declare interface AesCbcParams extends Algorithm {
  10302. iv: BufferSource;
  10303. }
  10304. /** @category Crypto */
  10305. declare interface AesGcmParams extends Algorithm {
  10306. iv: BufferSource;
  10307. additionalData?: BufferSource;
  10308. tagLength?: number;
  10309. }
  10310. /** @category Crypto */
  10311. declare interface AesCtrParams extends Algorithm {
  10312. counter: BufferSource;
  10313. length: number;
  10314. }
  10315. /** @category Crypto */
  10316. declare interface HmacKeyGenParams extends Algorithm {
  10317. hash: HashAlgorithmIdentifier;
  10318. length?: number;
  10319. }
  10320. /** @category Crypto */
  10321. declare interface EcKeyGenParams extends Algorithm {
  10322. namedCurve: NamedCurve;
  10323. }
  10324. /** @category Crypto */
  10325. declare interface EcKeyImportParams extends Algorithm {
  10326. namedCurve: NamedCurve;
  10327. }
  10328. /** @category Crypto */
  10329. declare interface EcdsaParams extends Algorithm {
  10330. hash: HashAlgorithmIdentifier;
  10331. }
  10332. /** @category Crypto */
  10333. declare interface RsaHashedImportParams extends Algorithm {
  10334. hash: HashAlgorithmIdentifier;
  10335. }
  10336. /** @category Crypto */
  10337. declare interface RsaHashedKeyGenParams extends RsaKeyGenParams {
  10338. hash: HashAlgorithmIdentifier;
  10339. }
  10340. /** @category Crypto */
  10341. declare interface RsaKeyGenParams extends Algorithm {
  10342. modulusLength: number;
  10343. publicExponent: Uint8Array;
  10344. }
  10345. /** @category Crypto */
  10346. declare interface RsaPssParams extends Algorithm {
  10347. saltLength: number;
  10348. }
  10349. /** @category Crypto */
  10350. declare interface RsaOaepParams extends Algorithm {
  10351. label?: Uint8Array;
  10352. }
  10353. /** @category Crypto */
  10354. declare interface HmacImportParams extends Algorithm {
  10355. hash: HashAlgorithmIdentifier;
  10356. length?: number;
  10357. }
  10358. /** @category Crypto */
  10359. declare interface EcKeyAlgorithm extends KeyAlgorithm {
  10360. namedCurve: NamedCurve;
  10361. }
  10362. /** @category Crypto */
  10363. declare interface HmacKeyAlgorithm extends KeyAlgorithm {
  10364. hash: KeyAlgorithm;
  10365. length: number;
  10366. }
  10367. /** @category Crypto */
  10368. declare interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm {
  10369. hash: KeyAlgorithm;
  10370. }
  10371. /** @category Crypto */
  10372. declare interface RsaKeyAlgorithm extends KeyAlgorithm {
  10373. modulusLength: number;
  10374. publicExponent: Uint8Array;
  10375. }
  10376. /** @category Crypto */
  10377. declare interface HkdfParams extends Algorithm {
  10378. hash: HashAlgorithmIdentifier;
  10379. info: BufferSource;
  10380. salt: BufferSource;
  10381. }
  10382. /** @category Crypto */
  10383. declare interface Pbkdf2Params extends Algorithm {
  10384. hash: HashAlgorithmIdentifier;
  10385. iterations: number;
  10386. salt: BufferSource;
  10387. }
  10388. /** @category Crypto */
  10389. declare interface AesDerivedKeyParams extends Algorithm {
  10390. length: number;
  10391. }
  10392. /** @category Crypto */
  10393. declare interface EcdhKeyDeriveParams extends Algorithm {
  10394. public: CryptoKey;
  10395. }
  10396. /** @category Crypto */
  10397. declare interface AesKeyGenParams extends Algorithm {
  10398. length: number;
  10399. }
  10400. /** @category Crypto */
  10401. declare interface AesKeyAlgorithm extends KeyAlgorithm {
  10402. length: number;
  10403. }
  10404. /** The CryptoKey dictionary of the Web Crypto API represents a cryptographic
  10405. * key.
  10406. *
  10407. * @category Crypto
  10408. */
  10409. declare interface CryptoKey {
  10410. readonly algorithm: KeyAlgorithm;
  10411. readonly extractable: boolean;
  10412. readonly type: KeyType;
  10413. readonly usages: KeyUsage[];
  10414. }
  10415. /** @category Crypto */
  10416. declare var CryptoKey: {
  10417. readonly prototype: CryptoKey;
  10418. new (): never;
  10419. };
  10420. /** The CryptoKeyPair dictionary of the Web Crypto API represents a key pair for
  10421. * an asymmetric cryptography algorithm, also known as a public-key algorithm.
  10422. *
  10423. * @category Crypto
  10424. */
  10425. declare interface CryptoKeyPair {
  10426. privateKey: CryptoKey;
  10427. publicKey: CryptoKey;
  10428. }
  10429. /** @category Crypto */
  10430. declare var CryptoKeyPair: {
  10431. readonly prototype: CryptoKeyPair;
  10432. new (): never;
  10433. };
  10434. /** This Web Crypto API interface provides a number of low-level cryptographic
  10435. * functions. It is accessed via the Crypto.subtle properties available in a
  10436. * window context (via Window.crypto).
  10437. *
  10438. * @category Crypto
  10439. */
  10440. declare interface SubtleCrypto {
  10441. generateKey(
  10442. algorithm: RsaHashedKeyGenParams | EcKeyGenParams,
  10443. extractable: boolean,
  10444. keyUsages: KeyUsage[],
  10445. ): Promise<CryptoKeyPair>;
  10446. generateKey(
  10447. algorithm: AesKeyGenParams | HmacKeyGenParams,
  10448. extractable: boolean,
  10449. keyUsages: KeyUsage[],
  10450. ): Promise<CryptoKey>;
  10451. generateKey(
  10452. algorithm: AlgorithmIdentifier,
  10453. extractable: boolean,
  10454. keyUsages: KeyUsage[],
  10455. ): Promise<CryptoKeyPair | CryptoKey>;
  10456. importKey(
  10457. format: "jwk",
  10458. keyData: JsonWebKey,
  10459. algorithm:
  10460. | AlgorithmIdentifier
  10461. | HmacImportParams
  10462. | RsaHashedImportParams
  10463. | EcKeyImportParams,
  10464. extractable: boolean,
  10465. keyUsages: KeyUsage[],
  10466. ): Promise<CryptoKey>;
  10467. importKey(
  10468. format: Exclude<KeyFormat, "jwk">,
  10469. keyData: BufferSource,
  10470. algorithm:
  10471. | AlgorithmIdentifier
  10472. | HmacImportParams
  10473. | RsaHashedImportParams
  10474. | EcKeyImportParams,
  10475. extractable: boolean,
  10476. keyUsages: KeyUsage[],
  10477. ): Promise<CryptoKey>;
  10478. exportKey(format: "jwk", key: CryptoKey): Promise<JsonWebKey>;
  10479. exportKey(
  10480. format: Exclude<KeyFormat, "jwk">,
  10481. key: CryptoKey,
  10482. ): Promise<ArrayBuffer>;
  10483. sign(
  10484. algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams,
  10485. key: CryptoKey,
  10486. data: BufferSource,
  10487. ): Promise<ArrayBuffer>;
  10488. verify(
  10489. algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams,
  10490. key: CryptoKey,
  10491. signature: BufferSource,
  10492. data: BufferSource,
  10493. ): Promise<boolean>;
  10494. digest(
  10495. algorithm: AlgorithmIdentifier,
  10496. data: BufferSource,
  10497. ): Promise<ArrayBuffer>;
  10498. encrypt(
  10499. algorithm:
  10500. | AlgorithmIdentifier
  10501. | RsaOaepParams
  10502. | AesCbcParams
  10503. | AesGcmParams
  10504. | AesCtrParams,
  10505. key: CryptoKey,
  10506. data: BufferSource,
  10507. ): Promise<ArrayBuffer>;
  10508. decrypt(
  10509. algorithm:
  10510. | AlgorithmIdentifier
  10511. | RsaOaepParams
  10512. | AesCbcParams
  10513. | AesGcmParams
  10514. | AesCtrParams,
  10515. key: CryptoKey,
  10516. data: BufferSource,
  10517. ): Promise<ArrayBuffer>;
  10518. deriveBits(
  10519. algorithm:
  10520. | AlgorithmIdentifier
  10521. | HkdfParams
  10522. | Pbkdf2Params
  10523. | EcdhKeyDeriveParams,
  10524. baseKey: CryptoKey,
  10525. length: number,
  10526. ): Promise<ArrayBuffer>;
  10527. deriveKey(
  10528. algorithm:
  10529. | AlgorithmIdentifier
  10530. | HkdfParams
  10531. | Pbkdf2Params
  10532. | EcdhKeyDeriveParams,
  10533. baseKey: CryptoKey,
  10534. derivedKeyType:
  10535. | AlgorithmIdentifier
  10536. | AesDerivedKeyParams
  10537. | HmacImportParams
  10538. | HkdfParams
  10539. | Pbkdf2Params,
  10540. extractable: boolean,
  10541. keyUsages: KeyUsage[],
  10542. ): Promise<CryptoKey>;
  10543. wrapKey(
  10544. format: KeyFormat,
  10545. key: CryptoKey,
  10546. wrappingKey: CryptoKey,
  10547. wrapAlgorithm:
  10548. | AlgorithmIdentifier
  10549. | RsaOaepParams
  10550. | AesCbcParams
  10551. | AesCtrParams,
  10552. ): Promise<ArrayBuffer>;
  10553. unwrapKey(
  10554. format: KeyFormat,
  10555. wrappedKey: BufferSource,
  10556. unwrappingKey: CryptoKey,
  10557. unwrapAlgorithm:
  10558. | AlgorithmIdentifier
  10559. | RsaOaepParams
  10560. | AesCbcParams
  10561. | AesCtrParams,
  10562. unwrappedKeyAlgorithm:
  10563. | AlgorithmIdentifier
  10564. | HmacImportParams
  10565. | RsaHashedImportParams
  10566. | EcKeyImportParams,
  10567. extractable: boolean,
  10568. keyUsages: KeyUsage[],
  10569. ): Promise<CryptoKey>;
  10570. }
  10571. /** @category Crypto */
  10572. declare var SubtleCrypto: {
  10573. readonly prototype: SubtleCrypto;
  10574. new (): never;
  10575. };
  10576. /** @category Crypto */
  10577. declare interface Crypto {
  10578. readonly subtle: SubtleCrypto;
  10579. getRandomValues<
  10580. T extends
  10581. | Int8Array
  10582. | Int16Array
  10583. | Int32Array
  10584. | Uint8Array
  10585. | Uint16Array
  10586. | Uint32Array
  10587. | Uint8ClampedArray
  10588. | BigInt64Array
  10589. | BigUint64Array,
  10590. >(
  10591. array: T,
  10592. ): T;
  10593. randomUUID(): `${string}-${string}-${string}-${string}-${string}`;
  10594. }
  10595. /** @category Crypto */
  10596. declare var Crypto: {
  10597. readonly prototype: Crypto;
  10598. new (): never;
  10599. };
  10600. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  10601. // deno-lint-ignore-file no-explicit-any no-var
  10602. /// <reference no-default-lib="true" />
  10603. /// <reference lib="esnext" />
  10604. /**
  10605. * @category Messaging
  10606. * @experimental
  10607. */
  10608. declare interface BroadcastChannelEventMap {
  10609. "message": MessageEvent;
  10610. "messageerror": MessageEvent;
  10611. }
  10612. /**
  10613. * @category Messaging
  10614. * @experimental
  10615. */
  10616. declare interface BroadcastChannel extends EventTarget {
  10617. /**
  10618. * Returns the channel name (as passed to the constructor).
  10619. */
  10620. readonly name: string;
  10621. onmessage: ((this: BroadcastChannel, ev: MessageEvent) => any) | null;
  10622. onmessageerror: ((this: BroadcastChannel, ev: MessageEvent) => any) | null;
  10623. /**
  10624. * Closes the BroadcastChannel object, opening it up to garbage collection.
  10625. */
  10626. close(): void;
  10627. /**
  10628. * Sends the given message to other BroadcastChannel objects set up for
  10629. * this channel. Messages can be structured objects, e.g. nested objects
  10630. * and arrays.
  10631. */
  10632. postMessage(message: any): void;
  10633. addEventListener<K extends keyof BroadcastChannelEventMap>(
  10634. type: K,
  10635. listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any,
  10636. options?: boolean | AddEventListenerOptions,
  10637. ): void;
  10638. addEventListener(
  10639. type: string,
  10640. listener: EventListenerOrEventListenerObject,
  10641. options?: boolean | AddEventListenerOptions,
  10642. ): void;
  10643. removeEventListener<K extends keyof BroadcastChannelEventMap>(
  10644. type: K,
  10645. listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any,
  10646. options?: boolean | EventListenerOptions,
  10647. ): void;
  10648. removeEventListener(
  10649. type: string,
  10650. listener: EventListenerOrEventListenerObject,
  10651. options?: boolean | EventListenerOptions,
  10652. ): void;
  10653. }
  10654. /**
  10655. * @category Messaging
  10656. * @experimental
  10657. */
  10658. declare var BroadcastChannel: {
  10659. readonly prototype: BroadcastChannel;
  10660. new (name: string): BroadcastChannel;
  10661. };
  10662. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  10663. /// <reference no-default-lib="true" />
  10664. /// <reference lib="esnext" />
  10665. /// <reference lib="esnext.disposable" />
  10666. declare namespace Deno {
  10667. /** @category Network */
  10668. export interface NetAddr {
  10669. transport: "tcp" | "udp";
  10670. hostname: string;
  10671. port: number;
  10672. }
  10673. /** @category Network */
  10674. export interface UnixAddr {
  10675. transport: "unix" | "unixpacket";
  10676. path: string;
  10677. }
  10678. /** @category Network */
  10679. export type Addr = NetAddr | UnixAddr;
  10680. /** A generic network listener for stream-oriented protocols.
  10681. *
  10682. * @category Network
  10683. */
  10684. export interface Listener<T extends Conn = Conn, A extends Addr = Addr>
  10685. extends AsyncIterable<T>, Disposable {
  10686. /** Waits for and resolves to the next connection to the `Listener`. */
  10687. accept(): Promise<T>;
  10688. /** Close closes the listener. Any pending accept promises will be rejected
  10689. * with errors. */
  10690. close(): void;
  10691. /** Return the address of the `Listener`. */
  10692. readonly addr: A;
  10693. /**
  10694. * Return the rid of the `Listener`.
  10695. *
  10696. * @deprecated This will be removed in Deno 2.0. See the
  10697. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  10698. * for migration instructions.
  10699. */
  10700. readonly rid: number;
  10701. [Symbol.asyncIterator](): AsyncIterableIterator<T>;
  10702. /**
  10703. * Make the listener block the event loop from finishing.
  10704. *
  10705. * Note: the listener blocks the event loop from finishing by default.
  10706. * This method is only meaningful after `.unref()` is called.
  10707. */
  10708. ref(): void;
  10709. /** Make the listener not block the event loop from finishing. */
  10710. unref(): void;
  10711. }
  10712. /** Specialized listener that accepts TLS connections.
  10713. *
  10714. * @category Network
  10715. */
  10716. export type TlsListener = Listener<TlsConn, NetAddr>;
  10717. /** Specialized listener that accepts TCP connections.
  10718. *
  10719. * @category Network
  10720. */
  10721. export type TcpListener = Listener<TcpConn, NetAddr>;
  10722. /** Specialized listener that accepts Unix connections.
  10723. *
  10724. * @category Network
  10725. */
  10726. export type UnixListener = Listener<UnixConn, UnixAddr>;
  10727. /** @category Network */
  10728. export interface Conn<A extends Addr = Addr>
  10729. extends Reader, Writer, Closer, Disposable {
  10730. /** The local address of the connection. */
  10731. readonly localAddr: A;
  10732. /** The remote address of the connection. */
  10733. readonly remoteAddr: A;
  10734. /**
  10735. * The resource ID of the connection.
  10736. *
  10737. * @deprecated This will be removed in Deno 2.0. See the
  10738. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  10739. * for migration instructions.
  10740. */
  10741. readonly rid: number;
  10742. /** Shuts down (`shutdown(2)`) the write side of the connection. Most
  10743. * callers should just use `close()`. */
  10744. closeWrite(): Promise<void>;
  10745. /** Make the connection block the event loop from finishing.
  10746. *
  10747. * Note: the connection blocks the event loop from finishing by default.
  10748. * This method is only meaningful after `.unref()` is called.
  10749. */
  10750. ref(): void;
  10751. /** Make the connection not block the event loop from finishing. */
  10752. unref(): void;
  10753. readonly readable: ReadableStream<Uint8Array>;
  10754. readonly writable: WritableStream<Uint8Array>;
  10755. }
  10756. /** @category Network */
  10757. export interface TlsHandshakeInfo {
  10758. /**
  10759. * Contains the ALPN protocol selected during negotiation with the server.
  10760. * If no ALPN protocol selected, returns `null`.
  10761. */
  10762. alpnProtocol: string | null;
  10763. }
  10764. /** @category Network */
  10765. export interface TlsConn extends Conn<NetAddr> {
  10766. /** Runs the client or server handshake protocol to completion if that has
  10767. * not happened yet. Calling this method is optional; the TLS handshake
  10768. * will be completed automatically as soon as data is sent or received. */
  10769. handshake(): Promise<TlsHandshakeInfo>;
  10770. /**
  10771. * The resource ID of the connection.
  10772. *
  10773. * @deprecated This will be removed in Deno 2.0. See the
  10774. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  10775. * for migration instructions.
  10776. */
  10777. readonly rid: number;
  10778. }
  10779. /** @category Network */
  10780. export interface ListenOptions {
  10781. /** The port to listen on.
  10782. *
  10783. * Set to `0` to listen on any available port.
  10784. */
  10785. port: number;
  10786. /** A literal IP address or host name that can be resolved to an IP address.
  10787. *
  10788. * __Note about `0.0.0.0`__ While listening `0.0.0.0` works on all platforms,
  10789. * the browsers on Windows don't work with the address `0.0.0.0`.
  10790. * You should show the message like `server running on localhost:8080` instead of
  10791. * `server running on 0.0.0.0:8080` if your program supports Windows.
  10792. *
  10793. * @default {"0.0.0.0"} */
  10794. hostname?: string;
  10795. }
  10796. /** @category Network */
  10797. export interface TcpListenOptions extends ListenOptions {
  10798. }
  10799. /** Listen announces on the local transport address.
  10800. *
  10801. * ```ts
  10802. * const listener1 = Deno.listen({ port: 80 })
  10803. * const listener2 = Deno.listen({ hostname: "192.0.2.1", port: 80 })
  10804. * const listener3 = Deno.listen({ hostname: "[2001:db8::1]", port: 80 });
  10805. * const listener4 = Deno.listen({ hostname: "golang.org", port: 80, transport: "tcp" });
  10806. * ```
  10807. *
  10808. * Requires `allow-net` permission.
  10809. *
  10810. * @tags allow-net
  10811. * @category Network
  10812. */
  10813. export function listen(
  10814. options: TcpListenOptions & { transport?: "tcp" },
  10815. ): TcpListener;
  10816. /** Options which can be set when opening a Unix listener via
  10817. * {@linkcode Deno.listen} or {@linkcode Deno.listenDatagram}.
  10818. *
  10819. * @category Network
  10820. */
  10821. export interface UnixListenOptions {
  10822. /** A path to the Unix Socket. */
  10823. path: string;
  10824. }
  10825. /** Listen announces on the local transport address.
  10826. *
  10827. * ```ts
  10828. * const listener = Deno.listen({ path: "/foo/bar.sock", transport: "unix" })
  10829. * ```
  10830. *
  10831. * Requires `allow-read` and `allow-write` permission.
  10832. *
  10833. * @tags allow-read, allow-write
  10834. * @category Network
  10835. */
  10836. // deno-lint-ignore adjacent-overload-signatures
  10837. export function listen(
  10838. options: UnixListenOptions & { transport: "unix" },
  10839. ): UnixListener;
  10840. /** Provides TLS certified keys, ie: a key that has been certified by a trusted certificate authority.
  10841. * A certified key generally consists of a private key and certificate part.
  10842. *
  10843. * @category Network
  10844. */
  10845. export type TlsCertifiedKeyOptions =
  10846. | TlsCertifiedKeyPem
  10847. | TlsCertifiedKeyFromFile
  10848. | TlsCertifiedKeyConnectTls;
  10849. /**
  10850. * Provides certified key material from strings. The key material is provided in
  10851. * `PEM`-format (Privacy Enhanced Mail, https://www.rfc-editor.org/rfc/rfc1422) which can be identified by having
  10852. * `-----BEGIN-----` and `-----END-----` markers at the beginning and end of the strings. This type of key is not compatible
  10853. * with `DER`-format keys which are binary.
  10854. *
  10855. * Deno supports RSA, EC, and PKCS8-format keys.
  10856. *
  10857. * ```ts
  10858. * const key = {
  10859. * key: "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
  10860. * cert: "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n" }
  10861. * };
  10862. * ```
  10863. *
  10864. * @category Network
  10865. */
  10866. export interface TlsCertifiedKeyPem {
  10867. /** The format of this key material, which must be PEM. */
  10868. keyFormat?: "pem";
  10869. /** Private key in `PEM` format. RSA, EC, and PKCS8-format keys are supported. */
  10870. key: string;
  10871. /** Certificate chain in `PEM` format. */
  10872. cert: string;
  10873. }
  10874. /**
  10875. * @deprecated This will be removed in Deno 2.0. See the
  10876. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  10877. * for migration instructions.
  10878. *
  10879. * @category Network
  10880. */
  10881. export interface TlsCertifiedKeyFromFile {
  10882. /** Path to a file containing a PEM formatted CA certificate. Requires
  10883. * `--allow-read`.
  10884. *
  10885. * @tags allow-read
  10886. * @deprecated This will be removed in Deno 2.0. See the
  10887. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  10888. * for migration instructions.
  10889. */
  10890. certFile: string;
  10891. /** Path to a file containing a private key file. Requires `--allow-read`.
  10892. *
  10893. * @tags allow-read
  10894. * @deprecated This will be removed in Deno 2.0. See the
  10895. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  10896. * for migration instructions.
  10897. */
  10898. keyFile: string;
  10899. }
  10900. /**
  10901. * @deprecated This will be removed in Deno 2.0. See the
  10902. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  10903. * for migration instructions.
  10904. *
  10905. * @category Network
  10906. */
  10907. export interface TlsCertifiedKeyConnectTls {
  10908. /**
  10909. * Certificate chain in `PEM` format.
  10910. *
  10911. * @deprecated This will be removed in Deno 2.0. See the
  10912. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  10913. * for migration instructions.
  10914. */
  10915. certChain: string;
  10916. /**
  10917. * Private key in `PEM` format. RSA, EC, and PKCS8-format keys are supported.
  10918. *
  10919. * @deprecated This will be removed in Deno 2.0. See the
  10920. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  10921. * for migration instructions.
  10922. */
  10923. privateKey: string;
  10924. }
  10925. /** @category Network */
  10926. export interface ListenTlsOptions extends TcpListenOptions {
  10927. transport?: "tcp";
  10928. /** Application-Layer Protocol Negotiation (ALPN) protocols to announce to
  10929. * the client. If not specified, no ALPN extension will be included in the
  10930. * TLS handshake.
  10931. */
  10932. alpnProtocols?: string[];
  10933. }
  10934. /** Listen announces on the local transport address over TLS (transport layer
  10935. * security).
  10936. *
  10937. * ```ts
  10938. * using listener = Deno.listenTls({
  10939. * port: 443,
  10940. * cert: Deno.readTextFileSync("./server.crt"),
  10941. * key: Deno.readTextFileSync("./server.key"),
  10942. * });
  10943. * ```
  10944. *
  10945. * Requires `allow-net` permission.
  10946. *
  10947. * @tags allow-net
  10948. * @category Network
  10949. */
  10950. export function listenTls(
  10951. options: ListenTlsOptions & TlsCertifiedKeyOptions,
  10952. ): TlsListener;
  10953. /** @category Network */
  10954. export interface ConnectOptions {
  10955. /** The port to connect to. */
  10956. port: number;
  10957. /** A literal IP address or host name that can be resolved to an IP address.
  10958. * If not specified,
  10959. *
  10960. * @default {"127.0.0.1"} */
  10961. hostname?: string;
  10962. transport?: "tcp";
  10963. }
  10964. /**
  10965. * Connects to the hostname (default is "127.0.0.1") and port on the named
  10966. * transport (default is "tcp"), and resolves to the connection (`Conn`).
  10967. *
  10968. * ```ts
  10969. * const conn1 = await Deno.connect({ port: 80 });
  10970. * const conn2 = await Deno.connect({ hostname: "192.0.2.1", port: 80 });
  10971. * const conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 });
  10972. * const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" });
  10973. * ```
  10974. *
  10975. * Requires `allow-net` permission for "tcp".
  10976. *
  10977. * @tags allow-net
  10978. * @category Network
  10979. */
  10980. export function connect(options: ConnectOptions): Promise<TcpConn>;
  10981. /** @category Network */
  10982. export interface TcpConn extends Conn<NetAddr> {
  10983. /**
  10984. * Enable/disable the use of Nagle's algorithm.
  10985. *
  10986. * @param [noDelay=true]
  10987. */
  10988. setNoDelay(noDelay?: boolean): void;
  10989. /** Enable/disable keep-alive functionality. */
  10990. setKeepAlive(keepAlive?: boolean): void;
  10991. /**
  10992. * The resource ID of the connection.
  10993. *
  10994. * @deprecated This will be removed in Deno 2.0. See the
  10995. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  10996. * for migration instructions.
  10997. */
  10998. readonly rid: number;
  10999. }
  11000. /** @category Network */
  11001. export interface UnixConnectOptions {
  11002. transport: "unix";
  11003. path: string;
  11004. }
  11005. /** @category Network */
  11006. export interface UnixConn extends Conn<UnixAddr> {
  11007. /**
  11008. * The resource ID of the connection.
  11009. *
  11010. * @deprecated This will be removed in Deno 2.0. See the
  11011. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  11012. * for migration instructions.
  11013. */
  11014. readonly rid: number;
  11015. }
  11016. /** Connects to the hostname (default is "127.0.0.1") and port on the named
  11017. * transport (default is "tcp"), and resolves to the connection (`Conn`).
  11018. *
  11019. * ```ts
  11020. * const conn1 = await Deno.connect({ port: 80 });
  11021. * const conn2 = await Deno.connect({ hostname: "192.0.2.1", port: 80 });
  11022. * const conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 });
  11023. * const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" });
  11024. * const conn5 = await Deno.connect({ path: "/foo/bar.sock", transport: "unix" });
  11025. * ```
  11026. *
  11027. * Requires `allow-net` permission for "tcp" and `allow-read` for "unix".
  11028. *
  11029. * @tags allow-net, allow-read
  11030. * @category Network
  11031. */
  11032. // deno-lint-ignore adjacent-overload-signatures
  11033. export function connect(options: UnixConnectOptions): Promise<UnixConn>;
  11034. /** @category Network */
  11035. export interface ConnectTlsOptions {
  11036. /** The port to connect to. */
  11037. port: number;
  11038. /** A literal IP address or host name that can be resolved to an IP address.
  11039. *
  11040. * @default {"127.0.0.1"} */
  11041. hostname?: string;
  11042. /** Path to a file containing a PEM formatted list of root certificates that will
  11043. * be used in addition to the default root certificates to verify the peer's certificate. Requires
  11044. * `--allow-read`.
  11045. *
  11046. * @tags allow-read
  11047. * @deprecated This will be removed in Deno 2.0. See the
  11048. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  11049. * for migration instructions.
  11050. */
  11051. certFile?: string;
  11052. /** A list of root certificates that will be used in addition to the
  11053. * default root certificates to verify the peer's certificate.
  11054. *
  11055. * Must be in PEM format. */
  11056. caCerts?: string[];
  11057. /** Application-Layer Protocol Negotiation (ALPN) protocols supported by
  11058. * the client. If not specified, no ALPN extension will be included in the
  11059. * TLS handshake.
  11060. */
  11061. alpnProtocols?: string[];
  11062. }
  11063. /** Establishes a secure connection over TLS (transport layer security) using
  11064. * an optional cert file, hostname (default is "127.0.0.1") and port. The
  11065. * cert file is optional and if not included Mozilla's root certificates will
  11066. * be used (see also https://github.com/ctz/webpki-roots for specifics)
  11067. *
  11068. * ```ts
  11069. * const caCert = await Deno.readTextFile("./certs/my_custom_root_CA.pem");
  11070. * const conn1 = await Deno.connectTls({ port: 80 });
  11071. * const conn2 = await Deno.connectTls({ caCerts: [caCert], hostname: "192.0.2.1", port: 80 });
  11072. * const conn3 = await Deno.connectTls({ hostname: "[2001:db8::1]", port: 80 });
  11073. * const conn4 = await Deno.connectTls({ caCerts: [caCert], hostname: "golang.org", port: 80});
  11074. * ```
  11075. *
  11076. * Requires `allow-net` permission.
  11077. *
  11078. * @tags allow-net
  11079. * @category Network
  11080. */
  11081. export function connectTls(options: ConnectTlsOptions): Promise<TlsConn>;
  11082. /** Establishes a secure connection over TLS (transport layer security) using
  11083. * an optional cert file, client certificate, hostname (default is "127.0.0.1") and
  11084. * port. The cert file is optional and if not included Mozilla's root certificates will
  11085. * be used (see also https://github.com/ctz/webpki-roots for specifics)
  11086. *
  11087. * ```ts
  11088. * const caCert = await Deno.readTextFile("./certs/my_custom_root_CA.pem");
  11089. * const key = "----BEGIN PRIVATE KEY----...";
  11090. * const cert = "----BEGIN CERTIFICATE----...";
  11091. * const conn1 = await Deno.connectTls({ port: 80, key, cert });
  11092. * const conn2 = await Deno.connectTls({ caCerts: [caCert], hostname: "192.0.2.1", port: 80, key, cert });
  11093. * const conn3 = await Deno.connectTls({ hostname: "[2001:db8::1]", port: 80, key, cert });
  11094. * const conn4 = await Deno.connectTls({ caCerts: [caCert], hostname: "golang.org", port: 80, key, cert });
  11095. * ```
  11096. *
  11097. * Requires `allow-net` permission.
  11098. *
  11099. * @tags allow-net
  11100. * @category Network
  11101. */
  11102. export function connectTls(
  11103. options: ConnectTlsOptions & TlsCertifiedKeyOptions,
  11104. ): Promise<TlsConn>;
  11105. /** @category Network */
  11106. export interface StartTlsOptions {
  11107. /** A literal IP address or host name that can be resolved to an IP address.
  11108. *
  11109. * @default {"127.0.0.1"} */
  11110. hostname?: string;
  11111. /** A list of root certificates that will be used in addition to the
  11112. * default root certificates to verify the peer's certificate.
  11113. *
  11114. * Must be in PEM format. */
  11115. caCerts?: string[];
  11116. /** Application-Layer Protocol Negotiation (ALPN) protocols to announce to
  11117. * the client. If not specified, no ALPN extension will be included in the
  11118. * TLS handshake.
  11119. */
  11120. alpnProtocols?: string[];
  11121. }
  11122. /** Start TLS handshake from an existing connection using an optional list of
  11123. * CA certificates, and hostname (default is "127.0.0.1"). Specifying CA certs
  11124. * is optional. By default the configured root certificates are used. Using
  11125. * this function requires that the other end of the connection is prepared for
  11126. * a TLS handshake.
  11127. *
  11128. * Note that this function *consumes* the TCP connection passed to it, thus the
  11129. * original TCP connection will be unusable after calling this. Additionally,
  11130. * you need to ensure that the TCP connection is not being used elsewhere when
  11131. * calling this function in order for the TCP connection to be consumed properly.
  11132. * For instance, if there is a `Promise` that is waiting for read operation on
  11133. * the TCP connection to complete, it is considered that the TCP connection is
  11134. * being used elsewhere. In such a case, this function will fail.
  11135. *
  11136. * ```ts
  11137. * const conn = await Deno.connect({ port: 80, hostname: "127.0.0.1" });
  11138. * const caCert = await Deno.readTextFile("./certs/my_custom_root_CA.pem");
  11139. * // `conn` becomes unusable after calling `Deno.startTls`
  11140. * const tlsConn = await Deno.startTls(conn, { caCerts: [caCert], hostname: "localhost" });
  11141. * ```
  11142. *
  11143. * Requires `allow-net` permission.
  11144. *
  11145. * @tags allow-net
  11146. * @category Network
  11147. */
  11148. export function startTls(
  11149. conn: TcpConn,
  11150. options?: StartTlsOptions,
  11151. ): Promise<TlsConn>;
  11152. /** Shutdown socket send operations.
  11153. *
  11154. * Matches behavior of POSIX shutdown(3).
  11155. *
  11156. * ```ts
  11157. * const listener = Deno.listen({ port: 80 });
  11158. * const conn = await listener.accept();
  11159. * Deno.shutdown(conn.rid);
  11160. * ```
  11161. *
  11162. * @deprecated This will be removed in Deno 2.0. See the
  11163. * {@link https://docs.deno.com/runtime/manual/advanced/migrate_deprecations | Deno 1.x to 2.x Migration Guide}
  11164. * for migration instructions.
  11165. *
  11166. * @category Network
  11167. */
  11168. export function shutdown(rid: number): Promise<void>;
  11169. }
  11170. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  11171. // Documentation partially adapted from [MDN](https://developer.mozilla.org/),
  11172. // by Mozilla Contributors, which is licensed under CC-BY-SA 2.5.
  11173. /// <reference no-default-lib="true" />
  11174. /// <reference lib="esnext" />
  11175. /// <reference lib="deno.console" />
  11176. /// <reference lib="deno.url" />
  11177. /// <reference lib="deno.web" />
  11178. /// <reference lib="deno.webgpu" />
  11179. /// <reference lib="deno.canvas" />
  11180. /// <reference lib="deno.fetch" />
  11181. /// <reference lib="deno.websocket" />
  11182. /// <reference lib="deno.crypto" />
  11183. /** @category WASM */
  11184. declare namespace WebAssembly {
  11185. /**
  11186. * The `WebAssembly.CompileError` object indicates an error during WebAssembly decoding or validation.
  11187. *
  11188. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/CompileError)
  11189. *
  11190. * @category WASM
  11191. */
  11192. export class CompileError extends Error {
  11193. /** Creates a new `WebAssembly.CompileError` object. */
  11194. constructor(message?: string, options?: ErrorOptions);
  11195. }
  11196. /**
  11197. * A `WebAssembly.Global` object represents a global variable instance, accessible from
  11198. * both JavaScript and importable/exportable across one or more `WebAssembly.Module`
  11199. * instances. This allows dynamic linking of multiple modules.
  11200. *
  11201. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global)
  11202. *
  11203. * @category WASM
  11204. */
  11205. export class Global {
  11206. /** Creates a new `Global` object. */
  11207. constructor(descriptor: GlobalDescriptor, v?: any);
  11208. /**
  11209. * The value contained inside the global variable — this can be used to directly set
  11210. * and get the global's value.
  11211. */
  11212. value: any;
  11213. /** Old-style method that returns the value contained inside the global variable. */
  11214. valueOf(): any;
  11215. }
  11216. /**
  11217. * A `WebAssembly.Instance` object is a stateful, executable instance of a `WebAssembly.Module`.
  11218. * Instance objects contain all the Exported WebAssembly functions that allow calling into
  11219. * WebAssembly code from JavaScript.
  11220. *
  11221. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance)
  11222. *
  11223. * @category WASM
  11224. */
  11225. export class Instance {
  11226. /** Creates a new Instance object. */
  11227. constructor(module: Module, importObject?: Imports);
  11228. /**
  11229. * Returns an object containing as its members all the functions exported from the
  11230. * WebAssembly module instance, to allow them to be accessed and used by JavaScript.
  11231. * Read-only.
  11232. */
  11233. readonly exports: Exports;
  11234. }
  11235. /**
  11236. * The `WebAssembly.LinkError` object indicates an error during module instantiation
  11237. * (besides traps from the start function).
  11238. *
  11239. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/LinkError)
  11240. *
  11241. * @category WASM
  11242. */
  11243. export class LinkError extends Error {
  11244. /** Creates a new WebAssembly.LinkError object. */
  11245. constructor(message?: string, options?: ErrorOptions);
  11246. }
  11247. /**
  11248. * The `WebAssembly.Memory` object is a resizable `ArrayBuffer` or `SharedArrayBuffer` that
  11249. * holds the raw bytes of memory accessed by a WebAssembly Instance.
  11250. *
  11251. * A memory created by JavaScript or in WebAssembly code will be accessible and mutable
  11252. * from both JavaScript and WebAssembly.
  11253. *
  11254. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory)
  11255. *
  11256. * @category WASM
  11257. */
  11258. export class Memory {
  11259. /** Creates a new `Memory` object. */
  11260. constructor(descriptor: MemoryDescriptor);
  11261. /** An accessor property that returns the buffer contained in the memory. */
  11262. readonly buffer: ArrayBuffer | SharedArrayBuffer;
  11263. /**
  11264. * Increases the size of the memory instance by a specified number of WebAssembly
  11265. * pages (each one is 64KB in size).
  11266. */
  11267. grow(delta: number): number;
  11268. }
  11269. /**
  11270. * A `WebAssembly.Module` object contains stateless WebAssembly code that has already been compiled
  11271. * by the browser — this can be efficiently shared with Workers, and instantiated multiple times.
  11272. *
  11273. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module)
  11274. *
  11275. * @category WASM
  11276. */
  11277. export class Module {
  11278. /** Creates a new `Module` object. */
  11279. constructor(bytes: BufferSource);
  11280. /**
  11281. * Given a `Module` and string, returns a copy of the contents of all custom sections in the
  11282. * module with the given string name.
  11283. */
  11284. static customSections(
  11285. moduleObject: Module,
  11286. sectionName: string,
  11287. ): ArrayBuffer[];
  11288. /** Given a `Module`, returns an array containing descriptions of all the declared exports. */
  11289. static exports(moduleObject: Module): ModuleExportDescriptor[];
  11290. /** Given a `Module`, returns an array containing descriptions of all the declared imports. */
  11291. static imports(moduleObject: Module): ModuleImportDescriptor[];
  11292. }
  11293. /**
  11294. * The `WebAssembly.RuntimeError` object is the error type that is thrown whenever WebAssembly
  11295. * specifies a trap.
  11296. *
  11297. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/RuntimeError)
  11298. *
  11299. * @category WASM
  11300. */
  11301. export class RuntimeError extends Error {
  11302. /** Creates a new `WebAssembly.RuntimeError` object. */
  11303. constructor(message?: string, options?: ErrorOptions);
  11304. }
  11305. /**
  11306. * The `WebAssembly.Table()` object is a JavaScript wrapper object — an array-like structure
  11307. * representing a WebAssembly Table, which stores function references. A table created by
  11308. * JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript
  11309. * and WebAssembly.
  11310. *
  11311. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table)
  11312. *
  11313. * @category WASM
  11314. */
  11315. export class Table {
  11316. /** Creates a new `Table` object. */
  11317. constructor(descriptor: TableDescriptor);
  11318. /** Returns the length of the table, i.e. the number of elements. */
  11319. readonly length: number;
  11320. /** Accessor function — gets the element stored at a given index. */
  11321. get(index: number): Function | null;
  11322. /** Increases the size of the `Table` instance by a specified number of elements. */
  11323. grow(delta: number): number;
  11324. /** Sets an element stored at a given index to a given value. */
  11325. set(index: number, value: Function | null): void;
  11326. }
  11327. /** The `GlobalDescriptor` describes the options you can pass to
  11328. * `new WebAssembly.Global()`.
  11329. *
  11330. * @category WASM
  11331. */
  11332. export interface GlobalDescriptor {
  11333. mutable?: boolean;
  11334. value: ValueType;
  11335. }
  11336. /** The `MemoryDescriptor` describes the options you can pass to
  11337. * `new WebAssembly.Memory()`.
  11338. *
  11339. * @category WASM
  11340. */
  11341. export interface MemoryDescriptor {
  11342. initial: number;
  11343. maximum?: number;
  11344. shared?: boolean;
  11345. }
  11346. /** A `ModuleExportDescriptor` is the description of a declared export in a
  11347. * `WebAssembly.Module`.
  11348. *
  11349. * @category WASM
  11350. */
  11351. export interface ModuleExportDescriptor {
  11352. kind: ImportExportKind;
  11353. name: string;
  11354. }
  11355. /** A `ModuleImportDescriptor` is the description of a declared import in a
  11356. * `WebAssembly.Module`.
  11357. *
  11358. * @category WASM
  11359. */
  11360. export interface ModuleImportDescriptor {
  11361. kind: ImportExportKind;
  11362. module: string;
  11363. name: string;
  11364. }
  11365. /** The `TableDescriptor` describes the options you can pass to
  11366. * `new WebAssembly.Table()`.
  11367. *
  11368. * @category WASM
  11369. */
  11370. export interface TableDescriptor {
  11371. element: TableKind;
  11372. initial: number;
  11373. maximum?: number;
  11374. }
  11375. /** The value returned from `WebAssembly.instantiate`.
  11376. *
  11377. * @category WASM
  11378. */
  11379. export interface WebAssemblyInstantiatedSource {
  11380. /* A `WebAssembly.Instance` object that contains all the exported WebAssembly functions. */
  11381. instance: Instance;
  11382. /**
  11383. * A `WebAssembly.Module` object representing the compiled WebAssembly module.
  11384. * This `Module` can be instantiated again, or shared via postMessage().
  11385. */
  11386. module: Module;
  11387. }
  11388. /** @category WASM */
  11389. export type ImportExportKind = "function" | "global" | "memory" | "table";
  11390. /** @category WASM */
  11391. export type TableKind = "anyfunc";
  11392. /** @category WASM */
  11393. export type ValueType = "f32" | "f64" | "i32" | "i64";
  11394. /** @category WASM */
  11395. export type ExportValue = Function | Global | Memory | Table;
  11396. /** @category WASM */
  11397. export type Exports = Record<string, ExportValue>;
  11398. /** @category WASM */
  11399. export type ImportValue = ExportValue | number;
  11400. /** @category WASM */
  11401. export type ModuleImports = Record<string, ImportValue>;
  11402. /** @category WASM */
  11403. export type Imports = Record<string, ModuleImports>;
  11404. /**
  11405. * The `WebAssembly.compile()` function compiles WebAssembly binary code into a
  11406. * `WebAssembly.Module` object. This function is useful if it is necessary to compile
  11407. * a module before it can be instantiated (otherwise, the `WebAssembly.instantiate()`
  11408. * function should be used).
  11409. *
  11410. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compile)
  11411. *
  11412. * @category WASM
  11413. */
  11414. export function compile(bytes: BufferSource): Promise<Module>;
  11415. /**
  11416. * The `WebAssembly.compileStreaming()` function compiles a `WebAssembly.Module`
  11417. * directly from a streamed underlying source. This function is useful if it is
  11418. * necessary to a compile a module before it can be instantiated (otherwise, the
  11419. * `WebAssembly.instantiateStreaming()` function should be used).
  11420. *
  11421. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compileStreaming)
  11422. *
  11423. * @category WASM
  11424. */
  11425. export function compileStreaming(
  11426. source: Response | Promise<Response>,
  11427. ): Promise<Module>;
  11428. /**
  11429. * The WebAssembly.instantiate() function allows you to compile and instantiate
  11430. * WebAssembly code.
  11431. *
  11432. * This overload takes the WebAssembly binary code, in the form of a typed
  11433. * array or ArrayBuffer, and performs both compilation and instantiation in one step.
  11434. * The returned Promise resolves to both a compiled WebAssembly.Module and its first
  11435. * WebAssembly.Instance.
  11436. *
  11437. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate)
  11438. *
  11439. * @category WASM
  11440. */
  11441. export function instantiate(
  11442. bytes: BufferSource,
  11443. importObject?: Imports,
  11444. ): Promise<WebAssemblyInstantiatedSource>;
  11445. /**
  11446. * The WebAssembly.instantiate() function allows you to compile and instantiate
  11447. * WebAssembly code.
  11448. *
  11449. * This overload takes an already-compiled WebAssembly.Module and returns
  11450. * a Promise that resolves to an Instance of that Module. This overload is useful
  11451. * if the Module has already been compiled.
  11452. *
  11453. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate)
  11454. *
  11455. * @category WASM
  11456. */
  11457. export function instantiate(
  11458. moduleObject: Module,
  11459. importObject?: Imports,
  11460. ): Promise<Instance>;
  11461. /**
  11462. * The `WebAssembly.instantiateStreaming()` function compiles and instantiates a
  11463. * WebAssembly module directly from a streamed underlying source. This is the most
  11464. * efficient, optimized way to load wasm code.
  11465. *
  11466. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming)
  11467. *
  11468. * @category WASM
  11469. */
  11470. export function instantiateStreaming(
  11471. response: Response | PromiseLike<Response>,
  11472. importObject?: Imports,
  11473. ): Promise<WebAssemblyInstantiatedSource>;
  11474. /**
  11475. * The `WebAssembly.validate()` function validates a given typed array of
  11476. * WebAssembly binary code, returning whether the bytes form a valid wasm
  11477. * module (`true`) or not (`false`).
  11478. *
  11479. * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/validate)
  11480. *
  11481. * @category WASM
  11482. */
  11483. export function validate(bytes: BufferSource): boolean;
  11484. }
  11485. /** Sets a timer which executes a function once after the delay (in milliseconds) elapses. Returns
  11486. * an id which may be used to cancel the timeout.
  11487. *
  11488. * ```ts
  11489. * setTimeout(() => { console.log('hello'); }, 500);
  11490. * ```
  11491. *
  11492. * @category Platform
  11493. */
  11494. declare function setTimeout(
  11495. /** callback function to execute when timer expires */
  11496. cb: (...args: any[]) => void,
  11497. /** delay in ms */
  11498. delay?: number,
  11499. /** arguments passed to callback function */
  11500. ...args: any[]
  11501. ): number;
  11502. /** Repeatedly calls a function , with a fixed time delay between each call.
  11503. *
  11504. * ```ts
  11505. * // Outputs 'hello' to the console every 500ms
  11506. * setInterval(() => { console.log('hello'); }, 500);
  11507. * ```
  11508. *
  11509. * @category Platform
  11510. */
  11511. declare function setInterval(
  11512. /** callback function to execute when timer expires */
  11513. cb: (...args: any[]) => void,
  11514. /** delay in ms */
  11515. delay?: number,
  11516. /** arguments passed to callback function */
  11517. ...args: any[]
  11518. ): number;
  11519. /** Cancels a timed, repeating action which was previously started by a call
  11520. * to `setInterval()`
  11521. *
  11522. * ```ts
  11523. * const id = setInterval(() => {console.log('hello');}, 500);
  11524. * // ...
  11525. * clearInterval(id);
  11526. * ```
  11527. *
  11528. * @category Platform
  11529. */
  11530. declare function clearInterval(id?: number): void;
  11531. /** Cancels a scheduled action initiated by `setTimeout()`
  11532. *
  11533. * ```ts
  11534. * const id = setTimeout(() => {console.log('hello');}, 500);
  11535. * // ...
  11536. * clearTimeout(id);
  11537. * ```
  11538. *
  11539. * @category Platform
  11540. */
  11541. declare function clearTimeout(id?: number): void;
  11542. /** @category Platform */
  11543. declare interface VoidFunction {
  11544. (): void;
  11545. }
  11546. /** A microtask is a short function which is executed after the function or
  11547. * module which created it exits and only if the JavaScript execution stack is
  11548. * empty, but before returning control to the event loop being used to drive the
  11549. * script's execution environment. This event loop may be either the main event
  11550. * loop or the event loop driving a web worker.
  11551. *
  11552. * ```ts
  11553. * queueMicrotask(() => { console.log('This event loop stack is complete'); });
  11554. * ```
  11555. *
  11556. * @category Platform
  11557. */
  11558. declare function queueMicrotask(func: VoidFunction): void;
  11559. /** Dispatches an event in the global scope, synchronously invoking any
  11560. * registered event listeners for this event in the appropriate order. Returns
  11561. * false if event is cancelable and at least one of the event handlers which
  11562. * handled this event called Event.preventDefault(). Otherwise it returns true.
  11563. *
  11564. * ```ts
  11565. * dispatchEvent(new Event('unload'));
  11566. * ```
  11567. *
  11568. * @category Events
  11569. */
  11570. declare function dispatchEvent(event: Event): boolean;
  11571. /** @category Platform */
  11572. declare interface DOMStringList {
  11573. /** Returns the number of strings in strings. */
  11574. readonly length: number;
  11575. /** Returns true if strings contains string, and false otherwise. */
  11576. contains(string: string): boolean;
  11577. /** Returns the string with index index from strings. */
  11578. item(index: number): string | null;
  11579. [index: number]: string;
  11580. }
  11581. /** @category Platform */
  11582. declare type BufferSource = ArrayBufferView | ArrayBuffer;
  11583. /** @category I/O */
  11584. declare var console: Console;
  11585. /** @category Events */
  11586. declare interface ErrorEventInit extends EventInit {
  11587. message?: string;
  11588. filename?: string;
  11589. lineno?: number;
  11590. colno?: number;
  11591. error?: any;
  11592. }
  11593. /** @category Events */
  11594. declare interface ErrorEvent extends Event {
  11595. readonly message: string;
  11596. readonly filename: string;
  11597. readonly lineno: number;
  11598. readonly colno: number;
  11599. readonly error: any;
  11600. }
  11601. /** @category Events */
  11602. declare var ErrorEvent: {
  11603. readonly prototype: ErrorEvent;
  11604. new (type: string, eventInitDict?: ErrorEventInit): ErrorEvent;
  11605. };
  11606. /** @category Events */
  11607. declare interface PromiseRejectionEventInit extends EventInit {
  11608. promise: Promise<any>;
  11609. reason?: any;
  11610. }
  11611. /** @category Events */
  11612. declare interface PromiseRejectionEvent extends Event {
  11613. readonly promise: Promise<any>;
  11614. readonly reason: any;
  11615. }
  11616. /** @category Events */
  11617. declare var PromiseRejectionEvent: {
  11618. readonly prototype: PromiseRejectionEvent;
  11619. new (
  11620. type: string,
  11621. eventInitDict?: PromiseRejectionEventInit,
  11622. ): PromiseRejectionEvent;
  11623. };
  11624. /** @category Workers */
  11625. declare interface AbstractWorkerEventMap {
  11626. "error": ErrorEvent;
  11627. }
  11628. /** @category Workers */
  11629. declare interface WorkerEventMap extends AbstractWorkerEventMap {
  11630. "message": MessageEvent;
  11631. "messageerror": MessageEvent;
  11632. }
  11633. /** @category Workers */
  11634. declare interface WorkerOptions {
  11635. type?: "classic" | "module";
  11636. name?: string;
  11637. }
  11638. /** @category Workers */
  11639. declare interface Worker extends EventTarget {
  11640. onerror: (this: Worker, e: ErrorEvent) => any | null;
  11641. onmessage: (this: Worker, e: MessageEvent) => any | null;
  11642. onmessageerror: (this: Worker, e: MessageEvent) => any | null;
  11643. postMessage(message: any, transfer: Transferable[]): void;
  11644. postMessage(message: any, options?: StructuredSerializeOptions): void;
  11645. addEventListener<K extends keyof WorkerEventMap>(
  11646. type: K,
  11647. listener: (this: Worker, ev: WorkerEventMap[K]) => any,
  11648. options?: boolean | AddEventListenerOptions,
  11649. ): void;
  11650. addEventListener(
  11651. type: string,
  11652. listener: EventListenerOrEventListenerObject,
  11653. options?: boolean | AddEventListenerOptions,
  11654. ): void;
  11655. removeEventListener<K extends keyof WorkerEventMap>(
  11656. type: K,
  11657. listener: (this: Worker, ev: WorkerEventMap[K]) => any,
  11658. options?: boolean | EventListenerOptions,
  11659. ): void;
  11660. removeEventListener(
  11661. type: string,
  11662. listener: EventListenerOrEventListenerObject,
  11663. options?: boolean | EventListenerOptions,
  11664. ): void;
  11665. terminate(): void;
  11666. }
  11667. /** @category Workers */
  11668. declare var Worker: {
  11669. readonly prototype: Worker;
  11670. new (specifier: string | URL, options?: WorkerOptions): Worker;
  11671. };
  11672. /** @category Performance */
  11673. declare type PerformanceEntryList = PerformanceEntry[];
  11674. /** @category Performance */
  11675. declare interface Performance extends EventTarget {
  11676. /** Returns a timestamp representing the start of the performance measurement. */
  11677. readonly timeOrigin: number;
  11678. /** Removes the stored timestamp with the associated name. */
  11679. clearMarks(markName?: string): void;
  11680. /** Removes stored timestamp with the associated name. */
  11681. clearMeasures(measureName?: string): void;
  11682. getEntries(): PerformanceEntryList;
  11683. getEntriesByName(name: string, type?: string): PerformanceEntryList;
  11684. getEntriesByType(type: string): PerformanceEntryList;
  11685. /** Stores a timestamp with the associated name (a "mark"). */
  11686. mark(markName: string, options?: PerformanceMarkOptions): PerformanceMark;
  11687. /** Stores the `DOMHighResTimeStamp` duration between two marks along with the
  11688. * associated name (a "measure"). */
  11689. measure(
  11690. measureName: string,
  11691. options?: PerformanceMeasureOptions,
  11692. ): PerformanceMeasure;
  11693. /** Stores the `DOMHighResTimeStamp` duration between two marks along with the
  11694. * associated name (a "measure"). */
  11695. measure(
  11696. measureName: string,
  11697. startMark?: string,
  11698. endMark?: string,
  11699. ): PerformanceMeasure;
  11700. /** Returns a current time from Deno's start in milliseconds.
  11701. *
  11702. * Use the permission flag `--allow-hrtime` to return a precise value.
  11703. *
  11704. * ```ts
  11705. * const t = performance.now();
  11706. * console.log(`${t} ms since start!`);
  11707. * ```
  11708. *
  11709. * @tags allow-hrtime
  11710. */
  11711. now(): number;
  11712. /** Returns a JSON representation of the performance object. */
  11713. toJSON(): any;
  11714. }
  11715. /** @category Performance */
  11716. declare var Performance: {
  11717. readonly prototype: Performance;
  11718. new (): never;
  11719. };
  11720. /** @category Performance */
  11721. declare var performance: Performance;
  11722. /** @category Performance */
  11723. declare interface PerformanceMarkOptions {
  11724. /** Metadata to be included in the mark. */
  11725. detail?: any;
  11726. /** Timestamp to be used as the mark time. */
  11727. startTime?: number;
  11728. }
  11729. /** @category Performance */
  11730. declare interface PerformanceMeasureOptions {
  11731. /** Metadata to be included in the measure. */
  11732. detail?: any;
  11733. /** Timestamp to be used as the start time or string to be used as start
  11734. * mark. */
  11735. start?: string | number;
  11736. /** Duration between the start and end times. */
  11737. duration?: number;
  11738. /** Timestamp to be used as the end time or string to be used as end mark. */
  11739. end?: string | number;
  11740. }
  11741. /** Encapsulates a single performance metric that is part of the performance
  11742. * timeline. A performance entry can be directly created by making a performance
  11743. * mark or measure (for example by calling the `.mark()` method) at an explicit
  11744. * point in an application.
  11745. *
  11746. * @category Performance
  11747. */
  11748. declare interface PerformanceEntry {
  11749. readonly duration: number;
  11750. readonly entryType: string;
  11751. readonly name: string;
  11752. readonly startTime: number;
  11753. toJSON(): any;
  11754. }
  11755. /** Encapsulates a single performance metric that is part of the performance
  11756. * timeline. A performance entry can be directly created by making a performance
  11757. * mark or measure (for example by calling the `.mark()` method) at an explicit
  11758. * point in an application.
  11759. *
  11760. * @category Performance
  11761. */
  11762. declare var PerformanceEntry: {
  11763. readonly prototype: PerformanceEntry;
  11764. new (): never;
  11765. };
  11766. /** `PerformanceMark` is an abstract interface for `PerformanceEntry` objects
  11767. * with an entryType of `"mark"`. Entries of this type are created by calling
  11768. * `performance.mark()` to add a named `DOMHighResTimeStamp` (the mark) to the
  11769. * performance timeline.
  11770. *
  11771. * @category Performance
  11772. */
  11773. declare interface PerformanceMark extends PerformanceEntry {
  11774. readonly detail: any;
  11775. readonly entryType: "mark";
  11776. }
  11777. /** `PerformanceMark` is an abstract interface for `PerformanceEntry` objects
  11778. * with an entryType of `"mark"`. Entries of this type are created by calling
  11779. * `performance.mark()` to add a named `DOMHighResTimeStamp` (the mark) to the
  11780. * performance timeline.
  11781. *
  11782. * @category Performance
  11783. */
  11784. declare var PerformanceMark: {
  11785. readonly prototype: PerformanceMark;
  11786. new (name: string, options?: PerformanceMarkOptions): PerformanceMark;
  11787. };
  11788. /** `PerformanceMeasure` is an abstract interface for `PerformanceEntry` objects
  11789. * with an entryType of `"measure"`. Entries of this type are created by calling
  11790. * `performance.measure()` to add a named `DOMHighResTimeStamp` (the measure)
  11791. * between two marks to the performance timeline.
  11792. *
  11793. * @category Performance
  11794. */
  11795. declare interface PerformanceMeasure extends PerformanceEntry {
  11796. readonly detail: any;
  11797. readonly entryType: "measure";
  11798. }
  11799. /** `PerformanceMeasure` is an abstract interface for `PerformanceEntry` objects
  11800. * with an entryType of `"measure"`. Entries of this type are created by calling
  11801. * `performance.measure()` to add a named `DOMHighResTimeStamp` (the measure)
  11802. * between two marks to the performance timeline.
  11803. *
  11804. * @category Performance
  11805. */
  11806. declare var PerformanceMeasure: {
  11807. readonly prototype: PerformanceMeasure;
  11808. new (): never;
  11809. };
  11810. /** @category Events */
  11811. declare interface CustomEventInit<T = any> extends EventInit {
  11812. detail?: T;
  11813. }
  11814. /** @category Events */
  11815. declare interface CustomEvent<T = any> extends Event {
  11816. /** Returns any custom data event was created with. Typically used for
  11817. * synthetic events. */
  11818. readonly detail: T;
  11819. }
  11820. /** @category Events */
  11821. declare var CustomEvent: {
  11822. readonly prototype: CustomEvent;
  11823. new <T>(typeArg: string, eventInitDict?: CustomEventInit<T>): CustomEvent<T>;
  11824. };
  11825. /** @category Platform */
  11826. declare interface ErrorConstructor {
  11827. /** See https://v8.dev/docs/stack-trace-api#stack-trace-collection-for-custom-exceptions. */
  11828. captureStackTrace(error: Object, constructor?: Function): void;
  11829. // TODO(nayeemrmn): Support `Error.prepareStackTrace()`. We currently use this
  11830. // internally in a way that makes it unavailable for users.
  11831. }
  11832. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  11833. // deno-lint-ignore-file no-var
  11834. /// <reference no-default-lib="true" />
  11835. /// <reference lib="esnext" />
  11836. /** @category Cache */
  11837. declare var caches: CacheStorage;
  11838. /** @category Cache */
  11839. declare interface CacheStorage {
  11840. /** Open a cache storage for the provided name. */
  11841. open(cacheName: string): Promise<Cache>;
  11842. /** Check if cache already exists for the provided name. */
  11843. has(cacheName: string): Promise<boolean>;
  11844. /** Delete cache storage for the provided name. */
  11845. delete(cacheName: string): Promise<boolean>;
  11846. }
  11847. /** @category Cache */
  11848. declare interface Cache {
  11849. /**
  11850. * Put the provided request/response into the cache.
  11851. *
  11852. * How is the API different from browsers?
  11853. * 1. You cannot match cache objects using by relative paths.
  11854. * 2. You cannot pass options like `ignoreVary`, `ignoreMethod`, `ignoreSearch`.
  11855. */
  11856. put(request: RequestInfo | URL, response: Response): Promise<void>;
  11857. /**
  11858. * Return cache object matching the provided request.
  11859. *
  11860. * How is the API different from browsers?
  11861. * 1. You cannot match cache objects using by relative paths.
  11862. * 2. You cannot pass options like `ignoreVary`, `ignoreMethod`, `ignoreSearch`.
  11863. */
  11864. match(
  11865. request: RequestInfo | URL,
  11866. options?: CacheQueryOptions,
  11867. ): Promise<Response | undefined>;
  11868. /**
  11869. * Delete cache object matching the provided request.
  11870. *
  11871. * How is the API different from browsers?
  11872. * 1. You cannot delete cache objects using by relative paths.
  11873. * 2. You cannot pass options like `ignoreVary`, `ignoreMethod`, `ignoreSearch`.
  11874. */
  11875. delete(
  11876. request: RequestInfo | URL,
  11877. options?: CacheQueryOptions,
  11878. ): Promise<boolean>;
  11879. }
  11880. /** @category Cache */
  11881. declare var Cache: {
  11882. readonly prototype: Cache;
  11883. new (): never;
  11884. };
  11885. /** @category Cache */
  11886. declare var CacheStorage: {
  11887. readonly prototype: CacheStorage;
  11888. new (): never;
  11889. };
  11890. /** @category Cache */
  11891. declare interface CacheQueryOptions {
  11892. ignoreMethod?: boolean;
  11893. ignoreSearch?: boolean;
  11894. ignoreVary?: boolean;
  11895. }
  11896. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  11897. /// <reference no-default-lib="true" />
  11898. /// <reference lib="deno.ns" />
  11899. /// <reference lib="deno.shared_globals" />
  11900. /// <reference lib="deno.webstorage" />
  11901. /// <reference lib="esnext" />
  11902. /// <reference lib="deno.cache" />
  11903. /** @category Platform */
  11904. declare interface WindowEventMap {
  11905. "error": ErrorEvent;
  11906. "unhandledrejection": PromiseRejectionEvent;
  11907. "rejectionhandled": PromiseRejectionEvent;
  11908. }
  11909. /** @category Platform */
  11910. declare interface Window extends EventTarget {
  11911. readonly window: Window & typeof globalThis;
  11912. readonly self: Window & typeof globalThis;
  11913. onerror: ((this: Window, ev: ErrorEvent) => any) | null;
  11914. onload: ((this: Window, ev: Event) => any) | null;
  11915. onbeforeunload: ((this: Window, ev: Event) => any) | null;
  11916. onunload: ((this: Window, ev: Event) => any) | null;
  11917. onunhandledrejection:
  11918. | ((this: Window, ev: PromiseRejectionEvent) => any)
  11919. | null;
  11920. onrejectionhandled:
  11921. | ((this: Window, ev: PromiseRejectionEvent) => any)
  11922. | null;
  11923. close: () => void;
  11924. readonly closed: boolean;
  11925. alert: (message?: string) => void;
  11926. confirm: (message?: string) => boolean;
  11927. prompt: (message?: string, defaultValue?: string) => string | null;
  11928. Deno: typeof Deno;
  11929. Navigator: typeof Navigator;
  11930. navigator: Navigator;
  11931. Location: typeof Location;
  11932. location: Location;
  11933. localStorage: Storage;
  11934. sessionStorage: Storage;
  11935. caches: CacheStorage;
  11936. name: string;
  11937. addEventListener<K extends keyof WindowEventMap>(
  11938. type: K,
  11939. listener: (
  11940. this: Window,
  11941. ev: WindowEventMap[K],
  11942. ) => any,
  11943. options?: boolean | AddEventListenerOptions,
  11944. ): void;
  11945. addEventListener(
  11946. type: string,
  11947. listener: EventListenerOrEventListenerObject,
  11948. options?: boolean | AddEventListenerOptions,
  11949. ): void;
  11950. removeEventListener<K extends keyof WindowEventMap>(
  11951. type: K,
  11952. listener: (
  11953. this: Window,
  11954. ev: WindowEventMap[K],
  11955. ) => any,
  11956. options?: boolean | EventListenerOptions,
  11957. ): void;
  11958. removeEventListener(
  11959. type: string,
  11960. listener: EventListenerOrEventListenerObject,
  11961. options?: boolean | EventListenerOptions,
  11962. ): void;
  11963. }
  11964. /** @category Platform */
  11965. declare var Window: {
  11966. readonly prototype: Window;
  11967. new (): never;
  11968. };
  11969. /** @category Platform */
  11970. declare var window: Window & typeof globalThis;
  11971. /** @category Platform */
  11972. declare var self: Window & typeof globalThis;
  11973. /** @category Platform */
  11974. declare var closed: boolean;
  11975. /** @category Platform */
  11976. declare function close(): void;
  11977. /** @category Events */
  11978. declare var onerror: ((this: Window, ev: ErrorEvent) => any) | null;
  11979. /** @category Events */
  11980. declare var onload: ((this: Window, ev: Event) => any) | null;
  11981. /** @category Events */
  11982. declare var onbeforeunload: ((this: Window, ev: Event) => any) | null;
  11983. /** @category Events */
  11984. declare var onunload: ((this: Window, ev: Event) => any) | null;
  11985. /** @category Events */
  11986. declare var onunhandledrejection:
  11987. | ((this: Window, ev: PromiseRejectionEvent) => any)
  11988. | null;
  11989. /** @category Storage */
  11990. declare var localStorage: Storage;
  11991. /** @category Storage */
  11992. declare var sessionStorage: Storage;
  11993. /** @category Cache */
  11994. declare var caches: CacheStorage;
  11995. /** @category Platform */
  11996. declare interface Navigator {
  11997. readonly gpu: GPU;
  11998. readonly hardwareConcurrency: number;
  11999. readonly userAgent: string;
  12000. readonly language: string;
  12001. readonly languages: string[];
  12002. }
  12003. /** @category Platform */
  12004. declare var Navigator: {
  12005. readonly prototype: Navigator;
  12006. new (): never;
  12007. };
  12008. /** @category Platform */
  12009. declare var navigator: Navigator;
  12010. /**
  12011. * Shows the given message and waits for the enter key pressed.
  12012. *
  12013. * If the stdin is not interactive, it does nothing.
  12014. *
  12015. * @category Platform
  12016. *
  12017. * @param message
  12018. */
  12019. declare function alert(message?: string): void;
  12020. /**
  12021. * Shows the given message and waits for the answer. Returns the user's answer as boolean.
  12022. *
  12023. * Only `y` and `Y` are considered as true.
  12024. *
  12025. * If the stdin is not interactive, it returns false.
  12026. *
  12027. * @category Platform
  12028. *
  12029. * @param message
  12030. */
  12031. declare function confirm(message?: string): boolean;
  12032. /**
  12033. * Shows the given message and waits for the user's input. Returns the user's input as string.
  12034. *
  12035. * If the default value is given and the user inputs the empty string, then it returns the given
  12036. * default value.
  12037. *
  12038. * If the default value is not given and the user inputs the empty string, it returns the empty
  12039. * string.
  12040. *
  12041. * If the stdin is not interactive, it returns null.
  12042. *
  12043. * @category Platform
  12044. *
  12045. * @param message
  12046. * @param defaultValue
  12047. */
  12048. declare function prompt(message?: string, defaultValue?: string): string | null;
  12049. /** Registers an event listener in the global scope, which will be called
  12050. * synchronously whenever the event `type` is dispatched.
  12051. *
  12052. * ```ts
  12053. * addEventListener('unload', () => { console.log('All finished!'); });
  12054. * ...
  12055. * dispatchEvent(new Event('unload'));
  12056. * ```
  12057. *
  12058. * @category Events
  12059. */
  12060. declare function addEventListener<
  12061. K extends keyof WindowEventMap,
  12062. >(
  12063. type: K,
  12064. listener: (this: Window, ev: WindowEventMap[K]) => any,
  12065. options?: boolean | AddEventListenerOptions,
  12066. ): void;
  12067. /** @category Events */
  12068. declare function addEventListener(
  12069. type: string,
  12070. listener: EventListenerOrEventListenerObject,
  12071. options?: boolean | AddEventListenerOptions,
  12072. ): void;
  12073. /** Remove a previously registered event listener from the global scope
  12074. *
  12075. * ```ts
  12076. * const listener = () => { console.log('hello'); };
  12077. * addEventListener('load', listener);
  12078. * removeEventListener('load', listener);
  12079. * ```
  12080. *
  12081. * @category Events
  12082. */
  12083. declare function removeEventListener<
  12084. K extends keyof WindowEventMap,
  12085. >(
  12086. type: K,
  12087. listener: (this: Window, ev: WindowEventMap[K]) => any,
  12088. options?: boolean | EventListenerOptions,
  12089. ): void;
  12090. /** @category Events */
  12091. declare function removeEventListener(
  12092. type: string,
  12093. listener: EventListenerOrEventListenerObject,
  12094. options?: boolean | EventListenerOptions,
  12095. ): void;
  12096. // TODO(nayeemrmn): Move this to `extensions/web` where its implementation is.
  12097. // The types there must first be split into window, worker and global types.
  12098. /** The location (URL) of the object it is linked to. Changes done on it are
  12099. * reflected on the object it relates to. Accessible via
  12100. * `globalThis.location`.
  12101. *
  12102. * @category Platform
  12103. */
  12104. declare interface Location {
  12105. /** Returns a DOMStringList object listing the origins of the ancestor
  12106. * browsing contexts, from the parent browsing context to the top-level
  12107. * browsing context.
  12108. *
  12109. * Always empty in Deno. */
  12110. readonly ancestorOrigins: DOMStringList;
  12111. /** Returns the Location object's URL's fragment (includes leading "#" if
  12112. * non-empty).
  12113. *
  12114. * Cannot be set in Deno. */
  12115. hash: string;
  12116. /** Returns the Location object's URL's host and port (if different from the
  12117. * default port for the scheme).
  12118. *
  12119. * Cannot be set in Deno. */
  12120. host: string;
  12121. /** Returns the Location object's URL's host.
  12122. *
  12123. * Cannot be set in Deno. */
  12124. hostname: string;
  12125. /** Returns the Location object's URL.
  12126. *
  12127. * Cannot be set in Deno. */
  12128. href: string;
  12129. toString(): string;
  12130. /** Returns the Location object's URL's origin. */
  12131. readonly origin: string;
  12132. /** Returns the Location object's URL's path.
  12133. *
  12134. * Cannot be set in Deno. */
  12135. pathname: string;
  12136. /** Returns the Location object's URL's port.
  12137. *
  12138. * Cannot be set in Deno. */
  12139. port: string;
  12140. /** Returns the Location object's URL's scheme.
  12141. *
  12142. * Cannot be set in Deno. */
  12143. protocol: string;
  12144. /** Returns the Location object's URL's query (includes leading "?" if
  12145. * non-empty).
  12146. *
  12147. * Cannot be set in Deno. */
  12148. search: string;
  12149. /** Navigates to the given URL.
  12150. *
  12151. * Cannot be set in Deno. */
  12152. assign(url: string): void;
  12153. /** Reloads the current page.
  12154. *
  12155. * Disabled in Deno. */
  12156. reload(): void;
  12157. /** @deprecated */
  12158. reload(forcedReload: boolean): void;
  12159. /** Removes the current page from the session history and navigates to the
  12160. * given URL.
  12161. *
  12162. * Disabled in Deno. */
  12163. replace(url: string): void;
  12164. }
  12165. // TODO(nayeemrmn): Move this to `extensions/web` where its implementation is.
  12166. // The types there must first be split into window, worker and global types.
  12167. /** The location (URL) of the object it is linked to. Changes done on it are
  12168. * reflected on the object it relates to. Accessible via
  12169. * `globalThis.location`.
  12170. *
  12171. * @category Platform
  12172. */
  12173. declare var Location: {
  12174. readonly prototype: Location;
  12175. new (): never;
  12176. };
  12177. // TODO(nayeemrmn): Move this to `extensions/web` where its implementation is.
  12178. // The types there must first be split into window, worker and global types.
  12179. /** @category Platform */
  12180. declare var location: Location;
  12181. /** @category Platform */
  12182. declare var name: string;
  12183. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
  12184. /// <reference no-default-lib="true" />
  12185. /// <reference lib="deno.ns" />
  12186. /// <reference lib="deno.broadcast_channel" />
  12187. /// <reference lib="deno.webgpu" />
  12188. /// <reference lib="esnext" />
  12189. /// <reference lib="es2022.intl" />
  12190. declare namespace Deno {
  12191. export {}; // stop default export type behavior
  12192. /** Information for a HTTP request.
  12193. *
  12194. * @category HTTP Server
  12195. * @experimental
  12196. */
  12197. export interface ServeHandlerInfo {
  12198. /** The remote address of the connection. */
  12199. remoteAddr: Deno.NetAddr;
  12200. /** The completion promise */
  12201. completed: Promise<void>;
  12202. }
  12203. /** **UNSTABLE**: New API, yet to be vetted.
  12204. *
  12205. * Retrieve the process umask. If `mask` is provided, sets the process umask.
  12206. * This call always returns what the umask was before the call.
  12207. *
  12208. * ```ts
  12209. * console.log(Deno.umask()); // e.g. 18 (0o022)
  12210. * const prevUmaskValue = Deno.umask(0o077); // e.g. 18 (0o022)
  12211. * console.log(Deno.umask()); // e.g. 63 (0o077)
  12212. * ```
  12213. *
  12214. * This API is under consideration to determine if permissions are required to
  12215. * call it.
  12216. *
  12217. * *Note*: This API is not implemented on Windows
  12218. *
  12219. * @category File System
  12220. * @experimental
  12221. */
  12222. export function umask(mask?: number): number;
  12223. /** **UNSTABLE**: New API, yet to be vetted.
  12224. *
  12225. * All plain number types for interfacing with foreign functions.
  12226. *
  12227. * @category FFI
  12228. * @experimental
  12229. */
  12230. export type NativeNumberType =
  12231. | "u8"
  12232. | "i8"
  12233. | "u16"
  12234. | "i16"
  12235. | "u32"
  12236. | "i32"
  12237. | "f32"
  12238. | "f64";
  12239. /** **UNSTABLE**: New API, yet to be vetted.
  12240. *
  12241. * All BigInt number types for interfacing with foreign functions.
  12242. *
  12243. * @category FFI
  12244. * @experimental
  12245. */
  12246. export type NativeBigIntType =
  12247. | "u64"
  12248. | "i64"
  12249. | "usize"
  12250. | "isize";
  12251. /** **UNSTABLE**: New API, yet to be vetted.
  12252. *
  12253. * The native boolean type for interfacing to foreign functions.
  12254. *
  12255. * @category FFI
  12256. * @experimental
  12257. */
  12258. export type NativeBooleanType = "bool";
  12259. /** **UNSTABLE**: New API, yet to be vetted.
  12260. *
  12261. * The native pointer type for interfacing to foreign functions.
  12262. *
  12263. * @category FFI
  12264. * @experimental
  12265. */
  12266. export type NativePointerType = "pointer";
  12267. /** **UNSTABLE**: New API, yet to be vetted.
  12268. *
  12269. * The native buffer type for interfacing to foreign functions.
  12270. *
  12271. * @category FFI
  12272. * @experimental
  12273. */
  12274. export type NativeBufferType = "buffer";
  12275. /** **UNSTABLE**: New API, yet to be vetted.
  12276. *
  12277. * The native function type for interfacing with foreign functions.
  12278. *
  12279. * @category FFI
  12280. * @experimental
  12281. */
  12282. export type NativeFunctionType = "function";
  12283. /** **UNSTABLE**: New API, yet to be vetted.
  12284. *
  12285. * The native void type for interfacing with foreign functions.
  12286. *
  12287. * @category FFI
  12288. * @experimental
  12289. */
  12290. export type NativeVoidType = "void";
  12291. /** **UNSTABLE**: New API, yet to be vetted.
  12292. *
  12293. * The native struct type for interfacing with foreign functions.
  12294. *
  12295. * @category FFI
  12296. * @experimental
  12297. */
  12298. export type NativeStructType = { readonly struct: readonly NativeType[] };
  12299. /**
  12300. * @category FFI
  12301. * @experimental
  12302. */
  12303. export const brand: unique symbol;
  12304. /**
  12305. * @category FFI
  12306. * @experimental
  12307. */
  12308. export type NativeU8Enum<T extends number> = "u8" & { [brand]: T };
  12309. /**
  12310. * @category FFI
  12311. * @experimental
  12312. */
  12313. export type NativeI8Enum<T extends number> = "i8" & { [brand]: T };
  12314. /**
  12315. * @category FFI
  12316. * @experimental
  12317. */
  12318. export type NativeU16Enum<T extends number> = "u16" & { [brand]: T };
  12319. /**
  12320. * @category FFI
  12321. * @experimental
  12322. */
  12323. export type NativeI16Enum<T extends number> = "i16" & { [brand]: T };
  12324. /**
  12325. * @category FFI
  12326. * @experimental
  12327. */
  12328. export type NativeU32Enum<T extends number> = "u32" & { [brand]: T };
  12329. /**
  12330. * @category FFI
  12331. * @experimental
  12332. */
  12333. export type NativeI32Enum<T extends number> = "i32" & { [brand]: T };
  12334. /**
  12335. * @category FFI
  12336. * @experimental
  12337. */
  12338. export type NativeTypedPointer<T extends PointerObject> = "pointer" & {
  12339. [brand]: T;
  12340. };
  12341. /**
  12342. * @category FFI
  12343. * @experimental
  12344. */
  12345. export type NativeTypedFunction<T extends UnsafeCallbackDefinition> =
  12346. & "function"
  12347. & {
  12348. [brand]: T;
  12349. };
  12350. /** **UNSTABLE**: New API, yet to be vetted.
  12351. *
  12352. * All supported types for interfacing with foreign functions.
  12353. *
  12354. * @category FFI
  12355. * @experimental
  12356. */
  12357. export type NativeType =
  12358. | NativeNumberType
  12359. | NativeBigIntType
  12360. | NativeBooleanType
  12361. | NativePointerType
  12362. | NativeBufferType
  12363. | NativeFunctionType
  12364. | NativeStructType;
  12365. /** **UNSTABLE**: New API, yet to be vetted.
  12366. *
  12367. * @category FFI
  12368. * @experimental
  12369. */
  12370. export type NativeResultType = NativeType | NativeVoidType;
  12371. /** **UNSTABLE**: New API, yet to be vetted.
  12372. *
  12373. * Type conversion for foreign symbol parameters and unsafe callback return
  12374. * types.
  12375. *
  12376. * @category FFI
  12377. * @experimental
  12378. */
  12379. export type ToNativeType<T extends NativeType = NativeType> = T extends
  12380. NativeStructType ? BufferSource
  12381. : T extends NativeNumberType ? T extends NativeU8Enum<infer U> ? U
  12382. : T extends NativeI8Enum<infer U> ? U
  12383. : T extends NativeU16Enum<infer U> ? U
  12384. : T extends NativeI16Enum<infer U> ? U
  12385. : T extends NativeU32Enum<infer U> ? U
  12386. : T extends NativeI32Enum<infer U> ? U
  12387. : number
  12388. : T extends NativeBigIntType ? bigint
  12389. : T extends NativeBooleanType ? boolean
  12390. : T extends NativePointerType
  12391. ? T extends NativeTypedPointer<infer U> ? U | null : PointerValue
  12392. : T extends NativeFunctionType
  12393. ? T extends NativeTypedFunction<infer U> ? PointerValue<U> | null
  12394. : PointerValue
  12395. : T extends NativeBufferType ? BufferSource | null
  12396. : never;
  12397. /** **UNSTABLE**: New API, yet to be vetted.
  12398. *
  12399. * Type conversion for unsafe callback return types.
  12400. *
  12401. * @category FFI
  12402. * @experimental
  12403. */
  12404. export type ToNativeResultType<
  12405. T extends NativeResultType = NativeResultType,
  12406. > = T extends NativeStructType ? BufferSource
  12407. : T extends NativeNumberType ? T extends NativeU8Enum<infer U> ? U
  12408. : T extends NativeI8Enum<infer U> ? U
  12409. : T extends NativeU16Enum<infer U> ? U
  12410. : T extends NativeI16Enum<infer U> ? U
  12411. : T extends NativeU32Enum<infer U> ? U
  12412. : T extends NativeI32Enum<infer U> ? U
  12413. : number
  12414. : T extends NativeBigIntType ? bigint
  12415. : T extends NativeBooleanType ? boolean
  12416. : T extends NativePointerType
  12417. ? T extends NativeTypedPointer<infer U> ? U | null : PointerValue
  12418. : T extends NativeFunctionType
  12419. ? T extends NativeTypedFunction<infer U> ? PointerObject<U> | null
  12420. : PointerValue
  12421. : T extends NativeBufferType ? BufferSource | null
  12422. : T extends NativeVoidType ? void
  12423. : never;
  12424. /** **UNSTABLE**: New API, yet to be vetted.
  12425. *
  12426. * A utility type for conversion of parameter types of foreign functions.
  12427. *
  12428. * @category FFI
  12429. * @experimental
  12430. */
  12431. export type ToNativeParameterTypes<T extends readonly NativeType[]> =
  12432. //
  12433. [(T[number])[]] extends [T] ? ToNativeType<T[number]>[]
  12434. : [readonly (T[number])[]] extends [T]
  12435. ? readonly ToNativeType<T[number]>[]
  12436. : T extends readonly [...NativeType[]] ? {
  12437. [K in keyof T]: ToNativeType<T[K]>;
  12438. }
  12439. : never;
  12440. /** **UNSTABLE**: New API, yet to be vetted.
  12441. *
  12442. * Type conversion for foreign symbol return types and unsafe callback
  12443. * parameters.
  12444. *
  12445. * @category FFI
  12446. * @experimental
  12447. */
  12448. export type FromNativeType<T extends NativeType = NativeType> = T extends
  12449. NativeStructType ? Uint8Array
  12450. : T extends NativeNumberType ? T extends NativeU8Enum<infer U> ? U
  12451. : T extends NativeI8Enum<infer U> ? U
  12452. : T extends NativeU16Enum<infer U> ? U
  12453. : T extends NativeI16Enum<infer U> ? U
  12454. : T extends NativeU32Enum<infer U> ? U
  12455. : T extends NativeI32Enum<infer U> ? U
  12456. : number
  12457. : T extends NativeBigIntType ? bigint
  12458. : T extends NativeBooleanType ? boolean
  12459. : T extends NativePointerType
  12460. ? T extends NativeTypedPointer<infer U> ? U | null : PointerValue
  12461. : T extends NativeBufferType ? PointerValue
  12462. : T extends NativeFunctionType
  12463. ? T extends NativeTypedFunction<infer U> ? PointerObject<U> | null
  12464. : PointerValue
  12465. : never;
  12466. /** **UNSTABLE**: New API, yet to be vetted.
  12467. *
  12468. * Type conversion for foreign symbol return types.
  12469. *
  12470. * @category FFI
  12471. * @experimental
  12472. */
  12473. export type FromNativeResultType<
  12474. T extends NativeResultType = NativeResultType,
  12475. > = T extends NativeStructType ? Uint8Array
  12476. : T extends NativeNumberType ? T extends NativeU8Enum<infer U> ? U
  12477. : T extends NativeI8Enum<infer U> ? U
  12478. : T extends NativeU16Enum<infer U> ? U
  12479. : T extends NativeI16Enum<infer U> ? U
  12480. : T extends NativeU32Enum<infer U> ? U
  12481. : T extends NativeI32Enum<infer U> ? U
  12482. : number
  12483. : T extends NativeBigIntType ? bigint
  12484. : T extends NativeBooleanType ? boolean
  12485. : T extends NativePointerType
  12486. ? T extends NativeTypedPointer<infer U> ? U | null : PointerValue
  12487. : T extends NativeBufferType ? PointerValue
  12488. : T extends NativeFunctionType
  12489. ? T extends NativeTypedFunction<infer U> ? PointerObject<U> | null
  12490. : PointerValue
  12491. : T extends NativeVoidType ? void
  12492. : never;
  12493. /** **UNSTABLE**: New API, yet to be vetted.
  12494. *
  12495. * @category FFI
  12496. * @experimental
  12497. */
  12498. export type FromNativeParameterTypes<
  12499. T extends readonly NativeType[],
  12500. > =
  12501. //
  12502. [(T[number])[]] extends [T] ? FromNativeType<T[number]>[]
  12503. : [readonly (T[number])[]] extends [T]
  12504. ? readonly FromNativeType<T[number]>[]
  12505. : T extends readonly [...NativeType[]] ? {
  12506. [K in keyof T]: FromNativeType<T[K]>;
  12507. }
  12508. : never;
  12509. /** **UNSTABLE**: New API, yet to be vetted.
  12510. *
  12511. * The interface for a foreign function as defined by its parameter and result
  12512. * types.
  12513. *
  12514. * @category FFI
  12515. * @experimental
  12516. */
  12517. export interface ForeignFunction<
  12518. Parameters extends readonly NativeType[] = readonly NativeType[],
  12519. Result extends NativeResultType = NativeResultType,
  12520. NonBlocking extends boolean = boolean,
  12521. > {
  12522. /** Name of the symbol.
  12523. *
  12524. * Defaults to the key name in symbols object. */
  12525. name?: string;
  12526. /** The parameters of the foreign function. */
  12527. parameters: Parameters;
  12528. /** The result (return value) of the foreign function. */
  12529. result: Result;
  12530. /** When `true`, function calls will run on a dedicated blocking thread and
  12531. * will return a `Promise` resolving to the `result`. */
  12532. nonblocking?: NonBlocking;
  12533. /** When `true`, dlopen will not fail if the symbol is not found.
  12534. * Instead, the symbol will be set to `null`.
  12535. *
  12536. * @default {false} */
  12537. optional?: boolean;
  12538. }
  12539. /** **UNSTABLE**: New API, yet to be vetted.
  12540. *
  12541. * @category FFI
  12542. * @experimental
  12543. */
  12544. export interface ForeignStatic<Type extends NativeType = NativeType> {
  12545. /** Name of the symbol, defaults to the key name in symbols object. */
  12546. name?: string;
  12547. /** The type of the foreign static value. */
  12548. type: Type;
  12549. /** When `true`, dlopen will not fail if the symbol is not found.
  12550. * Instead, the symbol will be set to `null`.
  12551. *
  12552. * @default {false} */
  12553. optional?: boolean;
  12554. }
  12555. /** **UNSTABLE**: New API, yet to be vetted.
  12556. *
  12557. * A foreign library interface descriptor.
  12558. *
  12559. * @category FFI
  12560. * @experimental
  12561. */
  12562. export interface ForeignLibraryInterface {
  12563. [name: string]: ForeignFunction | ForeignStatic;
  12564. }
  12565. /** **UNSTABLE**: New API, yet to be vetted.
  12566. *
  12567. * A utility type that infers a foreign symbol.
  12568. *
  12569. * @category FFI
  12570. * @experimental
  12571. */
  12572. export type StaticForeignSymbol<T extends ForeignFunction | ForeignStatic> =
  12573. T extends ForeignFunction ? FromForeignFunction<T>
  12574. : T extends ForeignStatic ? FromNativeType<T["type"]>
  12575. : never;
  12576. /** **UNSTABLE**: New API, yet to be vetted.
  12577. *
  12578. * @category FFI
  12579. * @experimental
  12580. */
  12581. export type FromForeignFunction<T extends ForeignFunction> =
  12582. T["parameters"] extends readonly [] ? () => StaticForeignSymbolReturnType<T>
  12583. : (
  12584. ...args: ToNativeParameterTypes<T["parameters"]>
  12585. ) => StaticForeignSymbolReturnType<T>;
  12586. /** **UNSTABLE**: New API, yet to be vetted.
  12587. *
  12588. * @category FFI
  12589. * @experimental
  12590. */
  12591. export type StaticForeignSymbolReturnType<T extends ForeignFunction> =
  12592. ConditionalAsync<T["nonblocking"], FromNativeResultType<T["result"]>>;
  12593. /** **UNSTABLE**: New API, yet to be vetted.
  12594. *
  12595. * @category FFI
  12596. * @experimental
  12597. */
  12598. export type ConditionalAsync<IsAsync extends boolean | undefined, T> =
  12599. IsAsync extends true ? Promise<T> : T;
  12600. /** **UNSTABLE**: New API, yet to be vetted.
  12601. *
  12602. * A utility type that infers a foreign library interface.
  12603. *
  12604. * @category FFI
  12605. * @experimental
  12606. */
  12607. export type StaticForeignLibraryInterface<T extends ForeignLibraryInterface> =
  12608. {
  12609. [K in keyof T]: T[K]["optional"] extends true
  12610. ? StaticForeignSymbol<T[K]> | null
  12611. : StaticForeignSymbol<T[K]>;
  12612. };
  12613. /** **UNSTABLE**: New API, yet to be vetted.
  12614. *
  12615. * A non-null pointer, represented as an object
  12616. * at runtime. The object's prototype is `null`
  12617. * and cannot be changed. The object cannot be
  12618. * assigned to either and is thus entirely read-only.
  12619. *
  12620. * To interact with memory through a pointer use the
  12621. * {@linkcode UnsafePointerView} class. To create a
  12622. * pointer from an address or the get the address of
  12623. * a pointer use the static methods of the
  12624. * {@linkcode UnsafePointer} class.
  12625. *
  12626. * @category FFI
  12627. * @experimental
  12628. */
  12629. export type PointerObject<T = unknown> = { [brand]: T };
  12630. /** **UNSTABLE**: New API, yet to be vetted.
  12631. *
  12632. * Pointers are represented either with a {@linkcode PointerObject}
  12633. * object or a `null` if the pointer is null.
  12634. *
  12635. * @category FFI
  12636. * @experimental
  12637. */
  12638. export type PointerValue<T = unknown> = null | PointerObject<T>;
  12639. /** **UNSTABLE**: New API, yet to be vetted.
  12640. *
  12641. * A collection of static functions for interacting with pointer objects.
  12642. *
  12643. * @category FFI
  12644. * @experimental
  12645. */
  12646. export class UnsafePointer {
  12647. /** Create a pointer from a numeric value. This one is <i>really</i> dangerous! */
  12648. static create<T = unknown>(value: bigint): PointerValue<T>;
  12649. /** Returns `true` if the two pointers point to the same address. */
  12650. static equals<T = unknown>(a: PointerValue<T>, b: PointerValue<T>): boolean;
  12651. /** Return the direct memory pointer to the typed array in memory. */
  12652. static of<T = unknown>(
  12653. value: Deno.UnsafeCallback | BufferSource,
  12654. ): PointerValue<T>;
  12655. /** Return a new pointer offset from the original by `offset` bytes. */
  12656. static offset<T = unknown>(
  12657. value: PointerObject,
  12658. offset: number,
  12659. ): PointerValue<T>;
  12660. /** Get the numeric value of a pointer */
  12661. static value(value: PointerValue): bigint;
  12662. }
  12663. /** **UNSTABLE**: New API, yet to be vetted.
  12664. *
  12665. * An unsafe pointer view to a memory location as specified by the `pointer`
  12666. * value. The `UnsafePointerView` API follows the standard built in interface
  12667. * {@linkcode DataView} for accessing the underlying types at an memory
  12668. * location (numbers, strings and raw bytes).
  12669. *
  12670. * @category FFI
  12671. * @experimental
  12672. */
  12673. export class UnsafePointerView {
  12674. constructor(pointer: PointerObject);
  12675. pointer: PointerObject;
  12676. /** Gets a boolean at the specified byte offset from the pointer. */
  12677. getBool(offset?: number): boolean;
  12678. /** Gets an unsigned 8-bit integer at the specified byte offset from the
  12679. * pointer. */
  12680. getUint8(offset?: number): number;
  12681. /** Gets a signed 8-bit integer at the specified byte offset from the
  12682. * pointer. */
  12683. getInt8(offset?: number): number;
  12684. /** Gets an unsigned 16-bit integer at the specified byte offset from the
  12685. * pointer. */
  12686. getUint16(offset?: number): number;
  12687. /** Gets a signed 16-bit integer at the specified byte offset from the
  12688. * pointer. */
  12689. getInt16(offset?: number): number;
  12690. /** Gets an unsigned 32-bit integer at the specified byte offset from the
  12691. * pointer. */
  12692. getUint32(offset?: number): number;
  12693. /** Gets a signed 32-bit integer at the specified byte offset from the
  12694. * pointer. */
  12695. getInt32(offset?: number): number;
  12696. /** Gets an unsigned 64-bit integer at the specified byte offset from the
  12697. * pointer. */
  12698. getBigUint64(offset?: number): bigint;
  12699. /** Gets a signed 64-bit integer at the specified byte offset from the
  12700. * pointer. */
  12701. getBigInt64(offset?: number): bigint;
  12702. /** Gets a signed 32-bit float at the specified byte offset from the
  12703. * pointer. */
  12704. getFloat32(offset?: number): number;
  12705. /** Gets a signed 64-bit float at the specified byte offset from the
  12706. * pointer. */
  12707. getFloat64(offset?: number): number;
  12708. /** Gets a pointer at the specified byte offset from the pointer */
  12709. getPointer<T = unknown>(offset?: number): PointerValue<T>;
  12710. /** Gets a C string (`null` terminated string) at the specified byte offset
  12711. * from the pointer. */
  12712. getCString(offset?: number): string;
  12713. /** Gets a C string (`null` terminated string) at the specified byte offset
  12714. * from the specified pointer. */
  12715. static getCString(
  12716. pointer: PointerObject,
  12717. offset?: number,
  12718. ): string;
  12719. /** Gets an `ArrayBuffer` of length `byteLength` at the specified byte
  12720. * offset from the pointer. */
  12721. getArrayBuffer(byteLength: number, offset?: number): ArrayBuffer;
  12722. /** Gets an `ArrayBuffer` of length `byteLength` at the specified byte
  12723. * offset from the specified pointer. */
  12724. static getArrayBuffer(
  12725. pointer: PointerObject,
  12726. byteLength: number,
  12727. offset?: number,
  12728. ): ArrayBuffer;
  12729. /** Copies the memory of the pointer into a typed array.
  12730. *
  12731. * Length is determined from the typed array's `byteLength`.
  12732. *
  12733. * Also takes optional byte offset from the pointer. */
  12734. copyInto(destination: BufferSource, offset?: number): void;
  12735. /** Copies the memory of the specified pointer into a typed array.
  12736. *
  12737. * Length is determined from the typed array's `byteLength`.
  12738. *
  12739. * Also takes optional byte offset from the pointer. */
  12740. static copyInto(
  12741. pointer: PointerObject,
  12742. destination: BufferSource,
  12743. offset?: number,
  12744. ): void;
  12745. }
  12746. /** **UNSTABLE**: New API, yet to be vetted.
  12747. *
  12748. * An unsafe pointer to a function, for calling functions that are not present
  12749. * as symbols.
  12750. *
  12751. * @category FFI
  12752. * @experimental
  12753. */
  12754. export class UnsafeFnPointer<const Fn extends ForeignFunction> {
  12755. /** The pointer to the function. */
  12756. pointer: PointerObject<Fn>;
  12757. /** The definition of the function. */
  12758. definition: Fn;
  12759. constructor(pointer: PointerObject<NoInfer<Fn>>, definition: Fn);
  12760. /** @deprecated Properly type {@linkcode pointer} using {@linkcode NativeTypedFunction} or {@linkcode UnsafeCallbackDefinition} types. */
  12761. constructor(pointer: PointerObject, definition: Fn);
  12762. /** Call the foreign function. */
  12763. call: FromForeignFunction<Fn>;
  12764. }
  12765. /** **UNSTABLE**: New API, yet to be vetted.
  12766. *
  12767. * Definition of a unsafe callback function.
  12768. *
  12769. * @category FFI
  12770. * @experimental
  12771. */
  12772. export interface UnsafeCallbackDefinition<
  12773. Parameters extends readonly NativeType[] = readonly NativeType[],
  12774. Result extends NativeResultType = NativeResultType,
  12775. > {
  12776. /** The parameters of the callbacks. */
  12777. parameters: Parameters;
  12778. /** The current result of the callback. */
  12779. result: Result;
  12780. }
  12781. /** **UNSTABLE**: New API, yet to be vetted.
  12782. *
  12783. * An unsafe callback function.
  12784. *
  12785. * @category FFI
  12786. * @experimental
  12787. */
  12788. export type UnsafeCallbackFunction<
  12789. Parameters extends readonly NativeType[] = readonly NativeType[],
  12790. Result extends NativeResultType = NativeResultType,
  12791. > = Parameters extends readonly [] ? () => ToNativeResultType<Result> : (
  12792. ...args: FromNativeParameterTypes<Parameters>
  12793. ) => ToNativeResultType<Result>;
  12794. /** **UNSTABLE**: New API, yet to be vetted.
  12795. *
  12796. * An unsafe function pointer for passing JavaScript functions as C function
  12797. * pointers to foreign function calls.
  12798. *
  12799. * The function pointer remains valid until the `close()` method is called.
  12800. *
  12801. * All `UnsafeCallback` are always thread safe in that they can be called from
  12802. * foreign threads without crashing. However, they do not wake up the Deno event
  12803. * loop by default.
  12804. *
  12805. * If a callback is to be called from foreign threads, use the `threadSafe()`
  12806. * static constructor or explicitly call `ref()` to have the callback wake up
  12807. * the Deno event loop when called from foreign threads. This also stops
  12808. * Deno's process from exiting while the callback still exists and is not
  12809. * unref'ed.
  12810. *
  12811. * Use `deref()` to then allow Deno's process to exit. Calling `deref()` on
  12812. * a ref'ed callback does not stop it from waking up the Deno event loop when
  12813. * called from foreign threads.
  12814. *
  12815. * @category FFI
  12816. * @experimental
  12817. */
  12818. export class UnsafeCallback<
  12819. const Definition extends UnsafeCallbackDefinition =
  12820. UnsafeCallbackDefinition,
  12821. > {
  12822. constructor(
  12823. definition: Definition,
  12824. callback: UnsafeCallbackFunction<
  12825. Definition["parameters"],
  12826. Definition["result"]
  12827. >,
  12828. );
  12829. /** The pointer to the unsafe callback. */
  12830. readonly pointer: PointerObject<Definition>;
  12831. /** The definition of the unsafe callback. */
  12832. readonly definition: Definition;
  12833. /** The callback function. */
  12834. readonly callback: UnsafeCallbackFunction<
  12835. Definition["parameters"],
  12836. Definition["result"]
  12837. >;
  12838. /**
  12839. * Creates an {@linkcode UnsafeCallback} and calls `ref()` once to allow it to
  12840. * wake up the Deno event loop when called from foreign threads.
  12841. *
  12842. * This also stops Deno's process from exiting while the callback still
  12843. * exists and is not unref'ed.
  12844. */
  12845. static threadSafe<
  12846. Definition extends UnsafeCallbackDefinition = UnsafeCallbackDefinition,
  12847. >(
  12848. definition: Definition,
  12849. callback: UnsafeCallbackFunction<
  12850. Definition["parameters"],
  12851. Definition["result"]
  12852. >,
  12853. ): UnsafeCallback<Definition>;
  12854. /**
  12855. * Increments the callback's reference counting and returns the new
  12856. * reference count.
  12857. *
  12858. * After `ref()` has been called, the callback always wakes up the
  12859. * Deno event loop when called from foreign threads.
  12860. *
  12861. * If the callback's reference count is non-zero, it keeps Deno's
  12862. * process from exiting.
  12863. */
  12864. ref(): number;
  12865. /**
  12866. * Decrements the callback's reference counting and returns the new
  12867. * reference count.
  12868. *
  12869. * Calling `unref()` does not stop a callback from waking up the Deno
  12870. * event loop when called from foreign threads.
  12871. *
  12872. * If the callback's reference counter is zero, it no longer keeps
  12873. * Deno's process from exiting.
  12874. */
  12875. unref(): number;
  12876. /**
  12877. * Removes the C function pointer associated with this instance.
  12878. *
  12879. * Continuing to use the instance or the C function pointer after closing
  12880. * the `UnsafeCallback` will lead to errors and crashes.
  12881. *
  12882. * Calling this method sets the callback's reference counting to zero,
  12883. * stops the callback from waking up the Deno event loop when called from
  12884. * foreign threads and no longer keeps Deno's process from exiting.
  12885. */
  12886. close(): void;
  12887. }
  12888. /** **UNSTABLE**: New API, yet to be vetted.
  12889. *
  12890. * A dynamic library resource. Use {@linkcode Deno.dlopen} to load a dynamic
  12891. * library and return this interface.
  12892. *
  12893. * @category FFI
  12894. * @experimental
  12895. */
  12896. export interface DynamicLibrary<S extends ForeignLibraryInterface> {
  12897. /** All of the registered library along with functions for calling them. */
  12898. symbols: StaticForeignLibraryInterface<S>;
  12899. /** Removes the pointers associated with the library symbols.
  12900. *
  12901. * Continuing to use symbols that are part of the library will lead to
  12902. * errors and crashes.
  12903. *
  12904. * Calling this method will also immediately set any references to zero and
  12905. * will no longer keep Deno's process from exiting.
  12906. */
  12907. close(): void;
  12908. }
  12909. /** **UNSTABLE**: New API, yet to be vetted.
  12910. *
  12911. * Opens an external dynamic library and registers symbols, making foreign
  12912. * functions available to be called.
  12913. *
  12914. * Requires `allow-ffi` permission. Loading foreign dynamic libraries can in
  12915. * theory bypass all of the sandbox permissions. While it is a separate
  12916. * permission users should acknowledge in practice that is effectively the
  12917. * same as running with the `allow-all` permission.
  12918. *
  12919. * @example Given a C library which exports a foreign function named `add()`
  12920. *
  12921. * ```ts
  12922. * // Determine library extension based on
  12923. * // your OS.
  12924. * let libSuffix = "";
  12925. * switch (Deno.build.os) {
  12926. * case "windows":
  12927. * libSuffix = "dll";
  12928. * break;
  12929. * case "darwin":
  12930. * libSuffix = "dylib";
  12931. * break;
  12932. * default:
  12933. * libSuffix = "so";
  12934. * break;
  12935. * }
  12936. *
  12937. * const libName = `./libadd.${libSuffix}`;
  12938. * // Open library and define exported symbols
  12939. * const dylib = Deno.dlopen(
  12940. * libName,
  12941. * {
  12942. * "add": { parameters: ["isize", "isize"], result: "isize" },
  12943. * } as const,
  12944. * );
  12945. *
  12946. * // Call the symbol `add`
  12947. * const result = dylib.symbols.add(35n, 34n); // 69n
  12948. *
  12949. * console.log(`Result from external addition of 35 and 34: ${result}`);
  12950. * ```
  12951. *
  12952. * @tags allow-ffi
  12953. * @category FFI
  12954. * @experimental
  12955. */
  12956. export function dlopen<const S extends ForeignLibraryInterface>(
  12957. filename: string | URL,
  12958. symbols: S,
  12959. ): DynamicLibrary<S>;
  12960. /** **UNSTABLE**: New API, yet to be vetted.
  12961. *
  12962. * Creates a presentable WebGPU surface from given window and
  12963. * display handles.
  12964. *
  12965. * The parameters correspond to the table below:
  12966. *
  12967. * | system | winHandle | displayHandle |
  12968. * | ----------------- | ------------- | --------------- |
  12969. * | "cocoa" (macOS) | `NSView*` | - |
  12970. * | "win32" (Windows) | `HWND` | `HINSTANCE` |
  12971. * | "x11" (Linux) | Xlib `Window` | Xlib `Display*` |
  12972. * | "wayland" (Linux) | `wl_surface*` | `wl_display*` |
  12973. *
  12974. * @category GPU
  12975. * @experimental
  12976. */
  12977. export class UnsafeWindowSurface {
  12978. constructor(
  12979. system: "cocoa" | "win32" | "x11" | "wayland",
  12980. windowHandle: Deno.PointerValue<unknown>,
  12981. displayHandle: Deno.PointerValue<unknown>,
  12982. );
  12983. getContext(context: "webgpu"): GPUCanvasContext;
  12984. present(): void;
  12985. }
  12986. /** **UNSTABLE**: New API, yet to be vetted.
  12987. *
  12988. * These are unstable options which can be used with {@linkcode Deno.run}.
  12989. *
  12990. * @category Sub Process
  12991. * @experimental
  12992. */
  12993. export interface UnstableRunOptions extends RunOptions {
  12994. /** If `true`, clears the environment variables before executing the
  12995. * sub-process.
  12996. *
  12997. * @default {false} */
  12998. clearEnv?: boolean;
  12999. /** For POSIX systems, sets the group ID for the sub process. */
  13000. gid?: number;
  13001. /** For POSIX systems, sets the user ID for the sub process. */
  13002. uid?: number;
  13003. }
  13004. /** **UNSTABLE**: New API, yet to be vetted.
  13005. *
  13006. * Spawns new subprocess. RunOptions must contain at a minimum the `opt.cmd`,
  13007. * an array of program arguments, the first of which is the binary.
  13008. *
  13009. * ```ts
  13010. * const p = Deno.run({
  13011. * cmd: ["curl", "https://example.com"],
  13012. * });
  13013. * const status = await p.status();
  13014. * ```
  13015. *
  13016. * Subprocess uses same working directory as parent process unless `opt.cwd`
  13017. * is specified.
  13018. *
  13019. * Environmental variables from parent process can be cleared using `opt.clearEnv`.
  13020. * Doesn't guarantee that only `opt.env` variables are present,
  13021. * as the OS may set environmental variables for processes.
  13022. *
  13023. * Environmental variables for subprocess can be specified using `opt.env`
  13024. * mapping.
  13025. *
  13026. * `opt.uid` sets the child process’s user ID. This translates to a setuid call
  13027. * in the child process. Failure in the setuid call will cause the spawn to fail.
  13028. *
  13029. * `opt.gid` is similar to `opt.uid`, but sets the group ID of the child process.
  13030. * This has the same semantics as the uid field.
  13031. *
  13032. * By default subprocess inherits stdio of parent process. To change
  13033. * this this, `opt.stdin`, `opt.stdout`, and `opt.stderr` can be set
  13034. * independently to a resource ID (_rid_) of an open file, `"inherit"`,
  13035. * `"piped"`, or `"null"`:
  13036. *
  13037. * - _number_: the resource ID of an open file/resource. This allows you to
  13038. * read or write to a file.
  13039. * - `"inherit"`: The default if unspecified. The subprocess inherits from the
  13040. * parent.
  13041. * - `"piped"`: A new pipe should be arranged to connect the parent and child
  13042. * sub-process.
  13043. * - `"null"`: This stream will be ignored. This is the equivalent of attaching
  13044. * the stream to `/dev/null`.
  13045. *
  13046. * Details of the spawned process are returned as an instance of
  13047. * {@linkcode Deno.Process}.
  13048. *
  13049. * Requires `allow-run` permission.
  13050. *
  13051. * @tags allow-run
  13052. * @category Sub Process
  13053. * @experimental
  13054. */
  13055. export function run<T extends UnstableRunOptions = UnstableRunOptions>(
  13056. opt: T,
  13057. ): Process<T>;
  13058. /** **UNSTABLE**: New API, yet to be vetted.
  13059. *
  13060. * A custom `HttpClient` for use with {@linkcode fetch} function. This is
  13061. * designed to allow custom certificates or proxies to be used with `fetch()`.
  13062. *
  13063. * @example ```ts
  13064. * const caCert = await Deno.readTextFile("./ca.pem");
  13065. * const client = Deno.createHttpClient({ caCerts: [ caCert ] });
  13066. * const req = await fetch("https://myserver.com", { client });
  13067. * ```
  13068. *
  13069. * @category Fetch
  13070. * @experimental
  13071. */
  13072. export interface HttpClient extends Disposable {
  13073. /** Close the HTTP client. */
  13074. close(): void;
  13075. }
  13076. /** **UNSTABLE**: New API, yet to be vetted.
  13077. *
  13078. * The options used when creating a {@linkcode Deno.HttpClient}.
  13079. *
  13080. * @category Fetch
  13081. * @experimental
  13082. */
  13083. export interface CreateHttpClientOptions {
  13084. /** A list of root certificates that will be used in addition to the
  13085. * default root certificates to verify the peer's certificate.
  13086. *
  13087. * Must be in PEM format. */
  13088. caCerts?: string[];
  13089. /** A HTTP proxy to use for new connections. */
  13090. proxy?: Proxy;
  13091. /** Sets the maximum numer of idle connections per host allowed in the pool. */
  13092. poolMaxIdlePerHost?: number;
  13093. /** Set an optional timeout for idle sockets being kept-alive.
  13094. * Set to false to disable the timeout. */
  13095. poolIdleTimeout?: number | false;
  13096. /**
  13097. * Whether HTTP/1.1 is allowed or not.
  13098. *
  13099. * @default {true}
  13100. */
  13101. http1?: boolean;
  13102. /** Whether HTTP/2 is allowed or not.
  13103. *
  13104. * @default {true}
  13105. */
  13106. http2?: boolean;
  13107. /** Whether setting the host header is allowed or not.
  13108. *
  13109. * @default {false}
  13110. */
  13111. allowHost?: boolean;
  13112. }
  13113. /** **UNSTABLE**: New API, yet to be vetted.
  13114. *
  13115. * The definition of a proxy when specifying
  13116. * {@linkcode Deno.CreateHttpClientOptions}.
  13117. *
  13118. * @category Fetch
  13119. * @experimental
  13120. */
  13121. export interface Proxy {
  13122. /** The string URL of the proxy server to use. */
  13123. url: string;
  13124. /** The basic auth credentials to be used against the proxy server. */
  13125. basicAuth?: BasicAuth;
  13126. }
  13127. /** **UNSTABLE**: New API, yet to be vetted.
  13128. *
  13129. * Basic authentication credentials to be used with a {@linkcode Deno.Proxy}
  13130. * server when specifying {@linkcode Deno.CreateHttpClientOptions}.
  13131. *
  13132. * @category Fetch
  13133. * @experimental
  13134. */
  13135. export interface BasicAuth {
  13136. /** The username to be used against the proxy server. */
  13137. username: string;
  13138. /** The password to be used against the proxy server. */
  13139. password: string;
  13140. }
  13141. /** **UNSTABLE**: New API, yet to be vetted.
  13142. *
  13143. * Create a custom HttpClient to use with {@linkcode fetch}. This is an
  13144. * extension of the web platform Fetch API which allows Deno to use custom
  13145. * TLS certificates and connect via a proxy while using `fetch()`.
  13146. *
  13147. * @example ```ts
  13148. * const caCert = await Deno.readTextFile("./ca.pem");
  13149. * const client = Deno.createHttpClient({ caCerts: [ caCert ] });
  13150. * const response = await fetch("https://myserver.com", { client });
  13151. * ```
  13152. *
  13153. * @example ```ts
  13154. * const client = Deno.createHttpClient({
  13155. * proxy: { url: "http://myproxy.com:8080" }
  13156. * });
  13157. * const response = await fetch("https://myserver.com", { client });
  13158. * ```
  13159. *
  13160. * @category Fetch
  13161. * @experimental
  13162. */
  13163. export function createHttpClient(
  13164. options: CreateHttpClientOptions,
  13165. ): HttpClient;
  13166. /** **UNSTABLE**: New API, yet to be vetted.
  13167. *
  13168. * Create a custom HttpClient to use with {@linkcode fetch}. This is an
  13169. * extension of the web platform Fetch API which allows Deno to use custom
  13170. * TLS certificates and connect via a proxy while using `fetch()`.
  13171. *
  13172. * @example ```ts
  13173. * const caCert = await Deno.readTextFile("./ca.pem");
  13174. * // Load a client key and certificate that we'll use to connect
  13175. * const key = await Deno.readTextFile("./key.key");
  13176. * const cert = await Deno.readTextFile("./cert.crt");
  13177. * const client = Deno.createHttpClient({ caCerts: [ caCert ], key, cert });
  13178. * const response = await fetch("https://myserver.com", { client });
  13179. * ```
  13180. *
  13181. * @category Fetch
  13182. * @experimental
  13183. */
  13184. export function createHttpClient(
  13185. options: CreateHttpClientOptions & TlsCertifiedKeyOptions,
  13186. ): HttpClient;
  13187. /** **UNSTABLE**: New API, yet to be vetted.
  13188. *
  13189. * Represents membership of a IPv4 multicast group.
  13190. *
  13191. * @category Network
  13192. * @experimental
  13193. */
  13194. export interface MulticastV4Membership {
  13195. /** Leaves the multicast group. */
  13196. leave: () => Promise<void>;
  13197. /** Sets the multicast loopback option. If enabled, multicast packets will be looped back to the local socket. */
  13198. setLoopback: (loopback: boolean) => Promise<void>;
  13199. /** Sets the time-to-live of outgoing multicast packets for this socket. */
  13200. setTTL: (ttl: number) => Promise<void>;
  13201. }
  13202. /** **UNSTABLE**: New API, yet to be vetted.
  13203. *
  13204. * Represents membership of a IPv6 multicast group.
  13205. *
  13206. * @category Network
  13207. * @experimental
  13208. */
  13209. export interface MulticastV6Membership {
  13210. /** Leaves the multicast group. */
  13211. leave: () => Promise<void>;
  13212. /** Sets the multicast loopback option. If enabled, multicast packets will be looped back to the local socket. */
  13213. setLoopback: (loopback: boolean) => Promise<void>;
  13214. }
  13215. /** **UNSTABLE**: New API, yet to be vetted.
  13216. *
  13217. * A generic transport listener for message-oriented protocols.
  13218. *
  13219. * @category Network
  13220. * @experimental
  13221. */
  13222. export interface DatagramConn extends AsyncIterable<[Uint8Array, Addr]> {
  13223. /** Joins an IPv4 multicast group. */
  13224. joinMulticastV4(
  13225. address: string,
  13226. networkInterface: string,
  13227. ): Promise<MulticastV4Membership>;
  13228. /** Joins an IPv6 multicast group. */
  13229. joinMulticastV6(
  13230. address: string,
  13231. networkInterface: number,
  13232. ): Promise<MulticastV6Membership>;
  13233. /** Waits for and resolves to the next message to the instance.
  13234. *
  13235. * Messages are received in the format of a tuple containing the data array
  13236. * and the address information.
  13237. */
  13238. receive(p?: Uint8Array): Promise<[Uint8Array, Addr]>;
  13239. /** Sends a message to the target via the connection. The method resolves
  13240. * with the number of bytes sent. */
  13241. send(p: Uint8Array, addr: Addr): Promise<number>;
  13242. /** Close closes the socket. Any pending message promises will be rejected
  13243. * with errors. */
  13244. close(): void;
  13245. /** Return the address of the instance. */
  13246. readonly addr: Addr;
  13247. [Symbol.asyncIterator](): AsyncIterableIterator<[Uint8Array, Addr]>;
  13248. }
  13249. /**
  13250. * @category Network
  13251. * @experimental
  13252. */
  13253. export interface TcpListenOptions extends ListenOptions {
  13254. /** When `true` the SO_REUSEPORT flag will be set on the listener. This
  13255. * allows multiple processes to listen on the same address and port.
  13256. *
  13257. * On Linux this will cause the kernel to distribute incoming connections
  13258. * across the different processes that are listening on the same address and
  13259. * port.
  13260. *
  13261. * This flag is only supported on Linux. It is silently ignored on other
  13262. * platforms.
  13263. *
  13264. * @default {false} */
  13265. reusePort?: boolean;
  13266. }
  13267. /** **UNSTABLE**: New API, yet to be vetted.
  13268. *
  13269. * Unstable options which can be set when opening a datagram listener via
  13270. * {@linkcode Deno.listenDatagram}.
  13271. *
  13272. * @category Network
  13273. * @experimental
  13274. */
  13275. export interface UdpListenOptions extends ListenOptions {
  13276. /** When `true` the specified address will be reused, even if another
  13277. * process has already bound a socket on it. This effectively steals the
  13278. * socket from the listener.
  13279. *
  13280. * @default {false} */
  13281. reuseAddress?: boolean;
  13282. /** When `true`, sent multicast packets will be looped back to the local socket.
  13283. *
  13284. * @default {false} */
  13285. loopback?: boolean;
  13286. }
  13287. /** **UNSTABLE**: New API, yet to be vetted.
  13288. *
  13289. * Listen announces on the local transport address.
  13290. *
  13291. * ```ts
  13292. * const listener1 = Deno.listenDatagram({
  13293. * port: 80,
  13294. * transport: "udp"
  13295. * });
  13296. * const listener2 = Deno.listenDatagram({
  13297. * hostname: "golang.org",
  13298. * port: 80,
  13299. * transport: "udp"
  13300. * });
  13301. * ```
  13302. *
  13303. * Requires `allow-net` permission.
  13304. *
  13305. * @tags allow-net
  13306. * @category Network
  13307. * @experimental
  13308. */
  13309. export function listenDatagram(
  13310. options: UdpListenOptions & { transport: "udp" },
  13311. ): DatagramConn;
  13312. /** **UNSTABLE**: New API, yet to be vetted.
  13313. *
  13314. * Listen announces on the local transport address.
  13315. *
  13316. * ```ts
  13317. * const listener = Deno.listenDatagram({
  13318. * path: "/foo/bar.sock",
  13319. * transport: "unixpacket"
  13320. * });
  13321. * ```
  13322. *
  13323. * Requires `allow-read` and `allow-write` permission.
  13324. *
  13325. * @tags allow-read, allow-write
  13326. * @category Network
  13327. * @experimental
  13328. */
  13329. export function listenDatagram(
  13330. options: UnixListenOptions & { transport: "unixpacket" },
  13331. ): DatagramConn;
  13332. /** **UNSTABLE**: New API, yet to be vetted.
  13333. *
  13334. * Acquire an advisory file-system lock for the provided file.
  13335. *
  13336. * @param [exclusive=false]
  13337. * @category File System
  13338. * @experimental
  13339. */
  13340. export function flock(rid: number, exclusive?: boolean): Promise<void>;
  13341. /** **UNSTABLE**: New API, yet to be vetted.
  13342. *
  13343. * Acquire an advisory file-system lock synchronously for the provided file.
  13344. *
  13345. * @param [exclusive=false]
  13346. * @category File System
  13347. * @experimental
  13348. */
  13349. export function flockSync(rid: number, exclusive?: boolean): void;
  13350. /** **UNSTABLE**: New API, yet to be vetted.
  13351. *
  13352. * Release an advisory file-system lock for the provided file.
  13353. *
  13354. * @category File System
  13355. * @experimental
  13356. */
  13357. export function funlock(rid: number): Promise<void>;
  13358. /** **UNSTABLE**: New API, yet to be vetted.
  13359. *
  13360. * Release an advisory file-system lock for the provided file synchronously.
  13361. *
  13362. * @category File System
  13363. * @experimental
  13364. */
  13365. export function funlockSync(rid: number): void;
  13366. /** **UNSTABLE**: New API, yet to be vetted.
  13367. *
  13368. * Open a new {@linkcode Deno.Kv} connection to persist data.
  13369. *
  13370. * When a path is provided, the database will be persisted to disk at that
  13371. * path. Read and write access to the file is required.
  13372. *
  13373. * When no path is provided, the database will be opened in a default path for
  13374. * the current script. This location is persistent across script runs and is
  13375. * keyed on the origin storage key (the same key that is used to determine
  13376. * `localStorage` persistence). More information about the origin storage key
  13377. * can be found in the Deno Manual.
  13378. *
  13379. * @tags allow-read, allow-write
  13380. * @category Cloud
  13381. * @experimental
  13382. */
  13383. export function openKv(path?: string): Promise<Deno.Kv>;
  13384. /** **UNSTABLE**: New API, yet to be vetted.
  13385. *
  13386. * CronScheduleExpression is used as the type of `minute`, `hour`,
  13387. * `dayOfMonth`, `month`, and `dayOfWeek` in {@linkcode CronSchedule}.
  13388. * @category Cloud
  13389. * @experimental
  13390. */
  13391. export type CronScheduleExpression = number | { exact: number | number[] } | {
  13392. start?: number;
  13393. end?: number;
  13394. every?: number;
  13395. };
  13396. /** **UNSTABLE**: New API, yet to be vetted.
  13397. *
  13398. * CronSchedule is the interface used for JSON format
  13399. * cron `schedule`.
  13400. * @category Cloud
  13401. * @experimental
  13402. */
  13403. export interface CronSchedule {
  13404. minute?: CronScheduleExpression;
  13405. hour?: CronScheduleExpression;
  13406. dayOfMonth?: CronScheduleExpression;
  13407. month?: CronScheduleExpression;
  13408. dayOfWeek?: CronScheduleExpression;
  13409. }
  13410. /** **UNSTABLE**: New API, yet to be vetted.
  13411. *
  13412. * Create a cron job that will periodically execute the provided handler
  13413. * callback based on the specified schedule.
  13414. *
  13415. * ```ts
  13416. * Deno.cron("sample cron", "20 * * * *", () => {
  13417. * console.log("cron job executed");
  13418. * });
  13419. * ```
  13420. *
  13421. * ```ts
  13422. * Deno.cron("sample cron", { hour: { every: 6 } }, () => {
  13423. * console.log("cron job executed");
  13424. * });
  13425. * ```
  13426. *
  13427. * `schedule` can be a string in the Unix cron format or in JSON format
  13428. * as specified by interface {@linkcode CronSchedule}, where time is specified
  13429. * using UTC time zone.
  13430. *
  13431. * @category Cloud
  13432. * @experimental
  13433. */
  13434. export function cron(
  13435. name: string,
  13436. schedule: string | CronSchedule,
  13437. handler: () => Promise<void> | void,
  13438. ): Promise<void>;
  13439. /** **UNSTABLE**: New API, yet to be vetted.
  13440. *
  13441. * Create a cron job that will periodically execute the provided handler
  13442. * callback based on the specified schedule.
  13443. *
  13444. * ```ts
  13445. * Deno.cron("sample cron", "20 * * * *", {
  13446. * backoffSchedule: [10, 20]
  13447. * }, () => {
  13448. * console.log("cron job executed");
  13449. * });
  13450. * ```
  13451. *
  13452. * `schedule` can be a string in the Unix cron format or in JSON format
  13453. * as specified by interface {@linkcode CronSchedule}, where time is specified
  13454. * using UTC time zone.
  13455. *
  13456. * `backoffSchedule` option can be used to specify the retry policy for failed
  13457. * executions. Each element in the array represents the number of milliseconds
  13458. * to wait before retrying the execution. For example, `[1000, 5000, 10000]`
  13459. * means that a failed execution will be retried at most 3 times, with 1
  13460. * second, 5 seconds, and 10 seconds delay between each retry.
  13461. *
  13462. * @category Cloud
  13463. * @experimental
  13464. */
  13465. export function cron(
  13466. name: string,
  13467. schedule: string | CronSchedule,
  13468. options: { backoffSchedule?: number[]; signal?: AbortSignal },
  13469. handler: () => Promise<void> | void,
  13470. ): Promise<void>;
  13471. /** **UNSTABLE**: New API, yet to be vetted.
  13472. *
  13473. * A key to be persisted in a {@linkcode Deno.Kv}. A key is a sequence
  13474. * of {@linkcode Deno.KvKeyPart}s.
  13475. *
  13476. * Keys are ordered lexicographically by their parts. The first part is the
  13477. * most significant, and the last part is the least significant. The order of
  13478. * the parts is determined by both the type and the value of the part. The
  13479. * relative significance of the types can be found in documentation for the
  13480. * {@linkcode Deno.KvKeyPart} type.
  13481. *
  13482. * Keys have a maximum size of 2048 bytes serialized. If the size of the key
  13483. * exceeds this limit, an error will be thrown on the operation that this key
  13484. * was passed to.
  13485. *
  13486. * @category Cloud
  13487. * @experimental
  13488. */
  13489. export type KvKey = readonly KvKeyPart[];
  13490. /** **UNSTABLE**: New API, yet to be vetted.
  13491. *
  13492. * A single part of a {@linkcode Deno.KvKey}. Parts are ordered
  13493. * lexicographically, first by their type, and within a given type by their
  13494. * value.
  13495. *
  13496. * The ordering of types is as follows:
  13497. *
  13498. * 1. `Uint8Array`
  13499. * 2. `string`
  13500. * 3. `number`
  13501. * 4. `bigint`
  13502. * 5. `boolean`
  13503. *
  13504. * Within a given type, the ordering is as follows:
  13505. *
  13506. * - `Uint8Array` is ordered by the byte ordering of the array
  13507. * - `string` is ordered by the byte ordering of the UTF-8 encoding of the
  13508. * string
  13509. * - `number` is ordered following this pattern: `-NaN`
  13510. * < `-Infinity` < `-100.0` < `-1.0` < -`0.5` < `-0.0` < `0.0` < `0.5`
  13511. * < `1.0` < `100.0` < `Infinity` < `NaN`
  13512. * - `bigint` is ordered by mathematical ordering, with the largest negative
  13513. * number being the least first value, and the largest positive number
  13514. * being the last value
  13515. * - `boolean` is ordered by `false` < `true`
  13516. *
  13517. * This means that the part `1.0` (a number) is ordered before the part `2.0`
  13518. * (also a number), but is greater than the part `0n` (a bigint), because
  13519. * `1.0` is a number and `0n` is a bigint, and type ordering has precedence
  13520. * over the ordering of values within a type.
  13521. *
  13522. * @category Cloud
  13523. * @experimental
  13524. */
  13525. export type KvKeyPart =
  13526. | Uint8Array
  13527. | string
  13528. | number
  13529. | bigint
  13530. | boolean
  13531. | symbol;
  13532. /** **UNSTABLE**: New API, yet to be vetted.
  13533. *
  13534. * Consistency level of a KV operation.
  13535. *
  13536. * - `strong` - This operation must be strongly-consistent.
  13537. * - `eventual` - Eventually-consistent behavior is allowed.
  13538. *
  13539. * @category Cloud
  13540. * @experimental
  13541. */
  13542. export type KvConsistencyLevel = "strong" | "eventual";
  13543. /** **UNSTABLE**: New API, yet to be vetted.
  13544. *
  13545. * A selector that selects the range of data returned by a list operation on a
  13546. * {@linkcode Deno.Kv}.
  13547. *
  13548. * The selector can either be a prefix selector or a range selector. A prefix
  13549. * selector selects all keys that start with the given prefix (optionally
  13550. * starting at a given key). A range selector selects all keys that are
  13551. * lexicographically between the given start and end keys.
  13552. *
  13553. * @category Cloud
  13554. * @experimental
  13555. */
  13556. export type KvListSelector =
  13557. | { prefix: KvKey }
  13558. | { prefix: KvKey; start: KvKey }
  13559. | { prefix: KvKey; end: KvKey }
  13560. | { start: KvKey; end: KvKey };
  13561. /** **UNSTABLE**: New API, yet to be vetted.
  13562. *
  13563. * A mutation to a key in a {@linkcode Deno.Kv}. A mutation is a
  13564. * combination of a key, a value, and a type. The type determines how the
  13565. * mutation is applied to the key.
  13566. *
  13567. * - `set` - Sets the value of the key to the given value, overwriting any
  13568. * existing value. Optionally an `expireIn` option can be specified to
  13569. * set a time-to-live (TTL) for the key. The TTL is specified in
  13570. * milliseconds, and the key will be deleted from the database at earliest
  13571. * after the specified number of milliseconds have elapsed. Once the
  13572. * specified duration has passed, the key may still be visible for some
  13573. * additional time. If the `expireIn` option is not specified, the key will
  13574. * not expire.
  13575. * - `delete` - Deletes the key from the database. The mutation is a no-op if
  13576. * the key does not exist.
  13577. * - `sum` - Adds the given value to the existing value of the key. Both the
  13578. * value specified in the mutation, and any existing value must be of type
  13579. * `Deno.KvU64`. If the key does not exist, the value is set to the given
  13580. * value (summed with 0). If the result of the sum overflows an unsigned
  13581. * 64-bit integer, the result is wrapped around.
  13582. * - `max` - Sets the value of the key to the maximum of the existing value
  13583. * and the given value. Both the value specified in the mutation, and any
  13584. * existing value must be of type `Deno.KvU64`. If the key does not exist,
  13585. * the value is set to the given value.
  13586. * - `min` - Sets the value of the key to the minimum of the existing value
  13587. * and the given value. Both the value specified in the mutation, and any
  13588. * existing value must be of type `Deno.KvU64`. If the key does not exist,
  13589. * the value is set to the given value.
  13590. *
  13591. * @category Cloud
  13592. * @experimental
  13593. */
  13594. export type KvMutation =
  13595. & { key: KvKey }
  13596. & (
  13597. | { type: "set"; value: unknown; expireIn?: number }
  13598. | { type: "delete" }
  13599. | { type: "sum"; value: KvU64 }
  13600. | { type: "max"; value: KvU64 }
  13601. | { type: "min"; value: KvU64 }
  13602. );
  13603. /** **UNSTABLE**: New API, yet to be vetted.
  13604. *
  13605. * An iterator over a range of data entries in a {@linkcode Deno.Kv}.
  13606. *
  13607. * The cursor getter returns the cursor that can be used to resume the
  13608. * iteration from the current position in the future.
  13609. *
  13610. * @category Cloud
  13611. * @experimental
  13612. */
  13613. export class KvListIterator<T> implements AsyncIterableIterator<KvEntry<T>> {
  13614. /**
  13615. * Returns the cursor of the current position in the iteration. This cursor
  13616. * can be used to resume the iteration from the current position in the
  13617. * future by passing it to the `cursor` option of the `list` method.
  13618. */
  13619. get cursor(): string;
  13620. next(): Promise<IteratorResult<KvEntry<T>, undefined>>;
  13621. [Symbol.asyncIterator](): AsyncIterableIterator<KvEntry<T>>;
  13622. }
  13623. /** **UNSTABLE**: New API, yet to be vetted.
  13624. *
  13625. * A versioned pair of key and value in a {@linkcode Deno.Kv}.
  13626. *
  13627. * The `versionstamp` is a string that represents the current version of the
  13628. * key-value pair. It can be used to perform atomic operations on the KV store
  13629. * by passing it to the `check` method of a {@linkcode Deno.AtomicOperation}.
  13630. *
  13631. * @category Cloud
  13632. * @experimental
  13633. */
  13634. export type KvEntry<T> = { key: KvKey; value: T; versionstamp: string };
  13635. /**
  13636. * **UNSTABLE**: New API, yet to be vetted.
  13637. *
  13638. * An optional versioned pair of key and value in a {@linkcode Deno.Kv}.
  13639. *
  13640. * This is the same as a {@linkcode KvEntry}, but the `value` and `versionstamp`
  13641. * fields may be `null` if no value exists for the given key in the KV store.
  13642. *
  13643. * @category Cloud
  13644. * @experimental
  13645. */
  13646. export type KvEntryMaybe<T> = KvEntry<T> | {
  13647. key: KvKey;
  13648. value: null;
  13649. versionstamp: null;
  13650. };
  13651. /** **UNSTABLE**: New API, yet to be vetted.
  13652. *
  13653. * Options for listing key-value pairs in a {@linkcode Deno.Kv}.
  13654. *
  13655. * @category Cloud
  13656. * @experimental
  13657. */
  13658. export interface KvListOptions {
  13659. /**
  13660. * The maximum number of key-value pairs to return. If not specified, all
  13661. * matching key-value pairs will be returned.
  13662. */
  13663. limit?: number;
  13664. /**
  13665. * The cursor to resume the iteration from. If not specified, the iteration
  13666. * will start from the beginning.
  13667. */
  13668. cursor?: string;
  13669. /**
  13670. * Whether to reverse the order of the returned key-value pairs. If not
  13671. * specified, the order will be ascending from the start of the range as per
  13672. * the lexicographical ordering of the keys. If `true`, the order will be
  13673. * descending from the end of the range.
  13674. *
  13675. * The default value is `false`.
  13676. */
  13677. reverse?: boolean;
  13678. /**
  13679. * The consistency level of the list operation. The default consistency
  13680. * level is "strong". Some use cases can benefit from using a weaker
  13681. * consistency level. For more information on consistency levels, see the
  13682. * documentation for {@linkcode Deno.KvConsistencyLevel}.
  13683. *
  13684. * List operations are performed in batches (in sizes specified by the
  13685. * `batchSize` option). The consistency level of the list operation is
  13686. * applied to each batch individually. This means that while each batch is
  13687. * guaranteed to be consistent within itself, the entire list operation may
  13688. * not be consistent across batches because a mutation may be applied to a
  13689. * key-value pair between batches, in a batch that has already been returned
  13690. * by the list operation.
  13691. */
  13692. consistency?: KvConsistencyLevel;
  13693. /**
  13694. * The size of the batches in which the list operation is performed. Larger
  13695. * or smaller batch sizes may positively or negatively affect the
  13696. * performance of a list operation depending on the specific use case and
  13697. * iteration behavior. Slow iterating queries may benefit from using a
  13698. * smaller batch size for increased overall consistency, while fast
  13699. * iterating queries may benefit from using a larger batch size for better
  13700. * performance.
  13701. *
  13702. * The default batch size is equal to the `limit` option, or 100 if this is
  13703. * unset. The maximum value for this option is 500. Larger values will be
  13704. * clamped.
  13705. */
  13706. batchSize?: number;
  13707. }
  13708. /**
  13709. * @category Cloud
  13710. * @experimental
  13711. */
  13712. export interface KvCommitResult {
  13713. ok: true;
  13714. /** The versionstamp of the value committed to KV. */
  13715. versionstamp: string;
  13716. }
  13717. /**
  13718. * @category Cloud
  13719. * @experimental
  13720. */
  13721. export interface KvCommitError {
  13722. ok: false;
  13723. }
  13724. /** **UNSTABLE**: New API, yet to be vetted.
  13725. *
  13726. * A check to perform as part of a {@linkcode Deno.AtomicOperation}. The check
  13727. * will fail if the versionstamp for the key-value pair in the KV store does
  13728. * not match the given versionstamp. A check with a `null` versionstamp checks
  13729. * that the key-value pair does not currently exist in the KV store.
  13730. *
  13731. * @category Cloud
  13732. * @experimental
  13733. */
  13734. export interface AtomicCheck {
  13735. key: KvKey;
  13736. versionstamp: string | null;
  13737. }
  13738. /** **UNSTABLE**: New API, yet to be vetted.
  13739. *
  13740. * An operation on a {@linkcode Deno.Kv} that can be performed
  13741. * atomically. Atomic operations do not auto-commit, and must be committed
  13742. * explicitly by calling the `commit` method.
  13743. *
  13744. * Atomic operations can be used to perform multiple mutations on the KV store
  13745. * in a single atomic transaction. They can also be used to perform
  13746. * conditional mutations by specifying one or more
  13747. * {@linkcode Deno.AtomicCheck}s that ensure that a mutation is only performed
  13748. * if the key-value pair in the KV has a specific versionstamp. If any of the
  13749. * checks fail, the entire operation will fail and no mutations will be made.
  13750. *
  13751. * The ordering of mutations is guaranteed to be the same as the ordering of
  13752. * the mutations specified in the operation. Checks are performed before any
  13753. * mutations are performed. The ordering of checks is unobservable.
  13754. *
  13755. * Atomic operations can be used to implement optimistic locking, where a
  13756. * mutation is only performed if the key-value pair in the KV store has not
  13757. * been modified since the last read. This can be done by specifying a check
  13758. * that ensures that the versionstamp of the key-value pair matches the
  13759. * versionstamp that was read. If the check fails, the mutation will not be
  13760. * performed and the operation will fail. One can then retry the read-modify-
  13761. * write operation in a loop until it succeeds.
  13762. *
  13763. * The `commit` method of an atomic operation returns a value indicating
  13764. * whether checks passed and mutations were performed. If the operation failed
  13765. * because of a failed check, the return value will be a
  13766. * {@linkcode Deno.KvCommitError} with an `ok: false` property. If the
  13767. * operation failed for any other reason (storage error, invalid value, etc.),
  13768. * an exception will be thrown. If the operation succeeded, the return value
  13769. * will be a {@linkcode Deno.KvCommitResult} object with a `ok: true` property
  13770. * and the versionstamp of the value committed to KV.
  13771. *
  13772. * @category Cloud
  13773. * @experimental
  13774. */
  13775. export class AtomicOperation {
  13776. /**
  13777. * Add to the operation a check that ensures that the versionstamp of the
  13778. * key-value pair in the KV store matches the given versionstamp. If the
  13779. * check fails, the entire operation will fail and no mutations will be
  13780. * performed during the commit.
  13781. */
  13782. check(...checks: AtomicCheck[]): this;
  13783. /**
  13784. * Add to the operation a mutation that performs the specified mutation on
  13785. * the specified key if all checks pass during the commit. The types and
  13786. * semantics of all available mutations are described in the documentation
  13787. * for {@linkcode Deno.KvMutation}.
  13788. */
  13789. mutate(...mutations: KvMutation[]): this;
  13790. /**
  13791. * Shortcut for creating a `sum` mutation. This method wraps `n` in a
  13792. * {@linkcode Deno.KvU64}, so the value of `n` must be in the range
  13793. * `[0, 2^64-1]`.
  13794. */
  13795. sum(key: KvKey, n: bigint): this;
  13796. /**
  13797. * Shortcut for creating a `min` mutation. This method wraps `n` in a
  13798. * {@linkcode Deno.KvU64}, so the value of `n` must be in the range
  13799. * `[0, 2^64-1]`.
  13800. */
  13801. min(key: KvKey, n: bigint): this;
  13802. /**
  13803. * Shortcut for creating a `max` mutation. This method wraps `n` in a
  13804. * {@linkcode Deno.KvU64}, so the value of `n` must be in the range
  13805. * `[0, 2^64-1]`.
  13806. */
  13807. max(key: KvKey, n: bigint): this;
  13808. /**
  13809. * Add to the operation a mutation that sets the value of the specified key
  13810. * to the specified value if all checks pass during the commit.
  13811. *
  13812. * Optionally an `expireIn` option can be specified to set a time-to-live
  13813. * (TTL) for the key. The TTL is specified in milliseconds, and the key will
  13814. * be deleted from the database at earliest after the specified number of
  13815. * milliseconds have elapsed. Once the specified duration has passed, the
  13816. * key may still be visible for some additional time. If the `expireIn`
  13817. * option is not specified, the key will not expire.
  13818. */
  13819. set(key: KvKey, value: unknown, options?: { expireIn?: number }): this;
  13820. /**
  13821. * Add to the operation a mutation that deletes the specified key if all
  13822. * checks pass during the commit.
  13823. */
  13824. delete(key: KvKey): this;
  13825. /**
  13826. * Add to the operation a mutation that enqueues a value into the queue
  13827. * if all checks pass during the commit.
  13828. */
  13829. enqueue(
  13830. value: unknown,
  13831. options?: {
  13832. delay?: number;
  13833. keysIfUndelivered?: Deno.KvKey[];
  13834. backoffSchedule?: number[];
  13835. },
  13836. ): this;
  13837. /**
  13838. * Commit the operation to the KV store. Returns a value indicating whether
  13839. * checks passed and mutations were performed. If the operation failed
  13840. * because of a failed check, the return value will be a {@linkcode
  13841. * Deno.KvCommitError} with an `ok: false` property. If the operation failed
  13842. * for any other reason (storage error, invalid value, etc.), an exception
  13843. * will be thrown. If the operation succeeded, the return value will be a
  13844. * {@linkcode Deno.KvCommitResult} object with a `ok: true` property and the
  13845. * versionstamp of the value committed to KV.
  13846. *
  13847. * If the commit returns `ok: false`, one may create a new atomic operation
  13848. * with updated checks and mutations and attempt to commit it again. See the
  13849. * note on optimistic locking in the documentation for
  13850. * {@linkcode Deno.AtomicOperation}.
  13851. */
  13852. commit(): Promise<KvCommitResult | KvCommitError>;
  13853. }
  13854. /** **UNSTABLE**: New API, yet to be vetted.
  13855. *
  13856. * A key-value database that can be used to store and retrieve data.
  13857. *
  13858. * Data is stored as key-value pairs, where the key is a {@linkcode Deno.KvKey}
  13859. * and the value is an arbitrary structured-serializable JavaScript value.
  13860. * Keys are ordered lexicographically as described in the documentation for
  13861. * {@linkcode Deno.KvKey}. Keys are unique within a database, and the last
  13862. * value set for a given key is the one that is returned when reading the
  13863. * key. Keys can be deleted from the database, in which case they will no
  13864. * longer be returned when reading keys.
  13865. *
  13866. * Values can be any structured-serializable JavaScript value (objects,
  13867. * arrays, strings, numbers, etc.). The special value {@linkcode Deno.KvU64}
  13868. * can be used to store 64-bit unsigned integers in the database. This special
  13869. * value can not be nested within other objects or arrays. In addition to the
  13870. * regular database mutation operations, the unsigned 64-bit integer value
  13871. * also supports `sum`, `max`, and `min` mutations.
  13872. *
  13873. * Keys are versioned on write by assigning the key an ever-increasing
  13874. * "versionstamp". The versionstamp represents the version of a key-value pair
  13875. * in the database at some point in time, and can be used to perform
  13876. * transactional operations on the database without requiring any locking.
  13877. * This is enabled by atomic operations, which can have conditions that ensure
  13878. * that the operation only succeeds if the versionstamp of the key-value pair
  13879. * matches an expected versionstamp.
  13880. *
  13881. * Keys have a maximum length of 2048 bytes after serialization. Values have a
  13882. * maximum length of 64 KiB after serialization. Serialization of both keys
  13883. * and values is somewhat opaque, but one can usually assume that the
  13884. * serialization of any value is about the same length as the resulting string
  13885. * of a JSON serialization of that same value. If theses limits are exceeded,
  13886. * an exception will be thrown.
  13887. *
  13888. * @category Cloud
  13889. * @experimental
  13890. */
  13891. export class Kv implements Disposable {
  13892. /**
  13893. * Retrieve the value and versionstamp for the given key from the database
  13894. * in the form of a {@linkcode Deno.KvEntryMaybe}. If no value exists for
  13895. * the key, the returned entry will have a `null` value and versionstamp.
  13896. *
  13897. * ```ts
  13898. * const db = await Deno.openKv();
  13899. * const result = await db.get(["foo"]);
  13900. * result.key; // ["foo"]
  13901. * result.value; // "bar"
  13902. * result.versionstamp; // "00000000000000010000"
  13903. * ```
  13904. *
  13905. * The `consistency` option can be used to specify the consistency level
  13906. * for the read operation. The default consistency level is "strong". Some
  13907. * use cases can benefit from using a weaker consistency level. For more
  13908. * information on consistency levels, see the documentation for
  13909. * {@linkcode Deno.KvConsistencyLevel}.
  13910. */
  13911. get<T = unknown>(
  13912. key: KvKey,
  13913. options?: { consistency?: KvConsistencyLevel },
  13914. ): Promise<KvEntryMaybe<T>>;
  13915. /**
  13916. * Retrieve multiple values and versionstamps from the database in the form
  13917. * of an array of {@linkcode Deno.KvEntryMaybe} objects. The returned array
  13918. * will have the same length as the `keys` array, and the entries will be in
  13919. * the same order as the keys. If no value exists for a given key, the
  13920. * returned entry will have a `null` value and versionstamp.
  13921. *
  13922. * ```ts
  13923. * const db = await Deno.openKv();
  13924. * const result = await db.getMany([["foo"], ["baz"]]);
  13925. * result[0].key; // ["foo"]
  13926. * result[0].value; // "bar"
  13927. * result[0].versionstamp; // "00000000000000010000"
  13928. * result[1].key; // ["baz"]
  13929. * result[1].value; // null
  13930. * result[1].versionstamp; // null
  13931. * ```
  13932. *
  13933. * The `consistency` option can be used to specify the consistency level
  13934. * for the read operation. The default consistency level is "strong". Some
  13935. * use cases can benefit from using a weaker consistency level. For more
  13936. * information on consistency levels, see the documentation for
  13937. * {@linkcode Deno.KvConsistencyLevel}.
  13938. */
  13939. getMany<T extends readonly unknown[]>(
  13940. keys: readonly [...{ [K in keyof T]: KvKey }],
  13941. options?: { consistency?: KvConsistencyLevel },
  13942. ): Promise<{ [K in keyof T]: KvEntryMaybe<T[K]> }>;
  13943. /**
  13944. * Set the value for the given key in the database. If a value already
  13945. * exists for the key, it will be overwritten.
  13946. *
  13947. * ```ts
  13948. * const db = await Deno.openKv();
  13949. * await db.set(["foo"], "bar");
  13950. * ```
  13951. *
  13952. * Optionally an `expireIn` option can be specified to set a time-to-live
  13953. * (TTL) for the key. The TTL is specified in milliseconds, and the key will
  13954. * be deleted from the database at earliest after the specified number of
  13955. * milliseconds have elapsed. Once the specified duration has passed, the
  13956. * key may still be visible for some additional time. If the `expireIn`
  13957. * option is not specified, the key will not expire.
  13958. */
  13959. set(
  13960. key: KvKey,
  13961. value: unknown,
  13962. options?: { expireIn?: number },
  13963. ): Promise<KvCommitResult>;
  13964. /**
  13965. * Delete the value for the given key from the database. If no value exists
  13966. * for the key, this operation is a no-op.
  13967. *
  13968. * ```ts
  13969. * const db = await Deno.openKv();
  13970. * await db.delete(["foo"]);
  13971. * ```
  13972. */
  13973. delete(key: KvKey): Promise<void>;
  13974. /**
  13975. * Retrieve a list of keys in the database. The returned list is an
  13976. * {@linkcode Deno.KvListIterator} which can be used to iterate over the
  13977. * entries in the database.
  13978. *
  13979. * Each list operation must specify a selector which is used to specify the
  13980. * range of keys to return. The selector can either be a prefix selector, or
  13981. * a range selector:
  13982. *
  13983. * - A prefix selector selects all keys that start with the given prefix of
  13984. * key parts. For example, the selector `["users"]` will select all keys
  13985. * that start with the prefix `["users"]`, such as `["users", "alice"]`
  13986. * and `["users", "bob"]`. Note that you can not partially match a key
  13987. * part, so the selector `["users", "a"]` will not match the key
  13988. * `["users", "alice"]`. A prefix selector may specify a `start` key that
  13989. * is used to skip over keys that are lexicographically less than the
  13990. * start key.
  13991. * - A range selector selects all keys that are lexicographically between
  13992. * the given start and end keys (including the start, and excluding the
  13993. * end). For example, the selector `["users", "a"], ["users", "n"]` will
  13994. * select all keys that start with the prefix `["users"]` and have a
  13995. * second key part that is lexicographically between `a` and `n`, such as
  13996. * `["users", "alice"]`, `["users", "bob"]`, and `["users", "mike"]`, but
  13997. * not `["users", "noa"]` or `["users", "zoe"]`.
  13998. *
  13999. * ```ts
  14000. * const db = await Deno.openKv();
  14001. * const entries = db.list({ prefix: ["users"] });
  14002. * for await (const entry of entries) {
  14003. * entry.key; // ["users", "alice"]
  14004. * entry.value; // { name: "Alice" }
  14005. * entry.versionstamp; // "00000000000000010000"
  14006. * }
  14007. * ```
  14008. *
  14009. * The `options` argument can be used to specify additional options for the
  14010. * list operation. See the documentation for {@linkcode Deno.KvListOptions}
  14011. * for more information.
  14012. */
  14013. list<T = unknown>(
  14014. selector: KvListSelector,
  14015. options?: KvListOptions,
  14016. ): KvListIterator<T>;
  14017. /**
  14018. * Add a value into the database queue to be delivered to the queue
  14019. * listener via {@linkcode Deno.Kv.listenQueue}.
  14020. *
  14021. * ```ts
  14022. * const db = await Deno.openKv();
  14023. * await db.enqueue("bar");
  14024. * ```
  14025. *
  14026. * The `delay` option can be used to specify the delay (in milliseconds)
  14027. * of the value delivery. The default delay is 0, which means immediate
  14028. * delivery.
  14029. *
  14030. * ```ts
  14031. * const db = await Deno.openKv();
  14032. * await db.enqueue("bar", { delay: 60000 });
  14033. * ```
  14034. *
  14035. * The `keysIfUndelivered` option can be used to specify the keys to
  14036. * be set if the value is not successfully delivered to the queue
  14037. * listener after several attempts. The values are set to the value of
  14038. * the queued message.
  14039. *
  14040. * The `backoffSchedule` option can be used to specify the retry policy for
  14041. * failed message delivery. Each element in the array represents the number of
  14042. * milliseconds to wait before retrying the delivery. For example,
  14043. * `[1000, 5000, 10000]` means that a failed delivery will be retried
  14044. * at most 3 times, with 1 second, 5 seconds, and 10 seconds delay
  14045. * between each retry.
  14046. *
  14047. * ```ts
  14048. * const db = await Deno.openKv();
  14049. * await db.enqueue("bar", {
  14050. * keysIfUndelivered: [["foo", "bar"]],
  14051. * backoffSchedule: [1000, 5000, 10000],
  14052. * });
  14053. * ```
  14054. */
  14055. enqueue(
  14056. value: unknown,
  14057. options?: {
  14058. delay?: number;
  14059. keysIfUndelivered?: Deno.KvKey[];
  14060. backoffSchedule?: number[];
  14061. },
  14062. ): Promise<KvCommitResult>;
  14063. /**
  14064. * Listen for queue values to be delivered from the database queue, which
  14065. * were enqueued with {@linkcode Deno.Kv.enqueue}. The provided handler
  14066. * callback is invoked on every dequeued value. A failed callback
  14067. * invocation is automatically retried multiple times until it succeeds
  14068. * or until the maximum number of retries is reached.
  14069. *
  14070. * ```ts
  14071. * const db = await Deno.openKv();
  14072. * db.listenQueue(async (msg: unknown) => {
  14073. * await db.set(["foo"], msg);
  14074. * });
  14075. * ```
  14076. */
  14077. // deno-lint-ignore no-explicit-any
  14078. listenQueue(handler: (value: any) => Promise<void> | void): Promise<void>;
  14079. /**
  14080. * Create a new {@linkcode Deno.AtomicOperation} object which can be used to
  14081. * perform an atomic transaction on the database. This does not perform any
  14082. * operations on the database - the atomic transaction must be committed
  14083. * explicitly using the {@linkcode Deno.AtomicOperation.commit} method once
  14084. * all checks and mutations have been added to the operation.
  14085. */
  14086. atomic(): AtomicOperation;
  14087. /**
  14088. * Watch for changes to the given keys in the database. The returned stream
  14089. * is a {@linkcode ReadableStream} that emits a new value whenever any of
  14090. * the watched keys change their versionstamp. The emitted value is an array
  14091. * of {@linkcode Deno.KvEntryMaybe} objects, with the same length and order
  14092. * as the `keys` array. If no value exists for a given key, the returned
  14093. * entry will have a `null` value and versionstamp.
  14094. *
  14095. * The returned stream does not return every single intermediate state of
  14096. * the watched keys, but rather only keeps you up to date with the latest
  14097. * state of the keys. This means that if a key is modified multiple times
  14098. * quickly, you may not receive a notification for every single change, but
  14099. * rather only the latest state of the key.
  14100. *
  14101. * ```ts
  14102. * const db = await Deno.openKv();
  14103. *
  14104. * const stream = db.watch([["foo"], ["bar"]]);
  14105. * for await (const entries of stream) {
  14106. * entries[0].key; // ["foo"]
  14107. * entries[0].value; // "bar"
  14108. * entries[0].versionstamp; // "00000000000000010000"
  14109. * entries[1].key; // ["bar"]
  14110. * entries[1].value; // null
  14111. * entries[1].versionstamp; // null
  14112. * }
  14113. * ```
  14114. *
  14115. * The `options` argument can be used to specify additional options for the
  14116. * watch operation. The `raw` option can be used to specify whether a new
  14117. * value should be emitted whenever a mutation occurs on any of the watched
  14118. * keys (even if the value of the key does not change, such as deleting a
  14119. * deleted key), or only when entries have observably changed in some way.
  14120. * When `raw: true` is used, it is possible for the stream to occasionally
  14121. * emit values even if no mutations have occurred on any of the watched
  14122. * keys. The default value for this option is `false`.
  14123. */
  14124. watch<T extends readonly unknown[]>(
  14125. keys: readonly [...{ [K in keyof T]: KvKey }],
  14126. options?: { raw?: boolean },
  14127. ): ReadableStream<{ [K in keyof T]: KvEntryMaybe<T[K]> }>;
  14128. /**
  14129. * Close the database connection. This will prevent any further operations
  14130. * from being performed on the database, and interrupt any in-flight
  14131. * operations immediately.
  14132. */
  14133. close(): void;
  14134. /**
  14135. * Get a symbol that represents the versionstamp of the current atomic
  14136. * operation. This symbol can be used as the last part of a key in
  14137. * `.set()`, both directly on the `Kv` object and on an `AtomicOperation`
  14138. * object created from this `Kv` instance.
  14139. */
  14140. commitVersionstamp(): symbol;
  14141. [Symbol.dispose](): void;
  14142. }
  14143. /** **UNSTABLE**: New API, yet to be vetted.
  14144. *
  14145. * Wrapper type for 64-bit unsigned integers for use as values in a
  14146. * {@linkcode Deno.Kv}.
  14147. *
  14148. * @category Cloud
  14149. * @experimental
  14150. */
  14151. export class KvU64 {
  14152. /** Create a new `KvU64` instance from the given bigint value. If the value
  14153. * is signed or greater than 64-bits, an error will be thrown. */
  14154. constructor(value: bigint);
  14155. /** The value of this unsigned 64-bit integer, represented as a bigint. */
  14156. readonly value: bigint;
  14157. }
  14158. /**
  14159. * A namespace containing runtime APIs available in Jupyter notebooks.
  14160. *
  14161. * When accessed outside of Jupyter notebook context an error will be thrown.
  14162. *
  14163. * @category Jupyter
  14164. * @experimental
  14165. */
  14166. export namespace jupyter {
  14167. /**
  14168. * @category Jupyter
  14169. * @experimental
  14170. */
  14171. export interface DisplayOptions {
  14172. raw?: boolean;
  14173. update?: boolean;
  14174. display_id?: string;
  14175. }
  14176. /**
  14177. * @category Jupyter
  14178. * @experimental
  14179. */
  14180. export type VegaObject = {
  14181. $schema: string;
  14182. [key: string]: unknown;
  14183. };
  14184. /**
  14185. * A collection of supported media types and data for Jupyter frontends.
  14186. *
  14187. * @category Jupyter
  14188. * @experimental
  14189. */
  14190. export type MediaBundle = {
  14191. "text/plain"?: string;
  14192. "text/html"?: string;
  14193. "image/svg+xml"?: string;
  14194. "text/markdown"?: string;
  14195. "application/javascript"?: string;
  14196. // Images (per Jupyter spec) must be base64 encoded. We could _allow_
  14197. // accepting Uint8Array or ArrayBuffer within `display` calls, however we still
  14198. // must encode them for jupyter.
  14199. "image/png"?: string; // WISH: Uint8Array | ArrayBuffer
  14200. "image/jpeg"?: string; // WISH: Uint8Array | ArrayBuffer
  14201. "image/gif"?: string; // WISH: Uint8Array | ArrayBuffer
  14202. "application/pdf"?: string; // WISH: Uint8Array | ArrayBuffer
  14203. // NOTE: all JSON types must be objects at the top level (no arrays, strings, or other primitives)
  14204. "application/json"?: object;
  14205. "application/geo+json"?: object;
  14206. "application/vdom.v1+json"?: object;
  14207. "application/vnd.plotly.v1+json"?: object;
  14208. "application/vnd.vega.v5+json"?: VegaObject;
  14209. "application/vnd.vegalite.v4+json"?: VegaObject;
  14210. "application/vnd.vegalite.v5+json"?: VegaObject;
  14211. // Must support a catch all for custom media types / mimetypes
  14212. [key: string]: string | object | undefined;
  14213. };
  14214. /**
  14215. * @category Jupyter
  14216. * @experimental
  14217. */
  14218. export const $display: unique symbol;
  14219. /**
  14220. * @category Jupyter
  14221. * @experimental
  14222. */
  14223. export type Displayable = {
  14224. [$display]: () => MediaBundle | Promise<MediaBundle>;
  14225. };
  14226. /**
  14227. * Display function for Jupyter Deno Kernel.
  14228. * Mimics the behavior of IPython's `display(obj, raw=True)` function to allow
  14229. * asynchronous displaying of objects in Jupyter.
  14230. *
  14231. * @param obj - The object to be displayed
  14232. * @param options - Display options with a default { raw: true }
  14233. * @category Jupyter
  14234. * @experimental
  14235. */
  14236. export function display(obj: unknown, options?: DisplayOptions): void;
  14237. /**
  14238. * Show Markdown in Jupyter frontends with a tagged template function.
  14239. *
  14240. * Takes a template string and returns a displayable object for Jupyter frontends.
  14241. *
  14242. * @example
  14243. * Create a Markdown view.
  14244. *
  14245. * ```typescript
  14246. * const { md } = Deno.jupyter;
  14247. * md`# Notebooks in TypeScript via Deno ![Deno logo](https://github.com/denoland.png?size=32)
  14248. *
  14249. * * TypeScript ${Deno.version.typescript}
  14250. * * V8 ${Deno.version.v8}
  14251. * * Deno ${Deno.version.deno}
  14252. *
  14253. * Interactive compute with Jupyter _built into Deno_!
  14254. * `
  14255. * ```
  14256. *
  14257. * @category Jupyter
  14258. * @experimental
  14259. */
  14260. export function md(
  14261. strings: TemplateStringsArray,
  14262. ...values: unknown[]
  14263. ): Displayable;
  14264. /**
  14265. * Show HTML in Jupyter frontends with a tagged template function.
  14266. *
  14267. * Takes a template string and returns a displayable object for Jupyter frontends.
  14268. *
  14269. * @example
  14270. * Create an HTML view.
  14271. * ```typescript
  14272. * const { html } = Deno.jupyter;
  14273. * html`<h1>Hello, world!</h1>`
  14274. * ```
  14275. *
  14276. * @category Jupyter
  14277. * @experimental
  14278. */
  14279. export function html(
  14280. strings: TemplateStringsArray,
  14281. ...values: unknown[]
  14282. ): Displayable;
  14283. /**
  14284. * SVG Tagged Template Function.
  14285. *
  14286. * Takes a template string and returns a displayable object for Jupyter frontends.
  14287. *
  14288. * Example usage:
  14289. *
  14290. * svg`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  14291. * <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
  14292. * </svg>`
  14293. *
  14294. * @category Jupyter
  14295. * @experimental
  14296. */
  14297. export function svg(
  14298. strings: TemplateStringsArray,
  14299. ...values: unknown[]
  14300. ): Displayable;
  14301. /**
  14302. * Format an object for displaying in Deno
  14303. *
  14304. * @param obj - The object to be displayed
  14305. * @returns MediaBundle
  14306. *
  14307. * @category Jupyter
  14308. * @experimental
  14309. */
  14310. export function format(obj: unknown): MediaBundle;
  14311. /**
  14312. * Broadcast a message on IO pub channel.
  14313. *
  14314. * ```
  14315. * await Deno.jupyter.broadcast("display_data", {
  14316. * data: { "text/html": "<b>Processing.</b>" },
  14317. * metadata: {},
  14318. * transient: { display_id: "progress" }
  14319. * });
  14320. *
  14321. * await new Promise((resolve) => setTimeout(resolve, 500));
  14322. *
  14323. * await Deno.jupyter.broadcast("update_display_data", {
  14324. * data: { "text/html": "<b>Processing..</b>" },
  14325. * metadata: {},
  14326. * transient: { display_id: "progress" }
  14327. * });
  14328. * ```
  14329. *
  14330. * @category Jupyter
  14331. * @experimental
  14332. */
  14333. export function broadcast(
  14334. msgType: string,
  14335. content: Record<string, unknown>,
  14336. extra?: {
  14337. metadata?: Record<string, unknown>;
  14338. buffers?: Uint8Array[];
  14339. },
  14340. ): Promise<void>;
  14341. }
  14342. }
  14343. /** **UNSTABLE**: New API, yet to be vetted.
  14344. *
  14345. * The [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
  14346. * which also supports setting a {@linkcode Deno.HttpClient} which provides a
  14347. * way to connect via proxies and use custom TLS certificates.
  14348. *
  14349. * @tags allow-net, allow-read
  14350. * @category Fetch
  14351. * @experimental
  14352. */
  14353. declare function fetch(
  14354. input: Request | URL | string,
  14355. init?: RequestInit & { client: Deno.HttpClient },
  14356. ): Promise<Response>;
  14357. /** **UNSTABLE**: New API, yet to be vetted.
  14358. *
  14359. * @category Workers
  14360. * @experimental
  14361. */
  14362. declare interface WorkerOptions {
  14363. /** **UNSTABLE**: New API, yet to be vetted.
  14364. *
  14365. * Configure permissions options to change the level of access the worker will
  14366. * have. By default it will have no permissions. Note that the permissions
  14367. * of a worker can't be extended beyond its parent's permissions reach.
  14368. *
  14369. * - `"inherit"` will take the permissions of the thread the worker is created
  14370. * in.
  14371. * - `"none"` will use the default behavior and have no permission
  14372. * - A list of routes can be provided that are relative to the file the worker
  14373. * is created in to limit the access of the worker (read/write permissions
  14374. * only)
  14375. *
  14376. * Example:
  14377. *
  14378. * ```ts
  14379. * // mod.ts
  14380. * const worker = new Worker(
  14381. * new URL("deno_worker.ts", import.meta.url).href, {
  14382. * type: "module",
  14383. * deno: {
  14384. * permissions: {
  14385. * read: true,
  14386. * },
  14387. * },
  14388. * }
  14389. * );
  14390. * ```
  14391. */
  14392. deno?: {
  14393. /** Set to `"none"` to disable all the permissions in the worker. */
  14394. permissions?: Deno.PermissionOptions;
  14395. };
  14396. }
  14397. /** **UNSTABLE**: New API, yet to be vetted.
  14398. *
  14399. * @category WebSockets
  14400. * @experimental
  14401. */
  14402. declare interface WebSocketStreamOptions {
  14403. protocols?: string[];
  14404. signal?: AbortSignal;
  14405. headers?: HeadersInit;
  14406. }
  14407. /** **UNSTABLE**: New API, yet to be vetted.
  14408. *
  14409. * @category WebSockets
  14410. * @experimental
  14411. */
  14412. declare interface WebSocketConnection {
  14413. readable: ReadableStream<string | Uint8Array>;
  14414. writable: WritableStream<string | Uint8Array>;
  14415. extensions: string;
  14416. protocol: string;
  14417. }
  14418. /** **UNSTABLE**: New API, yet to be vetted.
  14419. *
  14420. * @category WebSockets
  14421. * @experimental
  14422. */
  14423. declare interface WebSocketCloseInfo {
  14424. code?: number;
  14425. reason?: string;
  14426. }
  14427. /** **UNSTABLE**: New API, yet to be vetted.
  14428. *
  14429. * @tags allow-net
  14430. * @category WebSockets
  14431. * @experimental
  14432. */
  14433. declare interface WebSocketStream {
  14434. url: string;
  14435. opened: Promise<WebSocketConnection>;
  14436. closed: Promise<WebSocketCloseInfo>;
  14437. close(closeInfo?: WebSocketCloseInfo): void;
  14438. }
  14439. /** **UNSTABLE**: New API, yet to be vetted.
  14440. *
  14441. * @tags allow-net
  14442. * @category WebSockets
  14443. * @experimental
  14444. */
  14445. declare var WebSocketStream: {
  14446. readonly prototype: WebSocketStream;
  14447. new (url: string, options?: WebSocketStreamOptions): WebSocketStream;
  14448. };
  14449. /** **UNSTABLE**: New API, yet to be vetted.
  14450. *
  14451. * @tags allow-net
  14452. * @category WebSockets
  14453. * @experimental
  14454. */
  14455. declare interface WebSocketError extends DOMException {
  14456. readonly closeCode: number;
  14457. readonly reason: string;
  14458. }
  14459. /** **UNSTABLE**: New API, yet to be vetted.
  14460. *
  14461. * @tags allow-net
  14462. * @category WebSockets
  14463. * @experimental
  14464. */
  14465. declare var WebSocketError: {
  14466. readonly prototype: WebSocketError;
  14467. new (message?: string, init?: WebSocketCloseInfo): WebSocketError;
  14468. };
  14469. // Adapted from `tc39/proposal-temporal`: https://github.com/tc39/proposal-temporal/blob/main/polyfill/index.d.ts
  14470. /**
  14471. * [Specification](https://tc39.es/proposal-temporal/docs/index.html)
  14472. *
  14473. * @category Temporal
  14474. * @experimental
  14475. */
  14476. declare namespace Temporal {
  14477. /**
  14478. * @category Temporal
  14479. * @experimental
  14480. */
  14481. export type ComparisonResult = -1 | 0 | 1;
  14482. /**
  14483. * @category Temporal
  14484. * @experimental
  14485. */
  14486. export type RoundingMode =
  14487. | "ceil"
  14488. | "floor"
  14489. | "expand"
  14490. | "trunc"
  14491. | "halfCeil"
  14492. | "halfFloor"
  14493. | "halfExpand"
  14494. | "halfTrunc"
  14495. | "halfEven";
  14496. /**
  14497. * Options for assigning fields using `with()` or entire objects with
  14498. * `from()`.
  14499. *
  14500. * @category Temporal
  14501. * @experimental
  14502. */
  14503. export type AssignmentOptions = {
  14504. /**
  14505. * How to deal with out-of-range values
  14506. *
  14507. * - In `'constrain'` mode, out-of-range values are clamped to the nearest
  14508. * in-range value.
  14509. * - In `'reject'` mode, out-of-range values will cause the function to
  14510. * throw a RangeError.
  14511. *
  14512. * The default is `'constrain'`.
  14513. */
  14514. overflow?: "constrain" | "reject";
  14515. };
  14516. /**
  14517. * Options for assigning fields using `Duration.prototype.with()` or entire
  14518. * objects with `Duration.from()`, and for arithmetic with
  14519. * `Duration.prototype.add()` and `Duration.prototype.subtract()`.
  14520. *
  14521. * @category Temporal
  14522. * @experimental
  14523. */
  14524. export type DurationOptions = {
  14525. /**
  14526. * How to deal with out-of-range values
  14527. *
  14528. * - In `'constrain'` mode, out-of-range values are clamped to the nearest
  14529. * in-range value.
  14530. * - In `'balance'` mode, out-of-range values are resolved by balancing them
  14531. * with the next highest unit.
  14532. *
  14533. * The default is `'constrain'`.
  14534. */
  14535. overflow?: "constrain" | "balance";
  14536. };
  14537. /**
  14538. * Options for conversions of `Temporal.PlainDateTime` to `Temporal.Instant`
  14539. *
  14540. * @category Temporal
  14541. * @experimental
  14542. */
  14543. export type ToInstantOptions = {
  14544. /**
  14545. * Controls handling of invalid or ambiguous times caused by time zone
  14546. * offset changes like Daylight Saving time (DST) transitions.
  14547. *
  14548. * This option is only relevant if a `DateTime` value does not exist in the
  14549. * destination time zone (e.g. near "Spring Forward" DST transitions), or
  14550. * exists more than once (e.g. near "Fall Back" DST transitions).
  14551. *
  14552. * In case of ambiguous or nonexistent times, this option controls what
  14553. * exact time to return:
  14554. * - `'compatible'`: Equivalent to `'earlier'` for backward transitions like
  14555. * the start of DST in the Spring, and `'later'` for forward transitions
  14556. * like the end of DST in the Fall. This matches the behavior of legacy
  14557. * `Date`, of libraries like moment.js, Luxon, or date-fns, and of
  14558. * cross-platform standards like [RFC 5545
  14559. * (iCalendar)](https://tools.ietf.org/html/rfc5545).
  14560. * - `'earlier'`: The earlier time of two possible times
  14561. * - `'later'`: The later of two possible times
  14562. * - `'reject'`: Throw a RangeError instead
  14563. *
  14564. * The default is `'compatible'`.
  14565. */
  14566. disambiguation?: "compatible" | "earlier" | "later" | "reject";
  14567. };
  14568. /**
  14569. * @category Temporal
  14570. * @experimental
  14571. */
  14572. export type OffsetDisambiguationOptions = {
  14573. /**
  14574. * Time zone definitions can change. If an application stores data about
  14575. * events in the future, then stored data about future events may become
  14576. * ambiguous, for example if a country permanently abolishes DST. The
  14577. * `offset` option controls this unusual case.
  14578. *
  14579. * - `'use'` always uses the offset (if it's provided) to calculate the
  14580. * instant. This ensures that the result will match the instant that was
  14581. * originally stored, even if local clock time is different.
  14582. * - `'prefer'` uses the offset if it's valid for the date/time in this time
  14583. * zone, but if it's not valid then the time zone will be used as a
  14584. * fallback to calculate the instant.
  14585. * - `'ignore'` will disregard any provided offset. Instead, the time zone
  14586. * and date/time value are used to calculate the instant. This will keep
  14587. * local clock time unchanged but may result in a different real-world
  14588. * instant.
  14589. * - `'reject'` acts like `'prefer'`, except it will throw a RangeError if
  14590. * the offset is not valid for the given time zone identifier and
  14591. * date/time value.
  14592. *
  14593. * If the ISO string ends in 'Z' then this option is ignored because there
  14594. * is no possibility of ambiguity.
  14595. *
  14596. * If a time zone offset is not present in the input, then this option is
  14597. * ignored because the time zone will always be used to calculate the
  14598. * offset.
  14599. *
  14600. * If the offset is not used, and if the date/time and time zone don't
  14601. * uniquely identify a single instant, then the `disambiguation` option will
  14602. * be used to choose the correct instant. However, if the offset is used
  14603. * then the `disambiguation` option will be ignored.
  14604. */
  14605. offset?: "use" | "prefer" | "ignore" | "reject";
  14606. };
  14607. /**
  14608. * @category Temporal
  14609. * @experimental
  14610. */
  14611. export type ZonedDateTimeAssignmentOptions = Partial<
  14612. AssignmentOptions & ToInstantOptions & OffsetDisambiguationOptions
  14613. >;
  14614. /**
  14615. * Options for arithmetic operations like `add()` and `subtract()`
  14616. *
  14617. * @category Temporal
  14618. * @experimental
  14619. */
  14620. export type ArithmeticOptions = {
  14621. /**
  14622. * Controls handling of out-of-range arithmetic results.
  14623. *
  14624. * If a result is out of range, then `'constrain'` will clamp the result to
  14625. * the allowed range, while `'reject'` will throw a RangeError.
  14626. *
  14627. * The default is `'constrain'`.
  14628. */
  14629. overflow?: "constrain" | "reject";
  14630. };
  14631. /**
  14632. * @category Temporal
  14633. * @experimental
  14634. */
  14635. export type DateUnit = "year" | "month" | "week" | "day";
  14636. /**
  14637. * @category Temporal
  14638. * @experimental
  14639. */
  14640. export type TimeUnit =
  14641. | "hour"
  14642. | "minute"
  14643. | "second"
  14644. | "millisecond"
  14645. | "microsecond"
  14646. | "nanosecond";
  14647. /**
  14648. * @category Temporal
  14649. * @experimental
  14650. */
  14651. export type DateTimeUnit = DateUnit | TimeUnit;
  14652. /**
  14653. * When the name of a unit is provided to a Temporal API as a string, it is
  14654. * usually singular, e.g. 'day' or 'hour'. But plural unit names like 'days'
  14655. * or 'hours' are aso accepted too.
  14656. *
  14657. * @category Temporal
  14658. * @experimental
  14659. */
  14660. export type PluralUnit<T extends DateTimeUnit> = {
  14661. year: "years";
  14662. month: "months";
  14663. week: "weeks";
  14664. day: "days";
  14665. hour: "hours";
  14666. minute: "minutes";
  14667. second: "seconds";
  14668. millisecond: "milliseconds";
  14669. microsecond: "microseconds";
  14670. nanosecond: "nanoseconds";
  14671. }[T];
  14672. /**
  14673. * @category Temporal
  14674. * @experimental
  14675. */
  14676. export type LargestUnit<T extends DateTimeUnit> = "auto" | T | PluralUnit<T>;
  14677. /**
  14678. * @category Temporal
  14679. * @experimental
  14680. */
  14681. export type SmallestUnit<T extends DateTimeUnit> = T | PluralUnit<T>;
  14682. /**
  14683. * @category Temporal
  14684. * @experimental
  14685. */
  14686. export type TotalUnit<T extends DateTimeUnit> = T | PluralUnit<T>;
  14687. /**
  14688. * Options for outputting precision in toString() on types with seconds
  14689. *
  14690. * @category Temporal
  14691. * @experimental
  14692. */
  14693. export type ToStringPrecisionOptions = {
  14694. fractionalSecondDigits?: "auto" | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
  14695. smallestUnit?: SmallestUnit<
  14696. "minute" | "second" | "millisecond" | "microsecond" | "nanosecond"
  14697. >;
  14698. /**
  14699. * Controls how rounding is performed:
  14700. * - `halfExpand`: Round to the nearest of the values allowed by
  14701. * `roundingIncrement` and `smallestUnit`. When there is a tie, round up.
  14702. * This mode is the default.
  14703. * - `ceil`: Always round up, towards the end of time.
  14704. * - `trunc`: Always round down, towards the beginning of time.
  14705. * - `floor`: Also round down, towards the beginning of time. This mode acts
  14706. * the same as `trunc`, but it's included for consistency with
  14707. * `Temporal.Duration.round()` where negative values are allowed and
  14708. * `trunc` rounds towards zero, unlike `floor` which rounds towards
  14709. * negative infinity which is usually unexpected. For this reason, `trunc`
  14710. * is recommended for most use cases.
  14711. */
  14712. roundingMode?: RoundingMode;
  14713. };
  14714. /**
  14715. * @category Temporal
  14716. * @experimental
  14717. */
  14718. export type ShowCalendarOption = {
  14719. calendarName?: "auto" | "always" | "never" | "critical";
  14720. };
  14721. /**
  14722. * @category Temporal
  14723. * @experimental
  14724. */
  14725. export type CalendarTypeToStringOptions = Partial<
  14726. ToStringPrecisionOptions & ShowCalendarOption
  14727. >;
  14728. /**
  14729. * @category Temporal
  14730. * @experimental
  14731. */
  14732. export type ZonedDateTimeToStringOptions = Partial<
  14733. CalendarTypeToStringOptions & {
  14734. timeZoneName?: "auto" | "never" | "critical";
  14735. offset?: "auto" | "never";
  14736. }
  14737. >;
  14738. /**
  14739. * @category Temporal
  14740. * @experimental
  14741. */
  14742. export type InstantToStringOptions = Partial<
  14743. ToStringPrecisionOptions & {
  14744. timeZone: TimeZoneLike;
  14745. }
  14746. >;
  14747. /**
  14748. * Options to control the result of `until()` and `since()` methods in
  14749. * `Temporal` types.
  14750. *
  14751. * @category Temporal
  14752. * @experimental
  14753. */
  14754. export interface DifferenceOptions<T extends DateTimeUnit> {
  14755. /**
  14756. * The unit to round to. For example, to round to the nearest minute, use
  14757. * `smallestUnit: 'minute'`. This property is optional for `until()` and
  14758. * `since()`, because those methods default behavior is not to round.
  14759. * However, the same property is required for `round()`.
  14760. */
  14761. smallestUnit?: SmallestUnit<T>;
  14762. /**
  14763. * The largest unit to allow in the resulting `Temporal.Duration` object.
  14764. *
  14765. * Larger units will be "balanced" into smaller units. For example, if
  14766. * `largestUnit` is `'minute'` then a two-hour duration will be output as a
  14767. * 120-minute duration.
  14768. *
  14769. * Valid values may include `'year'`, `'month'`, `'week'`, `'day'`,
  14770. * `'hour'`, `'minute'`, `'second'`, `'millisecond'`, `'microsecond'`,
  14771. * `'nanosecond'` and `'auto'`, although some types may throw an exception
  14772. * if a value is used that would produce an invalid result. For example,
  14773. * `hours` is not accepted by `Temporal.PlainDate.prototype.since()`.
  14774. *
  14775. * The default is always `'auto'`, though the meaning of this depends on the
  14776. * type being used.
  14777. */
  14778. largestUnit?: LargestUnit<T>;
  14779. /**
  14780. * Allows rounding to an integer number of units. For example, to round to
  14781. * increments of a half hour, use `{ smallestUnit: 'minute',
  14782. * roundingIncrement: 30 }`.
  14783. */
  14784. roundingIncrement?: number;
  14785. /**
  14786. * Controls how rounding is performed:
  14787. * - `halfExpand`: Round to the nearest of the values allowed by
  14788. * `roundingIncrement` and `smallestUnit`. When there is a tie, round away
  14789. * from zero like `ceil` for positive durations and like `floor` for
  14790. * negative durations.
  14791. * - `ceil`: Always round up, towards the end of time.
  14792. * - `trunc`: Always round down, towards the beginning of time. This mode is
  14793. * the default.
  14794. * - `floor`: Also round down, towards the beginning of time. This mode acts
  14795. * the same as `trunc`, but it's included for consistency with
  14796. * `Temporal.Duration.round()` where negative values are allowed and
  14797. * `trunc` rounds towards zero, unlike `floor` which rounds towards
  14798. * negative infinity which is usually unexpected. For this reason, `trunc`
  14799. * is recommended for most use cases.
  14800. */
  14801. roundingMode?: RoundingMode;
  14802. }
  14803. /**
  14804. * `round` methods take one required parameter. If a string is provided, the
  14805. * resulting `Temporal.Duration` object will be rounded to that unit. If an
  14806. * object is provided, its `smallestUnit` property is required while other
  14807. * properties are optional. A string is treated the same as an object whose
  14808. * `smallestUnit` property value is that string.
  14809. *
  14810. * @category Temporal
  14811. * @experimental
  14812. */
  14813. export type RoundTo<T extends DateTimeUnit> =
  14814. | SmallestUnit<T>
  14815. | {
  14816. /**
  14817. * The unit to round to. For example, to round to the nearest minute,
  14818. * use `smallestUnit: 'minute'`. This option is required. Note that the
  14819. * same-named property is optional when passed to `until` or `since`
  14820. * methods, because those methods do no rounding by default.
  14821. */
  14822. smallestUnit: SmallestUnit<T>;
  14823. /**
  14824. * Allows rounding to an integer number of units. For example, to round to
  14825. * increments of a half hour, use `{ smallestUnit: 'minute',
  14826. * roundingIncrement: 30 }`.
  14827. */
  14828. roundingIncrement?: number;
  14829. /**
  14830. * Controls how rounding is performed:
  14831. * - `halfExpand`: Round to the nearest of the values allowed by
  14832. * `roundingIncrement` and `smallestUnit`. When there is a tie, round up.
  14833. * This mode is the default.
  14834. * - `ceil`: Always round up, towards the end of time.
  14835. * - `trunc`: Always round down, towards the beginning of time.
  14836. * - `floor`: Also round down, towards the beginning of time. This mode acts
  14837. * the same as `trunc`, but it's included for consistency with
  14838. * `Temporal.Duration.round()` where negative values are allowed and
  14839. * `trunc` rounds towards zero, unlike `floor` which rounds towards
  14840. * negative infinity which is usually unexpected. For this reason, `trunc`
  14841. * is recommended for most use cases.
  14842. */
  14843. roundingMode?: RoundingMode;
  14844. };
  14845. /**
  14846. * The `round` method of the `Temporal.Duration` accepts one required
  14847. * parameter. If a string is provided, the resulting `Temporal.Duration`
  14848. * object will be rounded to that unit. If an object is provided, the
  14849. * `smallestUnit` and/or `largestUnit` property is required, while other
  14850. * properties are optional. A string parameter is treated the same as an
  14851. * object whose `smallestUnit` property value is that string.
  14852. *
  14853. * @category Temporal
  14854. * @experimental
  14855. */
  14856. export type DurationRoundTo =
  14857. | SmallestUnit<DateTimeUnit>
  14858. | (
  14859. & (
  14860. | {
  14861. /**
  14862. * The unit to round to. For example, to round to the nearest
  14863. * minute, use `smallestUnit: 'minute'`. This property is normally
  14864. * required, but is optional if `largestUnit` is provided and not
  14865. * undefined.
  14866. */
  14867. smallestUnit: SmallestUnit<DateTimeUnit>;
  14868. /**
  14869. * The largest unit to allow in the resulting `Temporal.Duration`
  14870. * object.
  14871. *
  14872. * Larger units will be "balanced" into smaller units. For example,
  14873. * if `largestUnit` is `'minute'` then a two-hour duration will be
  14874. * output as a 120-minute duration.
  14875. *
  14876. * Valid values include `'year'`, `'month'`, `'week'`, `'day'`,
  14877. * `'hour'`, `'minute'`, `'second'`, `'millisecond'`,
  14878. * `'microsecond'`, `'nanosecond'` and `'auto'`.
  14879. *
  14880. * The default is `'auto'`, which means "the largest nonzero unit in
  14881. * the input duration". This default prevents expanding durations to
  14882. * larger units unless the caller opts into this behavior.
  14883. *
  14884. * If `smallestUnit` is larger, then `smallestUnit` will be used as
  14885. * `largestUnit`, superseding a caller-supplied or default value.
  14886. */
  14887. largestUnit?: LargestUnit<DateTimeUnit>;
  14888. }
  14889. | {
  14890. /**
  14891. * The unit to round to. For example, to round to the nearest
  14892. * minute, use `smallestUnit: 'minute'`. This property is normally
  14893. * required, but is optional if `largestUnit` is provided and not
  14894. * undefined.
  14895. */
  14896. smallestUnit?: SmallestUnit<DateTimeUnit>;
  14897. /**
  14898. * The largest unit to allow in the resulting `Temporal.Duration`
  14899. * object.
  14900. *
  14901. * Larger units will be "balanced" into smaller units. For example,
  14902. * if `largestUnit` is `'minute'` then a two-hour duration will be
  14903. * output as a 120-minute duration.
  14904. *
  14905. * Valid values include `'year'`, `'month'`, `'week'`, `'day'`,
  14906. * `'hour'`, `'minute'`, `'second'`, `'millisecond'`,
  14907. * `'microsecond'`, `'nanosecond'` and `'auto'`.
  14908. *
  14909. * The default is `'auto'`, which means "the largest nonzero unit in
  14910. * the input duration". This default prevents expanding durations to
  14911. * larger units unless the caller opts into this behavior.
  14912. *
  14913. * If `smallestUnit` is larger, then `smallestUnit` will be used as
  14914. * `largestUnit`, superseding a caller-supplied or default value.
  14915. */
  14916. largestUnit: LargestUnit<DateTimeUnit>;
  14917. }
  14918. )
  14919. & {
  14920. /**
  14921. * Allows rounding to an integer number of units. For example, to round
  14922. * to increments of a half hour, use `{ smallestUnit: 'minute',
  14923. * roundingIncrement: 30 }`.
  14924. */
  14925. roundingIncrement?: number;
  14926. /**
  14927. * Controls how rounding is performed:
  14928. * - `halfExpand`: Round to the nearest of the values allowed by
  14929. * `roundingIncrement` and `smallestUnit`. When there is a tie, round
  14930. * away from zero like `ceil` for positive durations and like `floor`
  14931. * for negative durations. This mode is the default.
  14932. * - `ceil`: Always round towards positive infinity. For negative
  14933. * durations this option will decrease the absolute value of the
  14934. * duration which may be unexpected. To round away from zero, use
  14935. * `ceil` for positive durations and `floor` for negative durations.
  14936. * - `trunc`: Always round down towards zero.
  14937. * - `floor`: Always round towards negative infinity. This mode acts the
  14938. * same as `trunc` for positive durations but for negative durations
  14939. * it will increase the absolute value of the result which may be
  14940. * unexpected. For this reason, `trunc` is recommended for most "round
  14941. * down" use cases.
  14942. */
  14943. roundingMode?: RoundingMode;
  14944. /**
  14945. * The starting point to use for rounding and conversions when
  14946. * variable-length units (years, months, weeks depending on the
  14947. * calendar) are involved. This option is required if any of the
  14948. * following are true:
  14949. * - `unit` is `'week'` or larger units
  14950. * - `this` has a nonzero value for `weeks` or larger units
  14951. *
  14952. * This value must be either a `Temporal.PlainDateTime`, a
  14953. * `Temporal.ZonedDateTime`, or a string or object value that can be
  14954. * passed to `from()` of those types. Examples:
  14955. * - `'2020-01'01T00:00-08:00[America/Los_Angeles]'`
  14956. * - `'2020-01'01'`
  14957. * - `Temporal.PlainDate.from('2020-01-01')`
  14958. *
  14959. * `Temporal.ZonedDateTime` will be tried first because it's more
  14960. * specific, with `Temporal.PlainDateTime` as a fallback.
  14961. *
  14962. * If the value resolves to a `Temporal.ZonedDateTime`, then operation
  14963. * will adjust for DST and other time zone transitions. Otherwise
  14964. * (including if this option is omitted), then the operation will ignore
  14965. * time zone transitions and all days will be assumed to be 24 hours
  14966. * long.
  14967. */
  14968. relativeTo?:
  14969. | Temporal.PlainDateTime
  14970. | Temporal.ZonedDateTime
  14971. | PlainDateTimeLike
  14972. | ZonedDateTimeLike
  14973. | string;
  14974. }
  14975. );
  14976. /**
  14977. * Options to control behavior of `Duration.prototype.total()`
  14978. *
  14979. * @category Temporal
  14980. * @experimental
  14981. */
  14982. export type DurationTotalOf =
  14983. | TotalUnit<DateTimeUnit>
  14984. | {
  14985. /**
  14986. * The unit to convert the duration to. This option is required.
  14987. */
  14988. unit: TotalUnit<DateTimeUnit>;
  14989. /**
  14990. * The starting point to use when variable-length units (years, months,
  14991. * weeks depending on the calendar) are involved. This option is required if
  14992. * any of the following are true:
  14993. * - `unit` is `'week'` or larger units
  14994. * - `this` has a nonzero value for `weeks` or larger units
  14995. *
  14996. * This value must be either a `Temporal.PlainDateTime`, a
  14997. * `Temporal.ZonedDateTime`, or a string or object value that can be passed
  14998. * to `from()` of those types. Examples:
  14999. * - `'2020-01'01T00:00-08:00[America/Los_Angeles]'`
  15000. * - `'2020-01'01'`
  15001. * - `Temporal.PlainDate.from('2020-01-01')`
  15002. *
  15003. * `Temporal.ZonedDateTime` will be tried first because it's more
  15004. * specific, with `Temporal.PlainDateTime` as a fallback.
  15005. *
  15006. * If the value resolves to a `Temporal.ZonedDateTime`, then operation will
  15007. * adjust for DST and other time zone transitions. Otherwise (including if
  15008. * this option is omitted), then the operation will ignore time zone
  15009. * transitions and all days will be assumed to be 24 hours long.
  15010. */
  15011. relativeTo?:
  15012. | Temporal.ZonedDateTime
  15013. | Temporal.PlainDateTime
  15014. | ZonedDateTimeLike
  15015. | PlainDateTimeLike
  15016. | string;
  15017. };
  15018. /**
  15019. * Options to control behavior of `Duration.compare()`, `Duration.add()`, and
  15020. * `Duration.subtract()`
  15021. *
  15022. * @category Temporal
  15023. * @experimental
  15024. */
  15025. export interface DurationArithmeticOptions {
  15026. /**
  15027. * The starting point to use when variable-length units (years, months,
  15028. * weeks depending on the calendar) are involved. This option is required if
  15029. * either of the durations has a nonzero value for `weeks` or larger units.
  15030. *
  15031. * This value must be either a `Temporal.PlainDateTime`, a
  15032. * `Temporal.ZonedDateTime`, or a string or object value that can be passed
  15033. * to `from()` of those types. Examples:
  15034. * - `'2020-01'01T00:00-08:00[America/Los_Angeles]'`
  15035. * - `'2020-01'01'`
  15036. * - `Temporal.PlainDate.from('2020-01-01')`
  15037. *
  15038. * `Temporal.ZonedDateTime` will be tried first because it's more
  15039. * specific, with `Temporal.PlainDateTime` as a fallback.
  15040. *
  15041. * If the value resolves to a `Temporal.ZonedDateTime`, then operation will
  15042. * adjust for DST and other time zone transitions. Otherwise (including if
  15043. * this option is omitted), then the operation will ignore time zone
  15044. * transitions and all days will be assumed to be 24 hours long.
  15045. */
  15046. relativeTo?:
  15047. | Temporal.ZonedDateTime
  15048. | Temporal.PlainDateTime
  15049. | ZonedDateTimeLike
  15050. | PlainDateTimeLike
  15051. | string;
  15052. }
  15053. /**
  15054. * @category Temporal
  15055. * @experimental
  15056. */
  15057. export type DurationLike = {
  15058. years?: number;
  15059. months?: number;
  15060. weeks?: number;
  15061. days?: number;
  15062. hours?: number;
  15063. minutes?: number;
  15064. seconds?: number;
  15065. milliseconds?: number;
  15066. microseconds?: number;
  15067. nanoseconds?: number;
  15068. };
  15069. /**
  15070. * A `Temporal.Duration` represents an immutable duration of time which can be
  15071. * used in date/time arithmetic.
  15072. *
  15073. * See https://tc39.es/proposal-temporal/docs/duration.html for more details.
  15074. *
  15075. * @category Temporal
  15076. * @experimental
  15077. */
  15078. export class Duration {
  15079. static from(
  15080. item: Temporal.Duration | DurationLike | string,
  15081. ): Temporal.Duration;
  15082. static compare(
  15083. one: Temporal.Duration | DurationLike | string,
  15084. two: Temporal.Duration | DurationLike | string,
  15085. options?: DurationArithmeticOptions,
  15086. ): ComparisonResult;
  15087. constructor(
  15088. years?: number,
  15089. months?: number,
  15090. weeks?: number,
  15091. days?: number,
  15092. hours?: number,
  15093. minutes?: number,
  15094. seconds?: number,
  15095. milliseconds?: number,
  15096. microseconds?: number,
  15097. nanoseconds?: number,
  15098. );
  15099. readonly sign: -1 | 0 | 1;
  15100. readonly blank: boolean;
  15101. readonly years: number;
  15102. readonly months: number;
  15103. readonly weeks: number;
  15104. readonly days: number;
  15105. readonly hours: number;
  15106. readonly minutes: number;
  15107. readonly seconds: number;
  15108. readonly milliseconds: number;
  15109. readonly microseconds: number;
  15110. readonly nanoseconds: number;
  15111. negated(): Temporal.Duration;
  15112. abs(): Temporal.Duration;
  15113. with(durationLike: DurationLike): Temporal.Duration;
  15114. add(
  15115. other: Temporal.Duration | DurationLike | string,
  15116. options?: DurationArithmeticOptions,
  15117. ): Temporal.Duration;
  15118. subtract(
  15119. other: Temporal.Duration | DurationLike | string,
  15120. options?: DurationArithmeticOptions,
  15121. ): Temporal.Duration;
  15122. round(roundTo: DurationRoundTo): Temporal.Duration;
  15123. total(totalOf: DurationTotalOf): number;
  15124. toLocaleString(
  15125. locales?: string | string[],
  15126. options?: Intl.DateTimeFormatOptions,
  15127. ): string;
  15128. toJSON(): string;
  15129. toString(options?: ToStringPrecisionOptions): string;
  15130. valueOf(): never;
  15131. readonly [Symbol.toStringTag]: "Temporal.Duration";
  15132. }
  15133. /**
  15134. * A `Temporal.Instant` is an exact point in time, with a precision in
  15135. * nanoseconds. No time zone or calendar information is present. Therefore,
  15136. * `Temporal.Instant` has no concept of days, months, or even hours.
  15137. *
  15138. * For convenience of interoperability, it internally uses nanoseconds since
  15139. * the {@link https://en.wikipedia.org/wiki/Unix_time|Unix epoch} (midnight
  15140. * UTC on January 1, 1970). However, a `Temporal.Instant` can be created from
  15141. * any of several expressions that refer to a single point in time, including
  15142. * an {@link https://en.wikipedia.org/wiki/ISO_8601|ISO 8601 string} with a
  15143. * time zone offset such as '2020-01-23T17:04:36.491865121-08:00'.
  15144. *
  15145. * See https://tc39.es/proposal-temporal/docs/instant.html for more details.
  15146. *
  15147. * @category Temporal
  15148. * @experimental
  15149. */
  15150. export class Instant {
  15151. static fromEpochSeconds(epochSeconds: number): Temporal.Instant;
  15152. static fromEpochMilliseconds(epochMilliseconds: number): Temporal.Instant;
  15153. static fromEpochMicroseconds(epochMicroseconds: bigint): Temporal.Instant;
  15154. static fromEpochNanoseconds(epochNanoseconds: bigint): Temporal.Instant;
  15155. static from(item: Temporal.Instant | string): Temporal.Instant;
  15156. static compare(
  15157. one: Temporal.Instant | string,
  15158. two: Temporal.Instant | string,
  15159. ): ComparisonResult;
  15160. constructor(epochNanoseconds: bigint);
  15161. readonly epochSeconds: number;
  15162. readonly epochMilliseconds: number;
  15163. readonly epochMicroseconds: bigint;
  15164. readonly epochNanoseconds: bigint;
  15165. equals(other: Temporal.Instant | string): boolean;
  15166. add(
  15167. durationLike:
  15168. | Omit<
  15169. Temporal.Duration | DurationLike,
  15170. "years" | "months" | "weeks" | "days"
  15171. >
  15172. | string,
  15173. ): Temporal.Instant;
  15174. subtract(
  15175. durationLike:
  15176. | Omit<
  15177. Temporal.Duration | DurationLike,
  15178. "years" | "months" | "weeks" | "days"
  15179. >
  15180. | string,
  15181. ): Temporal.Instant;
  15182. until(
  15183. other: Temporal.Instant | string,
  15184. options?: DifferenceOptions<
  15185. | "hour"
  15186. | "minute"
  15187. | "second"
  15188. | "millisecond"
  15189. | "microsecond"
  15190. | "nanosecond"
  15191. >,
  15192. ): Temporal.Duration;
  15193. since(
  15194. other: Temporal.Instant | string,
  15195. options?: DifferenceOptions<
  15196. | "hour"
  15197. | "minute"
  15198. | "second"
  15199. | "millisecond"
  15200. | "microsecond"
  15201. | "nanosecond"
  15202. >,
  15203. ): Temporal.Duration;
  15204. round(
  15205. roundTo: RoundTo<
  15206. | "hour"
  15207. | "minute"
  15208. | "second"
  15209. | "millisecond"
  15210. | "microsecond"
  15211. | "nanosecond"
  15212. >,
  15213. ): Temporal.Instant;
  15214. toZonedDateTime(
  15215. calendarAndTimeZone: { timeZone: TimeZoneLike; calendar: CalendarLike },
  15216. ): Temporal.ZonedDateTime;
  15217. toZonedDateTimeISO(tzLike: TimeZoneLike): Temporal.ZonedDateTime;
  15218. toLocaleString(
  15219. locales?: string | string[],
  15220. options?: Intl.DateTimeFormatOptions,
  15221. ): string;
  15222. toJSON(): string;
  15223. toString(options?: InstantToStringOptions): string;
  15224. valueOf(): never;
  15225. readonly [Symbol.toStringTag]: "Temporal.Instant";
  15226. }
  15227. /**
  15228. * @category Temporal
  15229. * @experimental
  15230. */
  15231. export type YearOrEraAndEraYear = { era: string; eraYear: number } | {
  15232. year: number;
  15233. };
  15234. /**
  15235. * @category Temporal
  15236. * @experimental
  15237. */
  15238. export type MonthCodeOrMonthAndYear =
  15239. | (YearOrEraAndEraYear & { month: number })
  15240. | {
  15241. monthCode: string;
  15242. };
  15243. /**
  15244. * @category Temporal
  15245. * @experimental
  15246. */
  15247. export type MonthOrMonthCode = { month: number } | { monthCode: string };
  15248. /**
  15249. * @category Temporal
  15250. * @experimental
  15251. */
  15252. export interface CalendarProtocol {
  15253. id: string;
  15254. year(
  15255. date:
  15256. | Temporal.PlainDate
  15257. | Temporal.PlainDateTime
  15258. | Temporal.PlainYearMonth
  15259. | PlainDateLike
  15260. | string,
  15261. ): number;
  15262. month(
  15263. date:
  15264. | Temporal.PlainDate
  15265. | Temporal.PlainDateTime
  15266. | Temporal.PlainYearMonth
  15267. | Temporal.PlainMonthDay
  15268. | PlainDateLike
  15269. | string,
  15270. ): number;
  15271. monthCode(
  15272. date:
  15273. | Temporal.PlainDate
  15274. | Temporal.PlainDateTime
  15275. | Temporal.PlainYearMonth
  15276. | Temporal.PlainMonthDay
  15277. | PlainDateLike
  15278. | string,
  15279. ): string;
  15280. day(
  15281. date:
  15282. | Temporal.PlainDate
  15283. | Temporal.PlainDateTime
  15284. | Temporal.PlainMonthDay
  15285. | PlainDateLike
  15286. | string,
  15287. ): number;
  15288. era(
  15289. date:
  15290. | Temporal.PlainDate
  15291. | Temporal.PlainDateTime
  15292. | PlainDateLike
  15293. | string,
  15294. ): string | undefined;
  15295. eraYear(
  15296. date:
  15297. | Temporal.PlainDate
  15298. | Temporal.PlainDateTime
  15299. | PlainDateLike
  15300. | string,
  15301. ): number | undefined;
  15302. dayOfWeek(
  15303. date:
  15304. | Temporal.PlainDate
  15305. | Temporal.PlainDateTime
  15306. | PlainDateLike
  15307. | string,
  15308. ): number;
  15309. dayOfYear(
  15310. date:
  15311. | Temporal.PlainDate
  15312. | Temporal.PlainDateTime
  15313. | PlainDateLike
  15314. | string,
  15315. ): number;
  15316. weekOfYear(
  15317. date:
  15318. | Temporal.PlainDate
  15319. | Temporal.PlainDateTime
  15320. | PlainDateLike
  15321. | string,
  15322. ): number;
  15323. yearOfWeek(
  15324. date:
  15325. | Temporal.PlainDate
  15326. | Temporal.PlainDateTime
  15327. | PlainDateLike
  15328. | string,
  15329. ): number;
  15330. daysInWeek(
  15331. date:
  15332. | Temporal.PlainDate
  15333. | Temporal.PlainDateTime
  15334. | PlainDateLike
  15335. | string,
  15336. ): number;
  15337. daysInMonth(
  15338. date:
  15339. | Temporal.PlainDate
  15340. | Temporal.PlainDateTime
  15341. | Temporal.PlainYearMonth
  15342. | PlainDateLike
  15343. | string,
  15344. ): number;
  15345. daysInYear(
  15346. date:
  15347. | Temporal.PlainDate
  15348. | Temporal.PlainDateTime
  15349. | Temporal.PlainYearMonth
  15350. | PlainDateLike
  15351. | string,
  15352. ): number;
  15353. monthsInYear(
  15354. date:
  15355. | Temporal.PlainDate
  15356. | Temporal.PlainDateTime
  15357. | Temporal.PlainYearMonth
  15358. | PlainDateLike
  15359. | string,
  15360. ): number;
  15361. inLeapYear(
  15362. date:
  15363. | Temporal.PlainDate
  15364. | Temporal.PlainDateTime
  15365. | Temporal.PlainYearMonth
  15366. | PlainDateLike
  15367. | string,
  15368. ): boolean;
  15369. dateFromFields(
  15370. fields: YearOrEraAndEraYear & MonthOrMonthCode & { day: number },
  15371. options?: AssignmentOptions,
  15372. ): Temporal.PlainDate;
  15373. yearMonthFromFields(
  15374. fields: YearOrEraAndEraYear & MonthOrMonthCode,
  15375. options?: AssignmentOptions,
  15376. ): Temporal.PlainYearMonth;
  15377. monthDayFromFields(
  15378. fields: MonthCodeOrMonthAndYear & { day: number },
  15379. options?: AssignmentOptions,
  15380. ): Temporal.PlainMonthDay;
  15381. dateAdd(
  15382. date: Temporal.PlainDate | PlainDateLike | string,
  15383. duration: Temporal.Duration | DurationLike | string,
  15384. options?: ArithmeticOptions,
  15385. ): Temporal.PlainDate;
  15386. dateUntil(
  15387. one: Temporal.PlainDate | PlainDateLike | string,
  15388. two: Temporal.PlainDate | PlainDateLike | string,
  15389. options?: DifferenceOptions<"year" | "month" | "week" | "day">,
  15390. ): Temporal.Duration;
  15391. fields(fields: Iterable<string>): Iterable<string>;
  15392. mergeFields(
  15393. fields: Record<string, unknown>,
  15394. additionalFields: Record<string, unknown>,
  15395. ): Record<string, unknown>;
  15396. toString?(): string;
  15397. toJSON?(): string;
  15398. }
  15399. /**
  15400. * Any of these types can be passed to Temporal methods instead of a Temporal.Calendar.
  15401. *
  15402. * @category Temporal
  15403. * @experimental
  15404. */
  15405. export type CalendarLike =
  15406. | string
  15407. | CalendarProtocol
  15408. | ZonedDateTime
  15409. | PlainDateTime
  15410. | PlainDate
  15411. | PlainYearMonth
  15412. | PlainMonthDay;
  15413. /**
  15414. * A `Temporal.Calendar` is a representation of a calendar system. It includes
  15415. * information about how many days are in each year, how many months are in
  15416. * each year, how many days are in each month, and how to do arithmetic in
  15417. * that calendar system.
  15418. *
  15419. * See https://tc39.es/proposal-temporal/docs/calendar.html for more details.
  15420. *
  15421. * @category Temporal
  15422. * @experimental
  15423. */
  15424. export class Calendar implements CalendarProtocol {
  15425. static from(item: CalendarLike): Temporal.Calendar | CalendarProtocol;
  15426. constructor(calendarIdentifier: string);
  15427. readonly id: string;
  15428. year(
  15429. date:
  15430. | Temporal.PlainDate
  15431. | Temporal.PlainDateTime
  15432. | Temporal.PlainYearMonth
  15433. | PlainDateLike
  15434. | string,
  15435. ): number;
  15436. month(
  15437. date:
  15438. | Temporal.PlainDate
  15439. | Temporal.PlainDateTime
  15440. | Temporal.PlainYearMonth
  15441. | Temporal.PlainMonthDay
  15442. | PlainDateLike
  15443. | string,
  15444. ): number;
  15445. monthCode(
  15446. date:
  15447. | Temporal.PlainDate
  15448. | Temporal.PlainDateTime
  15449. | Temporal.PlainYearMonth
  15450. | Temporal.PlainMonthDay
  15451. | PlainDateLike
  15452. | string,
  15453. ): string;
  15454. day(
  15455. date:
  15456. | Temporal.PlainDate
  15457. | Temporal.PlainDateTime
  15458. | Temporal.PlainMonthDay
  15459. | PlainDateLike
  15460. | string,
  15461. ): number;
  15462. era(
  15463. date:
  15464. | Temporal.PlainDate
  15465. | Temporal.PlainDateTime
  15466. | PlainDateLike
  15467. | string,
  15468. ): string | undefined;
  15469. eraYear(
  15470. date:
  15471. | Temporal.PlainDate
  15472. | Temporal.PlainDateTime
  15473. | PlainDateLike
  15474. | string,
  15475. ): number | undefined;
  15476. dayOfWeek(
  15477. date:
  15478. | Temporal.PlainDate
  15479. | Temporal.PlainDateTime
  15480. | PlainDateLike
  15481. | string,
  15482. ): number;
  15483. dayOfYear(
  15484. date:
  15485. | Temporal.PlainDate
  15486. | Temporal.PlainDateTime
  15487. | PlainDateLike
  15488. | string,
  15489. ): number;
  15490. weekOfYear(
  15491. date:
  15492. | Temporal.PlainDate
  15493. | Temporal.PlainDateTime
  15494. | PlainDateLike
  15495. | string,
  15496. ): number;
  15497. yearOfWeek(
  15498. date:
  15499. | Temporal.PlainDate
  15500. | Temporal.PlainDateTime
  15501. | PlainDateLike
  15502. | string,
  15503. ): number;
  15504. daysInWeek(
  15505. date:
  15506. | Temporal.PlainDate
  15507. | Temporal.PlainDateTime
  15508. | PlainDateLike
  15509. | string,
  15510. ): number;
  15511. daysInMonth(
  15512. date:
  15513. | Temporal.PlainDate
  15514. | Temporal.PlainDateTime
  15515. | Temporal.PlainYearMonth
  15516. | PlainDateLike
  15517. | string,
  15518. ): number;
  15519. daysInYear(
  15520. date:
  15521. | Temporal.PlainDate
  15522. | Temporal.PlainDateTime
  15523. | Temporal.PlainYearMonth
  15524. | PlainDateLike
  15525. | string,
  15526. ): number;
  15527. monthsInYear(
  15528. date:
  15529. | Temporal.PlainDate
  15530. | Temporal.PlainDateTime
  15531. | Temporal.PlainYearMonth
  15532. | PlainDateLike
  15533. | string,
  15534. ): number;
  15535. inLeapYear(
  15536. date:
  15537. | Temporal.PlainDate
  15538. | Temporal.PlainDateTime
  15539. | Temporal.PlainYearMonth
  15540. | PlainDateLike
  15541. | string,
  15542. ): boolean;
  15543. dateFromFields(
  15544. fields: YearOrEraAndEraYear & MonthOrMonthCode & { day: number },
  15545. options?: AssignmentOptions,
  15546. ): Temporal.PlainDate;
  15547. yearMonthFromFields(
  15548. fields: YearOrEraAndEraYear & MonthOrMonthCode,
  15549. options?: AssignmentOptions,
  15550. ): Temporal.PlainYearMonth;
  15551. monthDayFromFields(
  15552. fields: MonthCodeOrMonthAndYear & { day: number },
  15553. options?: AssignmentOptions,
  15554. ): Temporal.PlainMonthDay;
  15555. dateAdd(
  15556. date: Temporal.PlainDate | PlainDateLike | string,
  15557. duration: Temporal.Duration | DurationLike | string,
  15558. options?: ArithmeticOptions,
  15559. ): Temporal.PlainDate;
  15560. dateUntil(
  15561. one: Temporal.PlainDate | PlainDateLike | string,
  15562. two: Temporal.PlainDate | PlainDateLike | string,
  15563. options?: DifferenceOptions<"year" | "month" | "week" | "day">,
  15564. ): Temporal.Duration;
  15565. fields(fields: Iterable<string>): string[];
  15566. mergeFields(
  15567. fields: Record<string, unknown>,
  15568. additionalFields: Record<string, unknown>,
  15569. ): Record<string, unknown>;
  15570. toString(): string;
  15571. toJSON(): string;
  15572. readonly [Symbol.toStringTag]: "Temporal.Calendar";
  15573. }
  15574. /**
  15575. * @category Temporal
  15576. * @experimental
  15577. */
  15578. export type PlainDateLike = {
  15579. era?: string | undefined;
  15580. eraYear?: number | undefined;
  15581. year?: number;
  15582. month?: number;
  15583. monthCode?: string;
  15584. day?: number;
  15585. calendar?: CalendarLike;
  15586. };
  15587. /**
  15588. * @category Temporal
  15589. * @experimental
  15590. */
  15591. export type PlainDateISOFields = {
  15592. isoYear: number;
  15593. isoMonth: number;
  15594. isoDay: number;
  15595. calendar: string | CalendarProtocol;
  15596. };
  15597. /**
  15598. * A `Temporal.PlainDate` represents a calendar date. "Calendar date" refers to the
  15599. * concept of a date as expressed in everyday usage, independent of any time
  15600. * zone. For example, it could be used to represent an event on a calendar
  15601. * which happens during the whole day no matter which time zone it's happening
  15602. * in.
  15603. *
  15604. * See https://tc39.es/proposal-temporal/docs/date.html for more details.
  15605. *
  15606. * @category Temporal
  15607. * @experimental
  15608. */
  15609. export class PlainDate {
  15610. static from(
  15611. item: Temporal.PlainDate | PlainDateLike | string,
  15612. options?: AssignmentOptions,
  15613. ): Temporal.PlainDate;
  15614. static compare(
  15615. one: Temporal.PlainDate | PlainDateLike | string,
  15616. two: Temporal.PlainDate | PlainDateLike | string,
  15617. ): ComparisonResult;
  15618. constructor(
  15619. isoYear: number,
  15620. isoMonth: number,
  15621. isoDay: number,
  15622. calendar?: CalendarLike,
  15623. );
  15624. readonly era: string | undefined;
  15625. readonly eraYear: number | undefined;
  15626. readonly year: number;
  15627. readonly month: number;
  15628. readonly monthCode: string;
  15629. readonly day: number;
  15630. readonly calendarId: string;
  15631. getCalendar(): CalendarProtocol;
  15632. readonly dayOfWeek: number;
  15633. readonly dayOfYear: number;
  15634. readonly weekOfYear: number;
  15635. readonly yearOfWeek: number;
  15636. readonly daysInWeek: number;
  15637. readonly daysInYear: number;
  15638. readonly daysInMonth: number;
  15639. readonly monthsInYear: number;
  15640. readonly inLeapYear: boolean;
  15641. equals(other: Temporal.PlainDate | PlainDateLike | string): boolean;
  15642. with(
  15643. dateLike: PlainDateLike,
  15644. options?: AssignmentOptions,
  15645. ): Temporal.PlainDate;
  15646. withCalendar(calendar: CalendarLike): Temporal.PlainDate;
  15647. add(
  15648. durationLike: Temporal.Duration | DurationLike | string,
  15649. options?: ArithmeticOptions,
  15650. ): Temporal.PlainDate;
  15651. subtract(
  15652. durationLike: Temporal.Duration | DurationLike | string,
  15653. options?: ArithmeticOptions,
  15654. ): Temporal.PlainDate;
  15655. until(
  15656. other: Temporal.PlainDate | PlainDateLike | string,
  15657. options?: DifferenceOptions<"year" | "month" | "week" | "day">,
  15658. ): Temporal.Duration;
  15659. since(
  15660. other: Temporal.PlainDate | PlainDateLike | string,
  15661. options?: DifferenceOptions<"year" | "month" | "week" | "day">,
  15662. ): Temporal.Duration;
  15663. toPlainDateTime(
  15664. temporalTime?: Temporal.PlainTime | PlainTimeLike | string,
  15665. ): Temporal.PlainDateTime;
  15666. toZonedDateTime(
  15667. timeZoneAndTime:
  15668. | TimeZoneProtocol
  15669. | string
  15670. | {
  15671. timeZone: TimeZoneLike;
  15672. plainTime?: Temporal.PlainTime | PlainTimeLike | string;
  15673. },
  15674. ): Temporal.ZonedDateTime;
  15675. toPlainYearMonth(): Temporal.PlainYearMonth;
  15676. toPlainMonthDay(): Temporal.PlainMonthDay;
  15677. getISOFields(): PlainDateISOFields;
  15678. toLocaleString(
  15679. locales?: string | string[],
  15680. options?: Intl.DateTimeFormatOptions,
  15681. ): string;
  15682. toJSON(): string;
  15683. toString(options?: ShowCalendarOption): string;
  15684. valueOf(): never;
  15685. readonly [Symbol.toStringTag]: "Temporal.PlainDate";
  15686. }
  15687. /**
  15688. * @category Temporal
  15689. * @experimental
  15690. */
  15691. export type PlainDateTimeLike = {
  15692. era?: string | undefined;
  15693. eraYear?: number | undefined;
  15694. year?: number;
  15695. month?: number;
  15696. monthCode?: string;
  15697. day?: number;
  15698. hour?: number;
  15699. minute?: number;
  15700. second?: number;
  15701. millisecond?: number;
  15702. microsecond?: number;
  15703. nanosecond?: number;
  15704. calendar?: CalendarLike;
  15705. };
  15706. /**
  15707. * @category Temporal
  15708. * @experimental
  15709. */
  15710. export type PlainDateTimeISOFields = {
  15711. isoYear: number;
  15712. isoMonth: number;
  15713. isoDay: number;
  15714. isoHour: number;
  15715. isoMinute: number;
  15716. isoSecond: number;
  15717. isoMillisecond: number;
  15718. isoMicrosecond: number;
  15719. isoNanosecond: number;
  15720. calendar: string | CalendarProtocol;
  15721. };
  15722. /**
  15723. * A `Temporal.PlainDateTime` represents a calendar date and wall-clock time, with
  15724. * a precision in nanoseconds, and without any time zone. Of the Temporal
  15725. * classes carrying human-readable time information, it is the most general
  15726. * and complete one. `Temporal.PlainDate`, `Temporal.PlainTime`, `Temporal.PlainYearMonth`,
  15727. * and `Temporal.PlainMonthDay` all carry less information and should be used when
  15728. * complete information is not required.
  15729. *
  15730. * See https://tc39.es/proposal-temporal/docs/datetime.html for more details.
  15731. *
  15732. * @category Temporal
  15733. * @experimental
  15734. */
  15735. export class PlainDateTime {
  15736. static from(
  15737. item: Temporal.PlainDateTime | PlainDateTimeLike | string,
  15738. options?: AssignmentOptions,
  15739. ): Temporal.PlainDateTime;
  15740. static compare(
  15741. one: Temporal.PlainDateTime | PlainDateTimeLike | string,
  15742. two: Temporal.PlainDateTime | PlainDateTimeLike | string,
  15743. ): ComparisonResult;
  15744. constructor(
  15745. isoYear: number,
  15746. isoMonth: number,
  15747. isoDay: number,
  15748. hour?: number,
  15749. minute?: number,
  15750. second?: number,
  15751. millisecond?: number,
  15752. microsecond?: number,
  15753. nanosecond?: number,
  15754. calendar?: CalendarLike,
  15755. );
  15756. readonly era: string | undefined;
  15757. readonly eraYear: number | undefined;
  15758. readonly year: number;
  15759. readonly month: number;
  15760. readonly monthCode: string;
  15761. readonly day: number;
  15762. readonly hour: number;
  15763. readonly minute: number;
  15764. readonly second: number;
  15765. readonly millisecond: number;
  15766. readonly microsecond: number;
  15767. readonly nanosecond: number;
  15768. readonly calendarId: string;
  15769. getCalendar(): CalendarProtocol;
  15770. readonly dayOfWeek: number;
  15771. readonly dayOfYear: number;
  15772. readonly weekOfYear: number;
  15773. readonly yearOfWeek: number;
  15774. readonly daysInWeek: number;
  15775. readonly daysInYear: number;
  15776. readonly daysInMonth: number;
  15777. readonly monthsInYear: number;
  15778. readonly inLeapYear: boolean;
  15779. equals(other: Temporal.PlainDateTime | PlainDateTimeLike | string): boolean;
  15780. with(
  15781. dateTimeLike: PlainDateTimeLike,
  15782. options?: AssignmentOptions,
  15783. ): Temporal.PlainDateTime;
  15784. withPlainTime(
  15785. timeLike?: Temporal.PlainTime | PlainTimeLike | string,
  15786. ): Temporal.PlainDateTime;
  15787. withPlainDate(
  15788. dateLike: Temporal.PlainDate | PlainDateLike | string,
  15789. ): Temporal.PlainDateTime;
  15790. withCalendar(calendar: CalendarLike): Temporal.PlainDateTime;
  15791. add(
  15792. durationLike: Temporal.Duration | DurationLike | string,
  15793. options?: ArithmeticOptions,
  15794. ): Temporal.PlainDateTime;
  15795. subtract(
  15796. durationLike: Temporal.Duration | DurationLike | string,
  15797. options?: ArithmeticOptions,
  15798. ): Temporal.PlainDateTime;
  15799. until(
  15800. other: Temporal.PlainDateTime | PlainDateTimeLike | string,
  15801. options?: DifferenceOptions<
  15802. | "year"
  15803. | "month"
  15804. | "week"
  15805. | "day"
  15806. | "hour"
  15807. | "minute"
  15808. | "second"
  15809. | "millisecond"
  15810. | "microsecond"
  15811. | "nanosecond"
  15812. >,
  15813. ): Temporal.Duration;
  15814. since(
  15815. other: Temporal.PlainDateTime | PlainDateTimeLike | string,
  15816. options?: DifferenceOptions<
  15817. | "year"
  15818. | "month"
  15819. | "week"
  15820. | "day"
  15821. | "hour"
  15822. | "minute"
  15823. | "second"
  15824. | "millisecond"
  15825. | "microsecond"
  15826. | "nanosecond"
  15827. >,
  15828. ): Temporal.Duration;
  15829. round(
  15830. roundTo: RoundTo<
  15831. | "day"
  15832. | "hour"
  15833. | "minute"
  15834. | "second"
  15835. | "millisecond"
  15836. | "microsecond"
  15837. | "nanosecond"
  15838. >,
  15839. ): Temporal.PlainDateTime;
  15840. toZonedDateTime(
  15841. tzLike: TimeZoneLike,
  15842. options?: ToInstantOptions,
  15843. ): Temporal.ZonedDateTime;
  15844. toPlainDate(): Temporal.PlainDate;
  15845. toPlainYearMonth(): Temporal.PlainYearMonth;
  15846. toPlainMonthDay(): Temporal.PlainMonthDay;
  15847. toPlainTime(): Temporal.PlainTime;
  15848. getISOFields(): PlainDateTimeISOFields;
  15849. toLocaleString(
  15850. locales?: string | string[],
  15851. options?: Intl.DateTimeFormatOptions,
  15852. ): string;
  15853. toJSON(): string;
  15854. toString(options?: CalendarTypeToStringOptions): string;
  15855. valueOf(): never;
  15856. readonly [Symbol.toStringTag]: "Temporal.PlainDateTime";
  15857. }
  15858. /**
  15859. * @category Temporal
  15860. * @experimental
  15861. */
  15862. export type PlainMonthDayLike = {
  15863. era?: string | undefined;
  15864. eraYear?: number | undefined;
  15865. year?: number;
  15866. month?: number;
  15867. monthCode?: string;
  15868. day?: number;
  15869. calendar?: CalendarLike;
  15870. };
  15871. /**
  15872. * A `Temporal.PlainMonthDay` represents a particular day on the calendar, but
  15873. * without a year. For example, it could be used to represent a yearly
  15874. * recurring event, like "Bastille Day is on the 14th of July."
  15875. *
  15876. * See https://tc39.es/proposal-temporal/docs/monthday.html for more details.
  15877. *
  15878. * @category Temporal
  15879. * @experimental
  15880. */
  15881. export class PlainMonthDay {
  15882. static from(
  15883. item: Temporal.PlainMonthDay | PlainMonthDayLike | string,
  15884. options?: AssignmentOptions,
  15885. ): Temporal.PlainMonthDay;
  15886. constructor(
  15887. isoMonth: number,
  15888. isoDay: number,
  15889. calendar?: CalendarLike,
  15890. referenceISOYear?: number,
  15891. );
  15892. readonly monthCode: string;
  15893. readonly day: number;
  15894. readonly calendarId: string;
  15895. getCalendar(): CalendarProtocol;
  15896. equals(other: Temporal.PlainMonthDay | PlainMonthDayLike | string): boolean;
  15897. with(
  15898. monthDayLike: PlainMonthDayLike,
  15899. options?: AssignmentOptions,
  15900. ): Temporal.PlainMonthDay;
  15901. toPlainDate(year: { year: number }): Temporal.PlainDate;
  15902. getISOFields(): PlainDateISOFields;
  15903. toLocaleString(
  15904. locales?: string | string[],
  15905. options?: Intl.DateTimeFormatOptions,
  15906. ): string;
  15907. toJSON(): string;
  15908. toString(options?: ShowCalendarOption): string;
  15909. valueOf(): never;
  15910. readonly [Symbol.toStringTag]: "Temporal.PlainMonthDay";
  15911. }
  15912. /**
  15913. * @category Temporal
  15914. * @experimental
  15915. */
  15916. export type PlainTimeLike = {
  15917. hour?: number;
  15918. minute?: number;
  15919. second?: number;
  15920. millisecond?: number;
  15921. microsecond?: number;
  15922. nanosecond?: number;
  15923. };
  15924. /**
  15925. * @category Temporal
  15926. * @experimental
  15927. */
  15928. export type PlainTimeISOFields = {
  15929. isoHour: number;
  15930. isoMinute: number;
  15931. isoSecond: number;
  15932. isoMillisecond: number;
  15933. isoMicrosecond: number;
  15934. isoNanosecond: number;
  15935. };
  15936. /**
  15937. * A `Temporal.PlainTime` represents a wall-clock time, with a precision in
  15938. * nanoseconds, and without any time zone. "Wall-clock time" refers to the
  15939. * concept of a time as expressed in everyday usage — the time that you read
  15940. * off the clock on the wall. For example, it could be used to represent an
  15941. * event that happens daily at a certain time, no matter what time zone.
  15942. *
  15943. * `Temporal.PlainTime` refers to a time with no associated calendar date; if you
  15944. * need to refer to a specific time on a specific day, use
  15945. * `Temporal.PlainDateTime`. A `Temporal.PlainTime` can be converted into a
  15946. * `Temporal.PlainDateTime` by combining it with a `Temporal.PlainDate` using the
  15947. * `toPlainDateTime()` method.
  15948. *
  15949. * See https://tc39.es/proposal-temporal/docs/time.html for more details.
  15950. *
  15951. * @category Temporal
  15952. * @experimental
  15953. */
  15954. export class PlainTime {
  15955. static from(
  15956. item: Temporal.PlainTime | PlainTimeLike | string,
  15957. options?: AssignmentOptions,
  15958. ): Temporal.PlainTime;
  15959. static compare(
  15960. one: Temporal.PlainTime | PlainTimeLike | string,
  15961. two: Temporal.PlainTime | PlainTimeLike | string,
  15962. ): ComparisonResult;
  15963. constructor(
  15964. hour?: number,
  15965. minute?: number,
  15966. second?: number,
  15967. millisecond?: number,
  15968. microsecond?: number,
  15969. nanosecond?: number,
  15970. );
  15971. readonly hour: number;
  15972. readonly minute: number;
  15973. readonly second: number;
  15974. readonly millisecond: number;
  15975. readonly microsecond: number;
  15976. readonly nanosecond: number;
  15977. equals(other: Temporal.PlainTime | PlainTimeLike | string): boolean;
  15978. with(
  15979. timeLike: Temporal.PlainTime | PlainTimeLike,
  15980. options?: AssignmentOptions,
  15981. ): Temporal.PlainTime;
  15982. add(
  15983. durationLike: Temporal.Duration | DurationLike | string,
  15984. options?: ArithmeticOptions,
  15985. ): Temporal.PlainTime;
  15986. subtract(
  15987. durationLike: Temporal.Duration | DurationLike | string,
  15988. options?: ArithmeticOptions,
  15989. ): Temporal.PlainTime;
  15990. until(
  15991. other: Temporal.PlainTime | PlainTimeLike | string,
  15992. options?: DifferenceOptions<
  15993. | "hour"
  15994. | "minute"
  15995. | "second"
  15996. | "millisecond"
  15997. | "microsecond"
  15998. | "nanosecond"
  15999. >,
  16000. ): Temporal.Duration;
  16001. since(
  16002. other: Temporal.PlainTime | PlainTimeLike | string,
  16003. options?: DifferenceOptions<
  16004. | "hour"
  16005. | "minute"
  16006. | "second"
  16007. | "millisecond"
  16008. | "microsecond"
  16009. | "nanosecond"
  16010. >,
  16011. ): Temporal.Duration;
  16012. round(
  16013. roundTo: RoundTo<
  16014. | "hour"
  16015. | "minute"
  16016. | "second"
  16017. | "millisecond"
  16018. | "microsecond"
  16019. | "nanosecond"
  16020. >,
  16021. ): Temporal.PlainTime;
  16022. toPlainDateTime(
  16023. temporalDate: Temporal.PlainDate | PlainDateLike | string,
  16024. ): Temporal.PlainDateTime;
  16025. toZonedDateTime(timeZoneAndDate: {
  16026. timeZone: TimeZoneLike;
  16027. plainDate: Temporal.PlainDate | PlainDateLike | string;
  16028. }): Temporal.ZonedDateTime;
  16029. getISOFields(): PlainTimeISOFields;
  16030. toLocaleString(
  16031. locales?: string | string[],
  16032. options?: Intl.DateTimeFormatOptions,
  16033. ): string;
  16034. toJSON(): string;
  16035. toString(options?: ToStringPrecisionOptions): string;
  16036. valueOf(): never;
  16037. readonly [Symbol.toStringTag]: "Temporal.PlainTime";
  16038. }
  16039. /**
  16040. * A plain object implementing the protocol for a custom time zone.
  16041. *
  16042. * @category Temporal
  16043. * @experimental
  16044. */
  16045. export interface TimeZoneProtocol {
  16046. id: string;
  16047. getOffsetNanosecondsFor(instant: Temporal.Instant | string): number;
  16048. getOffsetStringFor?(instant: Temporal.Instant | string): string;
  16049. getPlainDateTimeFor?(
  16050. instant: Temporal.Instant | string,
  16051. calendar?: CalendarLike,
  16052. ): Temporal.PlainDateTime;
  16053. getInstantFor?(
  16054. dateTime: Temporal.PlainDateTime | PlainDateTimeLike | string,
  16055. options?: ToInstantOptions,
  16056. ): Temporal.Instant;
  16057. getNextTransition?(
  16058. startingPoint: Temporal.Instant | string,
  16059. ): Temporal.Instant | null;
  16060. getPreviousTransition?(
  16061. startingPoint: Temporal.Instant | string,
  16062. ): Temporal.Instant | null;
  16063. getPossibleInstantsFor(
  16064. dateTime: Temporal.PlainDateTime | PlainDateTimeLike | string,
  16065. ): Temporal.Instant[];
  16066. toString?(): string;
  16067. toJSON?(): string;
  16068. }
  16069. /**
  16070. * Any of these types can be passed to Temporal methods instead of a Temporal.TimeZone.
  16071. *
  16072. * @category Temporal
  16073. * @experimental
  16074. */
  16075. export type TimeZoneLike = string | TimeZoneProtocol | ZonedDateTime;
  16076. /**
  16077. * A `Temporal.TimeZone` is a representation of a time zone: either an
  16078. * {@link https://www.iana.org/time-zones|IANA time zone}, including
  16079. * information about the time zone such as the offset between the local time
  16080. * and UTC at a particular time, and daylight saving time (DST) changes; or
  16081. * simply a particular UTC offset with no DST.
  16082. *
  16083. * `Temporal.ZonedDateTime` is the only Temporal type to contain a time zone.
  16084. * Other types, like `Temporal.Instant` and `Temporal.PlainDateTime`, do not
  16085. * contain any time zone information, and a `Temporal.TimeZone` object is
  16086. * required to convert between them.
  16087. *
  16088. * See https://tc39.es/proposal-temporal/docs/timezone.html for more details.
  16089. *
  16090. * @category Temporal
  16091. * @experimental
  16092. */
  16093. export class TimeZone implements TimeZoneProtocol {
  16094. static from(timeZone: TimeZoneLike): Temporal.TimeZone | TimeZoneProtocol;
  16095. constructor(timeZoneIdentifier: string);
  16096. readonly id: string;
  16097. equals(timeZone: TimeZoneLike): boolean;
  16098. getOffsetNanosecondsFor(instant: Temporal.Instant | string): number;
  16099. getOffsetStringFor(instant: Temporal.Instant | string): string;
  16100. getPlainDateTimeFor(
  16101. instant: Temporal.Instant | string,
  16102. calendar?: CalendarLike,
  16103. ): Temporal.PlainDateTime;
  16104. getInstantFor(
  16105. dateTime: Temporal.PlainDateTime | PlainDateTimeLike | string,
  16106. options?: ToInstantOptions,
  16107. ): Temporal.Instant;
  16108. getNextTransition(
  16109. startingPoint: Temporal.Instant | string,
  16110. ): Temporal.Instant | null;
  16111. getPreviousTransition(
  16112. startingPoint: Temporal.Instant | string,
  16113. ): Temporal.Instant | null;
  16114. getPossibleInstantsFor(
  16115. dateTime: Temporal.PlainDateTime | PlainDateTimeLike | string,
  16116. ): Temporal.Instant[];
  16117. toString(): string;
  16118. toJSON(): string;
  16119. readonly [Symbol.toStringTag]: "Temporal.TimeZone";
  16120. }
  16121. /**
  16122. * @category Temporal
  16123. * @experimental
  16124. */
  16125. export type PlainYearMonthLike = {
  16126. era?: string | undefined;
  16127. eraYear?: number | undefined;
  16128. year?: number;
  16129. month?: number;
  16130. monthCode?: string;
  16131. calendar?: CalendarLike;
  16132. };
  16133. /**
  16134. * A `Temporal.PlainYearMonth` represents a particular month on the calendar. For
  16135. * example, it could be used to represent a particular instance of a monthly
  16136. * recurring event, like "the June 2019 meeting".
  16137. *
  16138. * See https://tc39.es/proposal-temporal/docs/yearmonth.html for more details.
  16139. *
  16140. * @category Temporal
  16141. * @experimental
  16142. */
  16143. export class PlainYearMonth {
  16144. static from(
  16145. item: Temporal.PlainYearMonth | PlainYearMonthLike | string,
  16146. options?: AssignmentOptions,
  16147. ): Temporal.PlainYearMonth;
  16148. static compare(
  16149. one: Temporal.PlainYearMonth | PlainYearMonthLike | string,
  16150. two: Temporal.PlainYearMonth | PlainYearMonthLike | string,
  16151. ): ComparisonResult;
  16152. constructor(
  16153. isoYear: number,
  16154. isoMonth: number,
  16155. calendar?: CalendarLike,
  16156. referenceISODay?: number,
  16157. );
  16158. readonly era: string | undefined;
  16159. readonly eraYear: number | undefined;
  16160. readonly year: number;
  16161. readonly month: number;
  16162. readonly monthCode: string;
  16163. readonly calendarId: string;
  16164. getCalendar(): CalendarProtocol;
  16165. readonly daysInMonth: number;
  16166. readonly daysInYear: number;
  16167. readonly monthsInYear: number;
  16168. readonly inLeapYear: boolean;
  16169. equals(
  16170. other: Temporal.PlainYearMonth | PlainYearMonthLike | string,
  16171. ): boolean;
  16172. with(
  16173. yearMonthLike: PlainYearMonthLike,
  16174. options?: AssignmentOptions,
  16175. ): Temporal.PlainYearMonth;
  16176. add(
  16177. durationLike: Temporal.Duration | DurationLike | string,
  16178. options?: ArithmeticOptions,
  16179. ): Temporal.PlainYearMonth;
  16180. subtract(
  16181. durationLike: Temporal.Duration | DurationLike | string,
  16182. options?: ArithmeticOptions,
  16183. ): Temporal.PlainYearMonth;
  16184. until(
  16185. other: Temporal.PlainYearMonth | PlainYearMonthLike | string,
  16186. options?: DifferenceOptions<"year" | "month">,
  16187. ): Temporal.Duration;
  16188. since(
  16189. other: Temporal.PlainYearMonth | PlainYearMonthLike | string,
  16190. options?: DifferenceOptions<"year" | "month">,
  16191. ): Temporal.Duration;
  16192. toPlainDate(day: { day: number }): Temporal.PlainDate;
  16193. getISOFields(): PlainDateISOFields;
  16194. toLocaleString(
  16195. locales?: string | string[],
  16196. options?: Intl.DateTimeFormatOptions,
  16197. ): string;
  16198. toJSON(): string;
  16199. toString(options?: ShowCalendarOption): string;
  16200. valueOf(): never;
  16201. readonly [Symbol.toStringTag]: "Temporal.PlainYearMonth";
  16202. }
  16203. /**
  16204. * @category Temporal
  16205. * @experimental
  16206. */
  16207. export type ZonedDateTimeLike = {
  16208. era?: string | undefined;
  16209. eraYear?: number | undefined;
  16210. year?: number;
  16211. month?: number;
  16212. monthCode?: string;
  16213. day?: number;
  16214. hour?: number;
  16215. minute?: number;
  16216. second?: number;
  16217. millisecond?: number;
  16218. microsecond?: number;
  16219. nanosecond?: number;
  16220. offset?: string;
  16221. timeZone?: TimeZoneLike;
  16222. calendar?: CalendarLike;
  16223. };
  16224. /**
  16225. * @category Temporal
  16226. * @experimental
  16227. */
  16228. export type ZonedDateTimeISOFields = {
  16229. isoYear: number;
  16230. isoMonth: number;
  16231. isoDay: number;
  16232. isoHour: number;
  16233. isoMinute: number;
  16234. isoSecond: number;
  16235. isoMillisecond: number;
  16236. isoMicrosecond: number;
  16237. isoNanosecond: number;
  16238. offset: string;
  16239. timeZone: string | TimeZoneProtocol;
  16240. calendar: string | CalendarProtocol;
  16241. };
  16242. /**
  16243. * @category Temporal
  16244. * @experimental
  16245. */
  16246. export class ZonedDateTime {
  16247. static from(
  16248. item: Temporal.ZonedDateTime | ZonedDateTimeLike | string,
  16249. options?: ZonedDateTimeAssignmentOptions,
  16250. ): ZonedDateTime;
  16251. static compare(
  16252. one: Temporal.ZonedDateTime | ZonedDateTimeLike | string,
  16253. two: Temporal.ZonedDateTime | ZonedDateTimeLike | string,
  16254. ): ComparisonResult;
  16255. constructor(
  16256. epochNanoseconds: bigint,
  16257. timeZone: TimeZoneLike,
  16258. calendar?: CalendarLike,
  16259. );
  16260. readonly era: string | undefined;
  16261. readonly eraYear: number | undefined;
  16262. readonly year: number;
  16263. readonly month: number;
  16264. readonly monthCode: string;
  16265. readonly day: number;
  16266. readonly hour: number;
  16267. readonly minute: number;
  16268. readonly second: number;
  16269. readonly millisecond: number;
  16270. readonly microsecond: number;
  16271. readonly nanosecond: number;
  16272. readonly timeZoneId: string;
  16273. getTimeZone(): TimeZoneProtocol;
  16274. readonly calendarId: string;
  16275. getCalendar(): CalendarProtocol;
  16276. readonly dayOfWeek: number;
  16277. readonly dayOfYear: number;
  16278. readonly weekOfYear: number;
  16279. readonly yearOfWeek: number;
  16280. readonly hoursInDay: number;
  16281. readonly daysInWeek: number;
  16282. readonly daysInMonth: number;
  16283. readonly daysInYear: number;
  16284. readonly monthsInYear: number;
  16285. readonly inLeapYear: boolean;
  16286. readonly offsetNanoseconds: number;
  16287. readonly offset: string;
  16288. readonly epochSeconds: number;
  16289. readonly epochMilliseconds: number;
  16290. readonly epochMicroseconds: bigint;
  16291. readonly epochNanoseconds: bigint;
  16292. equals(other: Temporal.ZonedDateTime | ZonedDateTimeLike | string): boolean;
  16293. with(
  16294. zonedDateTimeLike: ZonedDateTimeLike,
  16295. options?: ZonedDateTimeAssignmentOptions,
  16296. ): Temporal.ZonedDateTime;
  16297. withPlainTime(
  16298. timeLike?: Temporal.PlainTime | PlainTimeLike | string,
  16299. ): Temporal.ZonedDateTime;
  16300. withPlainDate(
  16301. dateLike: Temporal.PlainDate | PlainDateLike | string,
  16302. ): Temporal.ZonedDateTime;
  16303. withCalendar(calendar: CalendarLike): Temporal.ZonedDateTime;
  16304. withTimeZone(timeZone: TimeZoneLike): Temporal.ZonedDateTime;
  16305. add(
  16306. durationLike: Temporal.Duration | DurationLike | string,
  16307. options?: ArithmeticOptions,
  16308. ): Temporal.ZonedDateTime;
  16309. subtract(
  16310. durationLike: Temporal.Duration | DurationLike | string,
  16311. options?: ArithmeticOptions,
  16312. ): Temporal.ZonedDateTime;
  16313. until(
  16314. other: Temporal.ZonedDateTime | ZonedDateTimeLike | string,
  16315. options?: Temporal.DifferenceOptions<
  16316. | "year"
  16317. | "month"
  16318. | "week"
  16319. | "day"
  16320. | "hour"
  16321. | "minute"
  16322. | "second"
  16323. | "millisecond"
  16324. | "microsecond"
  16325. | "nanosecond"
  16326. >,
  16327. ): Temporal.Duration;
  16328. since(
  16329. other: Temporal.ZonedDateTime | ZonedDateTimeLike | string,
  16330. options?: Temporal.DifferenceOptions<
  16331. | "year"
  16332. | "month"
  16333. | "week"
  16334. | "day"
  16335. | "hour"
  16336. | "minute"
  16337. | "second"
  16338. | "millisecond"
  16339. | "microsecond"
  16340. | "nanosecond"
  16341. >,
  16342. ): Temporal.Duration;
  16343. round(
  16344. roundTo: RoundTo<
  16345. | "day"
  16346. | "hour"
  16347. | "minute"
  16348. | "second"
  16349. | "millisecond"
  16350. | "microsecond"
  16351. | "nanosecond"
  16352. >,
  16353. ): Temporal.ZonedDateTime;
  16354. startOfDay(): Temporal.ZonedDateTime;
  16355. toInstant(): Temporal.Instant;
  16356. toPlainDateTime(): Temporal.PlainDateTime;
  16357. toPlainDate(): Temporal.PlainDate;
  16358. toPlainYearMonth(): Temporal.PlainYearMonth;
  16359. toPlainMonthDay(): Temporal.PlainMonthDay;
  16360. toPlainTime(): Temporal.PlainTime;
  16361. getISOFields(): ZonedDateTimeISOFields;
  16362. toLocaleString(
  16363. locales?: string | string[],
  16364. options?: Intl.DateTimeFormatOptions,
  16365. ): string;
  16366. toJSON(): string;
  16367. toString(options?: ZonedDateTimeToStringOptions): string;
  16368. valueOf(): never;
  16369. readonly [Symbol.toStringTag]: "Temporal.ZonedDateTime";
  16370. }
  16371. /**
  16372. * The `Temporal.Now` object has several methods which give information about
  16373. * the current date, time, and time zone.
  16374. *
  16375. * See https://tc39.es/proposal-temporal/docs/now.html for more details.
  16376. *
  16377. * @category Temporal
  16378. * @experimental
  16379. */
  16380. export const Now: {
  16381. /**
  16382. * Get the exact system date and time as a `Temporal.Instant`.
  16383. *
  16384. * This method gets the current exact system time, without regard to
  16385. * calendar or time zone. This is a good way to get a timestamp for an
  16386. * event, for example. It works like the old-style JavaScript `Date.now()`,
  16387. * but with nanosecond precision instead of milliseconds.
  16388. *
  16389. * Note that a `Temporal.Instant` doesn't know about time zones. For the
  16390. * exact time in a specific time zone, use `Temporal.Now.zonedDateTimeISO`
  16391. * or `Temporal.Now.zonedDateTime`.
  16392. */
  16393. instant: () => Temporal.Instant;
  16394. /**
  16395. * Get the current calendar date and clock time in a specific calendar and
  16396. * time zone.
  16397. *
  16398. * The `calendar` parameter is required. When using the ISO 8601 calendar or
  16399. * if you don't understand the need for or implications of a calendar, then
  16400. * a more ergonomic alternative to this method is
  16401. * `Temporal.Now.zonedDateTimeISO()`.
  16402. *
  16403. * @param {CalendarLike} [calendar] - calendar identifier, or
  16404. * a `Temporal.Calendar` instance, or an object implementing the calendar
  16405. * protocol.
  16406. * @param {TimeZoneLike} [tzLike] -
  16407. * {@link https://en.wikipedia.org/wiki/List_of_tz_database_time_zones|IANA time zone identifier}
  16408. * string (e.g. `'Europe/London'`), `Temporal.TimeZone` instance, or an
  16409. * object implementing the time zone protocol. If omitted, the environment's
  16410. * current time zone will be used.
  16411. */
  16412. zonedDateTime: (
  16413. calendar: CalendarLike,
  16414. tzLike?: TimeZoneLike,
  16415. ) => Temporal.ZonedDateTime;
  16416. /**
  16417. * Get the current calendar date and clock time in a specific time zone,
  16418. * using the ISO 8601 calendar.
  16419. *
  16420. * @param {TimeZoneLike} [tzLike] -
  16421. * {@link https://en.wikipedia.org/wiki/List_of_tz_database_time_zones|IANA time zone identifier}
  16422. * string (e.g. `'Europe/London'`), `Temporal.TimeZone` instance, or an
  16423. * object implementing the time zone protocol. If omitted, the environment's
  16424. * current time zone will be used.
  16425. */
  16426. zonedDateTimeISO: (tzLike?: TimeZoneLike) => Temporal.ZonedDateTime;
  16427. /**
  16428. * Get the current calendar date and clock time in a specific calendar and
  16429. * time zone.
  16430. *
  16431. * The calendar is required. When using the ISO 8601 calendar or if you
  16432. * don't understand the need for or implications of a calendar, then a more
  16433. * ergonomic alternative to this method is `Temporal.Now.plainDateTimeISO`.
  16434. *
  16435. * Note that the `Temporal.PlainDateTime` type does not persist the time zone,
  16436. * but retaining the time zone is required for most time-zone-related use
  16437. * cases. Therefore, it's usually recommended to use
  16438. * `Temporal.Now.zonedDateTimeISO` or `Temporal.Now.zonedDateTime` instead
  16439. * of this function.
  16440. *
  16441. * @param {CalendarLike} [calendar] - calendar identifier, or
  16442. * a `Temporal.Calendar` instance, or an object implementing the calendar
  16443. * protocol.
  16444. * @param {TimeZoneLike} [tzLike] -
  16445. * {@link https://en.wikipedia.org/wiki/List_of_tz_database_time_zones|IANA time zone identifier}
  16446. * string (e.g. `'Europe/London'`), `Temporal.TimeZone` instance, or an
  16447. * object implementing the time zone protocol. If omitted,
  16448. * the environment's current time zone will be used.
  16449. */
  16450. plainDateTime: (
  16451. calendar: CalendarLike,
  16452. tzLike?: TimeZoneLike,
  16453. ) => Temporal.PlainDateTime;
  16454. /**
  16455. * Get the current date and clock time in a specific time zone, using the
  16456. * ISO 8601 calendar.
  16457. *
  16458. * Note that the `Temporal.PlainDateTime` type does not persist the time zone,
  16459. * but retaining the time zone is required for most time-zone-related use
  16460. * cases. Therefore, it's usually recommended to use
  16461. * `Temporal.Now.zonedDateTimeISO` instead of this function.
  16462. *
  16463. * @param {TimeZoneLike} [tzLike] -
  16464. * {@link https://en.wikipedia.org/wiki/List_of_tz_database_time_zones|IANA time zone identifier}
  16465. * string (e.g. `'Europe/London'`), `Temporal.TimeZone` instance, or an
  16466. * object implementing the time zone protocol. If omitted, the environment's
  16467. * current time zone will be used.
  16468. */
  16469. plainDateTimeISO: (tzLike?: TimeZoneLike) => Temporal.PlainDateTime;
  16470. /**
  16471. * Get the current calendar date in a specific calendar and time zone.
  16472. *
  16473. * The calendar is required. When using the ISO 8601 calendar or if you
  16474. * don't understand the need for or implications of a calendar, then a more
  16475. * ergonomic alternative to this method is `Temporal.Now.plainDateISO`.
  16476. *
  16477. * @param {CalendarLike} [calendar] - calendar identifier, or
  16478. * a `Temporal.Calendar` instance, or an object implementing the calendar
  16479. * protocol.
  16480. * @param {TimeZoneLike} [tzLike] -
  16481. * {@link https://en.wikipedia.org/wiki/List_of_tz_database_time_zones|IANA time zone identifier}
  16482. * string (e.g. `'Europe/London'`), `Temporal.TimeZone` instance, or an
  16483. * object implementing the time zone protocol. If omitted,
  16484. * the environment's current time zone will be used.
  16485. */
  16486. plainDate: (
  16487. calendar: CalendarLike,
  16488. tzLike?: TimeZoneLike,
  16489. ) => Temporal.PlainDate;
  16490. /**
  16491. * Get the current date in a specific time zone, using the ISO 8601
  16492. * calendar.
  16493. *
  16494. * @param {TimeZoneLike} [tzLike] -
  16495. * {@link https://en.wikipedia.org/wiki/List_of_tz_database_time_zones|IANA time zone identifier}
  16496. * string (e.g. `'Europe/London'`), `Temporal.TimeZone` instance, or an
  16497. * object implementing the time zone protocol. If omitted, the environment's
  16498. * current time zone will be used.
  16499. */
  16500. plainDateISO: (tzLike?: TimeZoneLike) => Temporal.PlainDate;
  16501. /**
  16502. * Get the current clock time in a specific time zone, using the ISO 8601 calendar.
  16503. *
  16504. * @param {TimeZoneLike} [tzLike] -
  16505. * {@link https://en.wikipedia.org/wiki/List_of_tz_database_time_zones|IANA time zone identifier}
  16506. * string (e.g. `'Europe/London'`), `Temporal.TimeZone` instance, or an
  16507. * object implementing the time zone protocol. If omitted, the environment's
  16508. * current time zone will be used.
  16509. */
  16510. plainTimeISO: (tzLike?: TimeZoneLike) => Temporal.PlainTime;
  16511. /**
  16512. * Get the identifier of the environment's current time zone.
  16513. *
  16514. * This method gets the identifier of the current system time zone. This
  16515. * will usually be a named
  16516. * {@link https://en.wikipedia.org/wiki/List_of_tz_database_time_zones|IANA time zone}.
  16517. */
  16518. timeZoneId: () => string;
  16519. readonly [Symbol.toStringTag]: "Temporal.Now";
  16520. };
  16521. }
  16522. /**
  16523. * @category Temporal
  16524. * @experimental
  16525. */
  16526. declare interface Date {
  16527. toTemporalInstant(): Temporal.Instant;
  16528. }
  16529. /**
  16530. * @category Intl
  16531. * @experimental
  16532. */
  16533. declare namespace Intl {
  16534. /**
  16535. * @category Intl
  16536. * @experimental
  16537. */
  16538. export type Formattable =
  16539. | Date
  16540. | Temporal.Instant
  16541. | Temporal.ZonedDateTime
  16542. | Temporal.PlainDate
  16543. | Temporal.PlainTime
  16544. | Temporal.PlainDateTime
  16545. | Temporal.PlainYearMonth
  16546. | Temporal.PlainMonthDay;
  16547. /**
  16548. * @category Intl
  16549. * @experimental
  16550. */
  16551. export interface DateTimeFormatRangePart {
  16552. source: "shared" | "startRange" | "endRange";
  16553. }
  16554. /**
  16555. * @category Intl
  16556. * @experimental
  16557. */
  16558. export interface DateTimeFormat {
  16559. /**
  16560. * Format a date into a string according to the locale and formatting
  16561. * options of this `Intl.DateTimeFormat` object.
  16562. *
  16563. * @param date The date to format.
  16564. */
  16565. format(date?: Formattable | number): string;
  16566. /**
  16567. * Allow locale-aware formatting of strings produced by
  16568. * `Intl.DateTimeFormat` formatters.
  16569. *
  16570. * @param date The date to format.
  16571. */
  16572. formatToParts(
  16573. date?: Formattable | number,
  16574. ): globalThis.Intl.DateTimeFormatPart[];
  16575. /**
  16576. * Format a date range in the most concise way based on the locale and
  16577. * options provided when instantiating this `Intl.DateTimeFormat` object.
  16578. *
  16579. * @param startDate The start date of the range to format.
  16580. * @param endDate The start date of the range to format. Must be the same
  16581. * type as `startRange`.
  16582. */
  16583. formatRange<T extends Formattable>(startDate: T, endDate: T): string;
  16584. formatRange(startDate: Date | number, endDate: Date | number): string;
  16585. /**
  16586. * Allow locale-aware formatting of tokens representing each part of the
  16587. * formatted date range produced by `Intl.DateTimeFormat` formatters.
  16588. *
  16589. * @param startDate The start date of the range to format.
  16590. * @param endDate The start date of the range to format. Must be the same
  16591. * type as `startRange`.
  16592. */
  16593. formatRangeToParts<T extends Formattable>(
  16594. startDate: T,
  16595. endDate: T,
  16596. ): DateTimeFormatRangePart[];
  16597. formatRangeToParts(
  16598. startDate: Date | number,
  16599. endDate: Date | number,
  16600. ): DateTimeFormatRangePart[];
  16601. }
  16602. /**
  16603. * @category Intl
  16604. * @experimental
  16605. */
  16606. export interface DateTimeFormatOptions {
  16607. // TODO: remove the props below after TS lib declarations are updated
  16608. dayPeriod?: "narrow" | "short" | "long";
  16609. dateStyle?: "full" | "long" | "medium" | "short";
  16610. timeStyle?: "full" | "long" | "medium" | "short";
  16611. }
  16612. }
  16613. /**
  16614. * A typed array of 16-bit float values. The contents are initialized to 0. If the requested number
  16615. * of bytes could not be allocated an exception is raised.
  16616. *
  16617. * @category Platform
  16618. * @experimental
  16619. */
  16620. declare interface Float16Array {
  16621. /**
  16622. * The size in bytes of each element in the array.
  16623. */
  16624. readonly BYTES_PER_ELEMENT: number;
  16625. /**
  16626. * The ArrayBuffer instance referenced by the array.
  16627. */
  16628. readonly buffer: ArrayBufferLike;
  16629. /**
  16630. * The length in bytes of the array.
  16631. */
  16632. readonly byteLength: number;
  16633. /**
  16634. * The offset in bytes of the array.
  16635. */
  16636. readonly byteOffset: number;
  16637. /**
  16638. * Returns the this object after copying a section of the array identified by start and end
  16639. * to the same array starting at position target
  16640. * @param target If target is negative, it is treated as length+target where length is the
  16641. * length of the array.
  16642. * @param start If start is negative, it is treated as length+start. If end is negative, it
  16643. * is treated as length+end.
  16644. * @param end If not specified, length of the this object is used as its default value.
  16645. */
  16646. copyWithin(target: number, start: number, end?: number): this;
  16647. /**
  16648. * Determines whether all the members of an array satisfy the specified test.
  16649. * @param predicate A function that accepts up to three arguments. The every method calls
  16650. * the predicate function for each element in the array until the predicate returns a value
  16651. * which is coercible to the Boolean value false, or until the end of the array.
  16652. * @param thisArg An object to which the this keyword can refer in the predicate function.
  16653. * If thisArg is omitted, undefined is used as the this value.
  16654. */
  16655. every(
  16656. predicate: (value: number, index: number, array: Float16Array) => unknown,
  16657. thisArg?: any,
  16658. ): boolean;
  16659. /**
  16660. * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
  16661. * @param value value to fill array section with
  16662. * @param start index to start filling the array at. If start is negative, it is treated as
  16663. * length+start where length is the length of the array.
  16664. * @param end index to stop filling the array at. If end is negative, it is treated as
  16665. * length+end.
  16666. */
  16667. fill(value: number, start?: number, end?: number): this;
  16668. /**
  16669. * Returns the elements of an array that meet the condition specified in a callback function.
  16670. * @param predicate A function that accepts up to three arguments. The filter method calls
  16671. * the predicate function one time for each element in the array.
  16672. * @param thisArg An object to which the this keyword can refer in the predicate function.
  16673. * If thisArg is omitted, undefined is used as the this value.
  16674. */
  16675. filter(
  16676. predicate: (value: number, index: number, array: Float16Array) => any,
  16677. thisArg?: any,
  16678. ): Float16Array;
  16679. /**
  16680. * Returns the value of the first element in the array where predicate is true, and undefined
  16681. * otherwise.
  16682. * @param predicate find calls predicate once for each element of the array, in ascending
  16683. * order, until it finds one where predicate returns true. If such an element is found, find
  16684. * immediately returns that element value. Otherwise, find returns undefined.
  16685. * @param thisArg If provided, it will be used as the this value for each invocation of
  16686. * predicate. If it is not provided, undefined is used instead.
  16687. */
  16688. find(
  16689. predicate: (value: number, index: number, obj: Float16Array) => boolean,
  16690. thisArg?: any,
  16691. ): number | undefined;
  16692. /**
  16693. * Returns the index of the first element in the array where predicate is true, and -1
  16694. * otherwise.
  16695. * @param predicate find calls predicate once for each element of the array, in ascending
  16696. * order, until it finds one where predicate returns true. If such an element is found,
  16697. * findIndex immediately returns that element index. Otherwise, findIndex returns -1.
  16698. * @param thisArg If provided, it will be used as the this value for each invocation of
  16699. * predicate. If it is not provided, undefined is used instead.
  16700. */
  16701. findIndex(
  16702. predicate: (value: number, index: number, obj: Float16Array) => boolean,
  16703. thisArg?: any,
  16704. ): number;
  16705. /**
  16706. * Performs the specified action for each element in an array.
  16707. * @param callbackfn A function that accepts up to three arguments. forEach calls the
  16708. * callbackfn function one time for each element in the array.
  16709. * @param thisArg An object to which the this keyword can refer in the callbackfn function.
  16710. * If thisArg is omitted, undefined is used as the this value.
  16711. */
  16712. forEach(
  16713. callbackfn: (value: number, index: number, array: Float16Array) => void,
  16714. thisArg?: any,
  16715. ): void;
  16716. /**
  16717. * Returns the index of the first occurrence of a value in an array.
  16718. * @param searchElement The value to locate in the array.
  16719. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
  16720. * search starts at index 0.
  16721. */
  16722. indexOf(searchElement: number, fromIndex?: number): number;
  16723. /**
  16724. * Adds all the elements of an array separated by the specified separator string.
  16725. * @param separator A string used to separate one element of an array from the next in the
  16726. * resulting String. If omitted, the array elements are separated with a comma.
  16727. */
  16728. join(separator?: string): string;
  16729. /**
  16730. * Returns the index of the last occurrence of a value in an array.
  16731. * @param searchElement The value to locate in the array.
  16732. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
  16733. * search starts at index 0.
  16734. */
  16735. lastIndexOf(searchElement: number, fromIndex?: number): number;
  16736. /**
  16737. * The length of the array.
  16738. */
  16739. readonly length: number;
  16740. /**
  16741. * Calls a defined callback function on each element of an array, and returns an array that
  16742. * contains the results.
  16743. * @param callbackfn A function that accepts up to three arguments. The map method calls the
  16744. * callbackfn function one time for each element in the array.
  16745. * @param thisArg An object to which the this keyword can refer in the callbackfn function.
  16746. * If thisArg is omitted, undefined is used as the this value.
  16747. */
  16748. map(
  16749. callbackfn: (value: number, index: number, array: Float16Array) => number,
  16750. thisArg?: any,
  16751. ): Float16Array;
  16752. /**
  16753. * Calls the specified callback function for all the elements in an array. The return value of
  16754. * the callback function is the accumulated result, and is provided as an argument in the next
  16755. * call to the callback function.
  16756. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the
  16757. * callbackfn function one time for each element in the array.
  16758. * @param initialValue If initialValue is specified, it is used as the initial value to start
  16759. * the accumulation. The first call to the callbackfn function provides this value as an argument
  16760. * instead of an array value.
  16761. */
  16762. reduce(
  16763. callbackfn: (
  16764. previousValue: number,
  16765. currentValue: number,
  16766. currentIndex: number,
  16767. array: Float16Array,
  16768. ) => number,
  16769. ): number;
  16770. reduce(
  16771. callbackfn: (
  16772. previousValue: number,
  16773. currentValue: number,
  16774. currentIndex: number,
  16775. array: Float16Array,
  16776. ) => number,
  16777. initialValue: number,
  16778. ): number;
  16779. /**
  16780. * Calls the specified callback function for all the elements in an array. The return value of
  16781. * the callback function is the accumulated result, and is provided as an argument in the next
  16782. * call to the callback function.
  16783. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the
  16784. * callbackfn function one time for each element in the array.
  16785. * @param initialValue If initialValue is specified, it is used as the initial value to start
  16786. * the accumulation. The first call to the callbackfn function provides this value as an argument
  16787. * instead of an array value.
  16788. */
  16789. reduce<U>(
  16790. callbackfn: (
  16791. previousValue: U,
  16792. currentValue: number,
  16793. currentIndex: number,
  16794. array: Float16Array,
  16795. ) => U,
  16796. initialValue: U,
  16797. ): U;
  16798. /**
  16799. * Calls the specified callback function for all the elements in an array, in descending order.
  16800. * The return value of the callback function is the accumulated result, and is provided as an
  16801. * argument in the next call to the callback function.
  16802. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
  16803. * the callbackfn function one time for each element in the array.
  16804. * @param initialValue If initialValue is specified, it is used as the initial value to start
  16805. * the accumulation. The first call to the callbackfn function provides this value as an
  16806. * argument instead of an array value.
  16807. */
  16808. reduceRight(
  16809. callbackfn: (
  16810. previousValue: number,
  16811. currentValue: number,
  16812. currentIndex: number,
  16813. array: Float16Array,
  16814. ) => number,
  16815. ): number;
  16816. reduceRight(
  16817. callbackfn: (
  16818. previousValue: number,
  16819. currentValue: number,
  16820. currentIndex: number,
  16821. array: Float16Array,
  16822. ) => number,
  16823. initialValue: number,
  16824. ): number;
  16825. /**
  16826. * Calls the specified callback function for all the elements in an array, in descending order.
  16827. * The return value of the callback function is the accumulated result, and is provided as an
  16828. * argument in the next call to the callback function.
  16829. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
  16830. * the callbackfn function one time for each element in the array.
  16831. * @param initialValue If initialValue is specified, it is used as the initial value to start
  16832. * the accumulation. The first call to the callbackfn function provides this value as an argument
  16833. * instead of an array value.
  16834. */
  16835. reduceRight<U>(
  16836. callbackfn: (
  16837. previousValue: U,
  16838. currentValue: number,
  16839. currentIndex: number,
  16840. array: Float16Array,
  16841. ) => U,
  16842. initialValue: U,
  16843. ): U;
  16844. /**
  16845. * Reverses the elements in an Array.
  16846. */
  16847. reverse(): Float16Array;
  16848. /**
  16849. * Sets a value or an array of values.
  16850. * @param array A typed or untyped array of values to set.
  16851. * @param offset The index in the current array at which the values are to be written.
  16852. */
  16853. set(array: ArrayLike<number>, offset?: number): void;
  16854. /**
  16855. * Returns a section of an array.
  16856. * @param start The beginning of the specified portion of the array.
  16857. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
  16858. */
  16859. slice(start?: number, end?: number): Float16Array;
  16860. /**
  16861. * Determines whether the specified callback function returns true for any element of an array.
  16862. * @param predicate A function that accepts up to three arguments. The some method calls
  16863. * the predicate function for each element in the array until the predicate returns a value
  16864. * which is coercible to the Boolean value true, or until the end of the array.
  16865. * @param thisArg An object to which the this keyword can refer in the predicate function.
  16866. * If thisArg is omitted, undefined is used as the this value.
  16867. */
  16868. some(
  16869. predicate: (value: number, index: number, array: Float16Array) => unknown,
  16870. thisArg?: any,
  16871. ): boolean;
  16872. /**
  16873. * Sorts an array.
  16874. * @param compareFn Function used to determine the order of the elements. It is expected to return
  16875. * a negative value if first argument is less than second argument, zero if they're equal and a positive
  16876. * value otherwise. If omitted, the elements are sorted in ascending order.
  16877. * ```ts
  16878. * [11,2,22,1].sort((a, b) => a - b)
  16879. * ```
  16880. */
  16881. sort(compareFn?: (a: number, b: number) => number): this;
  16882. /**
  16883. * Gets a new Float16Array view of the ArrayBuffer store for this array, referencing the elements
  16884. * at begin, inclusive, up to end, exclusive.
  16885. * @param begin The index of the beginning of the array.
  16886. * @param end The index of the end of the array.
  16887. */
  16888. subarray(begin?: number, end?: number): Float16Array;
  16889. /**
  16890. * Converts a number to a string by using the current locale.
  16891. */
  16892. toLocaleString(): string;
  16893. /**
  16894. * Returns a string representation of an array.
  16895. */
  16896. toString(): string;
  16897. /** Returns the primitive value of the specified object. */
  16898. valueOf(): Float16Array;
  16899. [index: number]: number;
  16900. }
  16901. /**
  16902. * @category Platform
  16903. * @experimental
  16904. */
  16905. declare interface Float16ArrayConstructor {
  16906. readonly prototype: Float16Array;
  16907. new (length: number): Float16Array;
  16908. new (array: ArrayLike<number> | ArrayBufferLike): Float16Array;
  16909. new (
  16910. buffer: ArrayBufferLike,
  16911. byteOffset?: number,
  16912. length?: number,
  16913. ): Float16Array;
  16914. /**
  16915. * The size in bytes of each element in the array.
  16916. */
  16917. readonly BYTES_PER_ELEMENT: number;
  16918. /**
  16919. * Returns a new array from a set of elements.
  16920. * @param items A set of elements to include in the new array object.
  16921. */
  16922. of(...items: number[]): Float16Array;
  16923. /**
  16924. * Creates an array from an array-like or iterable object.
  16925. * @param arrayLike An array-like or iterable object to convert to an array.
  16926. */
  16927. from(arrayLike: ArrayLike<number>): Float16Array;
  16928. /**
  16929. * Creates an array from an array-like or iterable object.
  16930. * @param arrayLike An array-like or iterable object to convert to an array.
  16931. * @param mapfn A mapping function to call on every element of the array.
  16932. * @param thisArg Value of 'this' used to invoke the mapfn.
  16933. */
  16934. from<T>(
  16935. arrayLike: ArrayLike<T>,
  16936. mapfn: (v: T, k: number) => number,
  16937. thisArg?: any,
  16938. ): Float16Array;
  16939. }
  16940. /**
  16941. * @category Platform
  16942. * @experimental
  16943. */
  16944. declare var Float16Array: Float16ArrayConstructor;
  16945. /**
  16946. * @category Platform
  16947. * @experimental
  16948. */
  16949. declare interface Float16 {
  16950. [Symbol.iterator](): IterableIterator<number>;
  16951. /**
  16952. * Returns an array of key, value pairs for every entry in the array
  16953. */
  16954. entries(): IterableIterator<[number, number]>;
  16955. /**
  16956. * Returns an list of keys in the array
  16957. */
  16958. keys(): IterableIterator<number>;
  16959. /**
  16960. * Returns an list of values in the array
  16961. */
  16962. values(): IterableIterator<number>;
  16963. }
  16964. /**
  16965. * @category Platform
  16966. * @experimental
  16967. */
  16968. declare interface Float16Constructor {
  16969. new (elements: Iterable<number>): Float16;
  16970. /**
  16971. * Creates an array from an array-like or iterable object.
  16972. * @param arrayLike An array-like or iterable object to convert to an array.
  16973. * @param mapfn A mapping function to call on every element of the array.
  16974. * @param thisArg Value of 'this' used to invoke the mapfn.
  16975. */
  16976. from(
  16977. arrayLike: Iterable<number>,
  16978. mapfn?: (v: number, k: number) => number,
  16979. thisArg?: any,
  16980. ): Float16;
  16981. }
  16982. /**
  16983. * @category Platform
  16984. * @experimental
  16985. */
  16986. declare interface Float16Array {
  16987. readonly [Symbol.toStringTag]: "Float16Array";
  16988. }
  16989. /**
  16990. * @category Platform
  16991. * @experimental
  16992. */
  16993. declare interface Float16Array {
  16994. /**
  16995. * Determines whether an array includes a certain element, returning true or false as appropriate.
  16996. * @param searchElement The element to search for.
  16997. * @param fromIndex The position in this array at which to begin searching for searchElement.
  16998. */
  16999. includes(searchElement: number, fromIndex?: number): boolean;
  17000. }
  17001. /**
  17002. * @category Platform
  17003. * @experimental
  17004. */
  17005. declare interface Float16ArrayConstructor {
  17006. new (): Float16Array;
  17007. }
  17008. /**
  17009. * @category Platform
  17010. * @experimental
  17011. */
  17012. declare interface Float16Array {
  17013. /**
  17014. * Returns the item located at the specified index.
  17015. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
  17016. */
  17017. at(index: number): number | undefined;
  17018. }
  17019. /**
  17020. * @category Platform
  17021. * @experimental
  17022. */
  17023. declare interface Float16Array {
  17024. /**
  17025. * Returns the value of the last element in the array where predicate is true, and undefined
  17026. * otherwise.
  17027. * @param predicate findLast calls predicate once for each element of the array, in descending
  17028. * order, until it finds one where predicate returns true. If such an element is found, findLast
  17029. * immediately returns that element value. Otherwise, findLast returns undefined.
  17030. * @param thisArg If provided, it will be used as the this value for each invocation of
  17031. * predicate. If it is not provided, undefined is used instead.
  17032. */
  17033. findLast<S extends number>(
  17034. predicate: (
  17035. value: number,
  17036. index: number,
  17037. array: Float16Array,
  17038. ) => value is S,
  17039. thisArg?: any,
  17040. ): S | undefined;
  17041. findLast(
  17042. predicate: (
  17043. value: number,
  17044. index: number,
  17045. array: Float16Array,
  17046. ) => unknown,
  17047. thisArg?: any,
  17048. ): number | undefined;
  17049. /**
  17050. * Returns the index of the last element in the array where predicate is true, and -1
  17051. * otherwise.
  17052. * @param predicate findLastIndex calls predicate once for each element of the array, in descending
  17053. * order, until it finds one where predicate returns true. If such an element is found,
  17054. * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
  17055. * @param thisArg If provided, it will be used as the this value for each invocation of
  17056. * predicate. If it is not provided, undefined is used instead.
  17057. */
  17058. findLastIndex(
  17059. predicate: (
  17060. value: number,
  17061. index: number,
  17062. array: Float16Array,
  17063. ) => unknown,
  17064. thisArg?: any,
  17065. ): number;
  17066. /**
  17067. * Copies the array and returns the copy with the elements in reverse order.
  17068. */
  17069. toReversed(): Float16Array;
  17070. /**
  17071. * Copies and sorts the array.
  17072. * @param compareFn Function used to determine the order of the elements. It is expected to return
  17073. * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
  17074. * value otherwise. If omitted, the elements are sorted in ascending order.
  17075. * ```ts
  17076. * const myNums = Float16Array.from([11.25, 2, -22.5, 1]);
  17077. * myNums.toSorted((a, b) => a - b) // Float16Array(4) [-22.5, 1, 2, 11.5]
  17078. * ```
  17079. */
  17080. toSorted(compareFn?: (a: number, b: number) => number): Float16Array;
  17081. /**
  17082. * Copies the array and inserts the given number at the provided index.
  17083. * @param index The index of the value to overwrite. If the index is
  17084. * negative, then it replaces from the end of the array.
  17085. * @param value The value to insert into the copied array.
  17086. * @returns A copy of the original array with the inserted value.
  17087. */
  17088. with(index: number, value: number): Float16Array;
  17089. }
  17090. /**
  17091. * @category Platform
  17092. * @experimental
  17093. */
  17094. declare interface DataView {
  17095. /**
  17096. * Gets the Float16 value at the specified byte offset from the start of the view. There is
  17097. * no alignment constraint; multi-byte values may be fetched from any offset.
  17098. * @param byteOffset The place in the buffer at which the value should be retrieved.
  17099. * @param littleEndian If false or undefined, a big-endian value should be read.
  17100. */
  17101. getFloat16(byteOffset: number, littleEndian?: boolean): number;
  17102. /**
  17103. * Stores an Float16 value at the specified byte offset from the start of the view.
  17104. * @param byteOffset The place in the buffer at which the value should be set.
  17105. * @param value The value to set.
  17106. * @param littleEndian If false or undefined, a big-endian value should be written.
  17107. */
  17108. setFloat16(byteOffset: number, value: number, littleEndian?: boolean): void;
  17109. }