define-config-kIZKjX8Q.d.mts 155 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190
  1. import { a as RolldownLog, i as RolldownError, n as LogLevelOption, o as RolldownLogWithString, r as LogOrStringHandler, t as LogLevel } from "./logging-xuHO4mAy.mjs";
  2. import { H as ParserOptions, I as JsxOptions, L as ManglePropertiesOptions$1, M as BindingWatcherBundler, N as ExternalMemoryStatus, R as MinifyOptions$1, U as PreRenderedChunk, c as BindingHookResolveIdExtraArgs, d as BindingMagicString, g as BindingRenderedChunk, m as BindingPluginContextResolveOptions, q as TransformOptions$1, t as BindingBuiltinPluginName, v as BindingTransformHookExtraArgs } from "./binding-tzp6Hc_3.mjs";
  3. import { TopLevelFilterExpression } from "@rolldown/pluginutils";
  4. import { Program } from "@oxc-project/types";
  5. //#region src/types/misc.d.ts
  6. /** @inline */
  7. type SourcemapPathTransformOption = (relativeSourcePath: string, sourcemapPath: string) => string;
  8. /** @inline */
  9. type SourcemapIgnoreListOption = (relativeSourcePath: string, sourcemapPath: string) => boolean;
  10. //#endregion
  11. //#region src/types/module-info.d.ts
  12. /** @category Plugin APIs */
  13. interface ModuleInfo extends ModuleOptions {
  14. /**
  15. * @hidden Not supported by Rolldown
  16. */
  17. ast: any;
  18. /**
  19. * The source code of the module.
  20. *
  21. * `null` if external or not yet available.
  22. */
  23. code: string | null;
  24. /**
  25. * The id of the module for convenience
  26. */
  27. id: string;
  28. /**
  29. * The ids of all modules that statically import this module.
  30. */
  31. importers: string[];
  32. /**
  33. * The ids of all modules that dynamically import this module.
  34. */
  35. dynamicImporters: string[];
  36. /**
  37. * The module ids statically imported by this module.
  38. */
  39. importedIds: string[];
  40. /**
  41. * The module ids dynamically imported by this module.
  42. */
  43. dynamicallyImportedIds: string[];
  44. /**
  45. * All exported variables
  46. */
  47. exports: string[];
  48. /**
  49. * Whether this module is a user- or plugin-defined entry point.
  50. */
  51. isEntry: boolean;
  52. /**
  53. * The detected format of the module, based on both its syntax and module definition
  54. * metadata (such as `package.json` `type` and file extensions like `.mjs`/`.cjs`/`.mts`/`.cts`).
  55. * - "esm" for ES modules (has `import`/`export` statements or is defined as ESM by module metadata)
  56. * - "cjs" for CommonJS modules (uses `module.exports`, `exports`, top-level `return`, or is defined as CommonJS by module metadata)
  57. * - "unknown" when the format could not be determined from either syntax or module definition metadata
  58. *
  59. * @experimental
  60. */
  61. inputFormat: "es" | "cjs" | "unknown";
  62. }
  63. //#endregion
  64. //#region src/utils/asset-source.d.ts
  65. /** @inline */
  66. type AssetSource = string | Uint8Array;
  67. //#endregion
  68. //#region src/types/external-memory-handle.d.ts
  69. declare const symbolForExternalMemoryHandle: "__rolldown_external_memory_handle__";
  70. /**
  71. * Interface for objects that hold external memory that can be explicitly freed.
  72. */
  73. interface ExternalMemoryHandle {
  74. /**
  75. * Frees the external memory held by this object.
  76. * @param keepDataAlive - If true, evaluates all lazy fields before freeing memory.
  77. * This will take time but prevents errors when accessing properties after freeing.
  78. * @returns Status object with `freed` boolean and optional `reason` string.
  79. * @internal
  80. */
  81. [symbolForExternalMemoryHandle]: (keepDataAlive?: boolean) => ExternalMemoryStatus;
  82. }
  83. /**
  84. * Frees the external memory held by the given handle.
  85. *
  86. * This is useful when you want to manually release memory held by Rust objects
  87. * (like `OutputChunk` or `OutputAsset`) before they are garbage collected.
  88. *
  89. * @param handle - The object with external memory to free
  90. * @param keepDataAlive - If true, evaluates all lazy fields before freeing memory (default: false).
  91. * This will take time to copy data from Rust to JavaScript, but prevents errors
  92. * when accessing properties after the memory is freed.
  93. * @returns Status object with `freed` boolean and optional `reason` string.
  94. * - `{ freed: true }` if memory was successfully freed
  95. * - `{ freed: false, reason: "..." }` if memory couldn't be freed (e.g., already freed or other references exist)
  96. *
  97. * @example
  98. * ```typescript
  99. * import { freeExternalMemory } from 'rolldown/experimental';
  100. *
  101. * const output = await bundle.generate();
  102. * const chunk = output.output[0];
  103. *
  104. * // Use the chunk...
  105. *
  106. * // Manually free the memory (fast, but accessing properties after will throw)
  107. * const status = freeExternalMemory(chunk); // { freed: true }
  108. * const statusAgain = freeExternalMemory(chunk); // { freed: false, reason: "Memory has already been freed" }
  109. *
  110. * // Keep data alive before freeing (slower, but data remains accessible)
  111. * freeExternalMemory(chunk, true); // Evaluates all lazy fields first
  112. * console.log(chunk.code); // OK - data was copied to JavaScript before freeing
  113. *
  114. * // Without keepDataAlive, accessing chunk properties after freeing will throw an error
  115. * ```
  116. */
  117. declare function freeExternalMemory(handle: ExternalMemoryHandle, keepDataAlive?: boolean): ExternalMemoryStatus;
  118. //#endregion
  119. //#region src/types/rolldown-output.d.ts
  120. /**
  121. * The information about an asset in the generated bundle.
  122. *
  123. * @category Plugin APIs
  124. */
  125. interface OutputAsset extends ExternalMemoryHandle {
  126. type: "asset";
  127. /** The file name of this asset. */
  128. fileName: string;
  129. /** @deprecated Use {@linkcode originalFileNames} instead. */
  130. originalFileName: string | null;
  131. /** The list of the absolute paths to the original file of this asset. */
  132. originalFileNames: string[];
  133. /** The content of this asset. */
  134. source: AssetSource;
  135. /** @deprecated Use {@linkcode names} instead. */
  136. name: string | undefined;
  137. names: string[];
  138. }
  139. /** @category Plugin APIs */
  140. interface SourceMap {
  141. file: string;
  142. mappings: string;
  143. names: string[];
  144. sources: string[];
  145. sourcesContent: string[];
  146. version: number;
  147. debugId?: string;
  148. ignoreList?: number[];
  149. /** @deprecated Use `ignoreList` instead. */
  150. x_google_ignoreList?: number[];
  151. toString(): string;
  152. toUrl(): string;
  153. }
  154. /** @category Plugin APIs */
  155. interface RenderedModule {
  156. /**
  157. * The rendered code of this module.
  158. *
  159. * The unused variables and functions are removed.
  160. */
  161. readonly code: string | null;
  162. /**
  163. * The length of the rendered code of this module.
  164. */
  165. renderedLength: number;
  166. /**
  167. * The list of exported names from this module.
  168. *
  169. * The names that are not used are not included.
  170. */
  171. renderedExports: string[];
  172. }
  173. /**
  174. * The information about the chunk being rendered.
  175. *
  176. * Unlike {@link OutputChunk}, `code` and `map` are not set as the chunk has not been rendered yet.
  177. * All referenced chunk file names in each property that would contain hashes will contain hash placeholders instead.
  178. *
  179. * @category Plugin APIs
  180. */
  181. interface RenderedChunk extends Omit<BindingRenderedChunk, "modules"> {
  182. type: "chunk";
  183. /** Information about the modules included in this chunk. */
  184. modules: {
  185. [id: string]: RenderedModule;
  186. };
  187. /** The name of this chunk, which is used in naming patterns. */
  188. name: string;
  189. /** Whether this chunk is a static entry point. */
  190. isEntry: boolean;
  191. /** Whether this chunk is a dynamic entry point. */
  192. isDynamicEntry: boolean;
  193. /** The id of a module that this chunk corresponds to. */
  194. facadeModuleId: string | null;
  195. /** The list of ids of modules included in this chunk. */
  196. moduleIds: Array<string>;
  197. /** Exported variable names from this chunk. */
  198. exports: Array<string>;
  199. /** The preliminary file name of this chunk with hash placeholders. */
  200. fileName: string;
  201. /** External modules imported statically by this chunk. */
  202. imports: Array<string>;
  203. /** External modules imported dynamically by this chunk. */
  204. dynamicImports: Array<string>;
  205. }
  206. /**
  207. * The information about a chunk in the generated bundle.
  208. *
  209. * @category Plugin APIs
  210. */
  211. interface OutputChunk extends ExternalMemoryHandle {
  212. type: "chunk";
  213. /** The generated code of this chunk. */
  214. code: string;
  215. /** The name of this chunk, which is used in naming patterns. */
  216. name: string;
  217. /** Whether this chunk is a static entry point. */
  218. isEntry: boolean;
  219. /** Exported variable names from this chunk. */
  220. exports: string[];
  221. /** The file name of this chunk. */
  222. fileName: string;
  223. /** Information about the modules included in this chunk. */
  224. modules: {
  225. [id: string]: RenderedModule;
  226. };
  227. /** External modules imported statically by this chunk. */
  228. imports: string[];
  229. /** External modules imported dynamically by this chunk. */
  230. dynamicImports: string[];
  231. /** The id of a module that this chunk corresponds to. */
  232. facadeModuleId: string | null;
  233. /** Whether this chunk is a dynamic entry point. */
  234. isDynamicEntry: boolean;
  235. moduleIds: string[];
  236. /** The source map of this chunk if present. */
  237. map: SourceMap | null;
  238. sourcemapFileName: string | null;
  239. /** The preliminary file name of this chunk with hash placeholders. */
  240. preliminaryFileName: string;
  241. }
  242. /**
  243. * The generated bundle output.
  244. *
  245. * @category Programmatic APIs
  246. */
  247. interface RolldownOutput extends ExternalMemoryHandle {
  248. /**
  249. * The list of chunks and assets in the generated bundle.
  250. *
  251. * This includes at least one {@linkcode OutputChunk}. It may also include more
  252. * {@linkcode OutputChunk} and/or {@linkcode OutputAsset}s.
  253. */
  254. output: [OutputChunk, ...(OutputChunk | OutputAsset)[]];
  255. /**
  256. * The updated property-name cache. Present when `minify.mangleProps` runs.
  257. *
  258. * This contains the input cache and any generated mappings. Pass it to a later
  259. * `minify.mangleProps.cache` to reuse the same mappings.
  260. */
  261. mangleCache?: Record<string, string | false>;
  262. }
  263. //#endregion
  264. //#region src/types/utils.d.ts
  265. type MaybePromise<T> = T | Promise<T>;
  266. /** @inline */
  267. type NullValue<T = void> = T | undefined | null | void;
  268. type PartialNull<T> = { [P in keyof T]: T[P] | null; };
  269. type MakeAsync<Function_> = Function_ extends ((this: infer This, ...parameters: infer Arguments) => infer Return) ? (this: This, ...parameters: Arguments) => Return | Promise<Return> : never;
  270. type MaybeArray<T> = T | T[];
  271. /** @inline */
  272. type StringOrRegExp = string | RegExp;
  273. //#endregion
  274. //#region src/options/output-options.d.ts
  275. type GeneratedCodePreset = "es5" | "es2015";
  276. interface GeneratedCodeOptions {
  277. /**
  278. * Whether to use Symbol.toStringTag for namespace objects.
  279. * @default false
  280. */
  281. symbols?: boolean;
  282. /**
  283. * Allows choosing one of the presets listed above while overriding some options.
  284. *
  285. * ```js
  286. * export default {
  287. * output: {
  288. * generatedCode: {
  289. * preset: 'es2015',
  290. * symbols: false
  291. * }
  292. * }
  293. * };
  294. * ```
  295. *
  296. * @default 'es2015'
  297. */
  298. preset?: GeneratedCodePreset;
  299. /**
  300. * Whether to add readable names to internal variables for profiling purposes.
  301. *
  302. * When enabled, generated code will use descriptive variable names that correspond
  303. * to the original module names, making it easier to profile and debug the bundled code.
  304. *
  305. * @default false
  306. *
  307. *
  308. */
  309. profilerNames?: boolean;
  310. }
  311. /** @inline */
  312. type ModuleFormat = "es" | "cjs" | "esm" | "module" | "commonjs" | "iife" | "umd";
  313. /** @inline */
  314. type AddonFunction = (chunk: RenderedChunk) => string | Promise<string>;
  315. /** @inline */
  316. type ChunkFileNamesFunction = (chunkInfo: PreRenderedChunk) => string;
  317. /** @inline */
  318. type SanitizeFileNameFunction = (name: string) => string;
  319. /** @category Plugin APIs */
  320. interface PreRenderedAsset {
  321. type: "asset";
  322. /** @deprecated Use {@linkcode names} instead. */
  323. name?: string;
  324. names: string[];
  325. /** @deprecated Use {@linkcode originalFileNames} instead. */
  326. originalFileName?: string;
  327. /** The list of the absolute paths to the original file of this asset. */
  328. originalFileNames: string[];
  329. /** The content of this asset. */
  330. source: AssetSource;
  331. }
  332. /** @inline */
  333. type AssetFileNamesFunction = (chunkInfo: PreRenderedAsset) => string;
  334. /** @inline */
  335. type PathsFunction$1 = (id: string) => string;
  336. /** @inline */
  337. type ManualChunksFunction = (moduleId: string, meta: {
  338. getModuleInfo: (moduleId: string) => ModuleInfo | null;
  339. }) => string | NullValue;
  340. /** @inline */
  341. type GlobalsFunction = (name: string) => string;
  342. /** @category Code Splitting */
  343. type CodeSplittingNameFunction = (moduleId: string, ctx: ChunkingContext) => string | NullValue;
  344. /** @inline @category Code Splitting */
  345. type CodeSplittingTestFunction = (id: string) => boolean | undefined | void;
  346. interface ManglePropertiesOptions extends Omit<ManglePropertiesOptions$1, "cache"> {
  347. /**
  348. * Stable mappings from original names to output names. `false` reserves an original name.
  349. * String targets must be valid identifiers and cannot be `__proto__`, `constructor`, or
  350. * `prototype`. Generated mappings are returned as `RolldownOutput.mangleCache`.
  351. */
  352. cache?: Record<string, string | false>;
  353. }
  354. type MinifyOptions = Omit<MinifyOptions$1, "module" | "sourcemap" | "mangleProps"> & {
  355. /**
  356. * Mangle matching property names. This currently requires a single JavaScript output chunk.
  357. * Rolldown throws an error when this option is used with multiple JavaScript chunks.
  358. *
  359. * Reserve names accessed indirectly, through module namespace objects, or by code outside
  360. * Rolldown's minification.
  361. * Numeric spellings, `__proto__`, `constructor`, and `prototype` are never mangled.
  362. */
  363. mangleProps?: ManglePropertiesOptions;
  364. };
  365. interface CommentsOptions {
  366. /**
  367. * Comments that contain `@license`, `@preserve` or start with `//!` or `/*!`
  368. */
  369. legal?: boolean;
  370. /**
  371. * Comments that contain `@__PURE__`, `@__NO_SIDE_EFFECTS__` or `@vite-ignore`
  372. */
  373. annotation?: boolean;
  374. /**
  375. * JSDoc comments
  376. */
  377. jsdoc?: boolean;
  378. }
  379. /** @inline @category Code Splitting */
  380. interface ChunkingContext {
  381. /**
  382. * The returned object and its dependency arrays are reused within the current chunking pass.
  383. * Treat graph fields as read-only. `meta` properties and the `moduleSideEffects` field remain mutable.
  384. */
  385. getModuleInfo(moduleId: string): ModuleInfo | null;
  386. }
  387. interface OutputOptions {
  388. /**
  389. * The directory in which all generated chunks are placed.
  390. *
  391. * The {@linkcode file | output.file} option can be used instead if only a single chunk is generated.
  392. *
  393. *
  394. *
  395. * @default 'dist'
  396. */
  397. dir?: string;
  398. /**
  399. * The file path for the single generated chunk.
  400. *
  401. * The {@linkcode dir | output.dir} option should be used instead if multiple chunks are generated.
  402. */
  403. file?: string;
  404. /**
  405. * Which exports mode to use.
  406. *
  407. *
  408. *
  409. * @default 'auto'
  410. */
  411. exports?: "auto" | "named" | "default" | "none";
  412. /**
  413. * Specify the character set that Rolldown is allowed to use in file hashes.
  414. *
  415. * - `'base64'`: Uses url-safe base64 characters (0-9, a-z, A-Z, -, _). This will produce the shortest hashes.
  416. * - `'base36'`: Uses alphanumeric characters (0-9, a-z)
  417. * - `'hex'`: Uses hexadecimal characters (0-9, a-f)
  418. *
  419. * @default 'base64'
  420. */
  421. hashCharacters?: "base64" | "base36" | "hex";
  422. /**
  423. * Expected format of generated code.
  424. *
  425. * - `'es'`, `'esm'` and `'module'` are the same format, all stand for ES module.
  426. * - `'cjs'` and `'commonjs'` are the same format, all stand for CommonJS module.
  427. * - `'iife'` stands for [Immediately Invoked Function Expression](https://developer.mozilla.org/en-US/docs/Glossary/IIFE).
  428. * - `'umd'` stands for [Universal Module Definition](https://github.com/umdjs/umd).
  429. *
  430. * @default 'es'
  431. *
  432. *
  433. */
  434. format?: ModuleFormat;
  435. /**
  436. * Whether to generate sourcemaps.
  437. *
  438. * - `false`: No sourcemap will be generated.
  439. * - `true`: A separate sourcemap file will be generated.
  440. * - `'inline'`: The sourcemap will be appended to the output file as a data URL.
  441. * - `'hidden'`: A separate sourcemap file will be generated, but the link to the sourcemap (`//# sourceMappingURL` comment) will not be included in the output file.
  442. *
  443. * @default false
  444. */
  445. sourcemap?: boolean | "inline" | "hidden";
  446. /**
  447. * The base URL for the links to the sourcemap file in the output file.
  448. *
  449. * By default, relative URLs are generated. If this option is set, an absolute URL with that base URL will be generated. This is useful when deploying source maps to a different location than your code, such as a CDN or separate debugging server.
  450. */
  451. sourcemapBaseUrl?: string;
  452. /**
  453. * The pattern to use for sourcemaps created from entry points, or a function that is called per entry chunk with {@linkcode PreRenderedChunk} to return such a pattern.
  454. *
  455. * Patterns support the following placeholders:
  456. * - `[format]`: The rendering format defined in the output options. The value is any of {@linkcode InternalModuleFormat}.
  457. * - `[hash]`: A hash based only on the content of the final generated sourcemap. You can also set a specific hash length via e.g. `[hash:10]`. By default, it will create a base-64 hash. If you need a reduced character set, see {@linkcode hashCharacters | output.hashCharacters}.
  458. * - `[chunkhash]`: The same hash as the one used for the corresponding generated chunk (if any).
  459. * - `[name]`: The name of the corresponding chunk.
  460. *
  461. * Forward slashes (`/`) can be used to place files in sub-directories. This pattern will also be used for every file when setting the {@linkcode preserveModules | output.preserveModules} option.
  462. *
  463. * See also {@linkcode assetFileNames | output.assetFileNames}, {@linkcode chunkFileNames | output.chunkFileNames}.
  464. *
  465. * @default the corresponding chunk filename with `.map` appended
  466. */
  467. sourcemapFileNames?: string | ChunkFileNamesFunction;
  468. /**
  469. * Whether to include [debug IDs](https://github.com/tc39/ecma426/blob/main/proposals/debug-id.md) in the sourcemap.
  470. *
  471. * When `true`, a unique debug ID will be emitted in source and sourcemaps which streamlines identifying sourcemaps across different builds.
  472. *
  473. * @default false
  474. */
  475. sourcemapDebugIds?: boolean;
  476. /**
  477. * Control which source files are included in the sourcemap ignore list.
  478. *
  479. * Files in the ignore list are excluded from debugger stepping and error stack traces.
  480. *
  481. * - `false`: Include no source files in the ignore list
  482. * - `true`: Include all source files in the ignore list
  483. * - `string`: Files containing this string in their path will be included in the ignore list
  484. * - `RegExp`: Files matching this regular expression will be included in the ignore list
  485. * - `function`: Custom function to determine if a source should be ignored
  486. *
  487. * :::tip Performance
  488. * Using static values (`boolean`, `string`, or `RegExp`) is significantly more performant than functions.
  489. * Calling JavaScript functions from Rust has extremely high overhead, so prefer static patterns when possible.
  490. * :::
  491. *
  492. * @example
  493. * ```js
  494. * // ✅ Preferred: Use RegExp for better performance
  495. * sourcemapIgnoreList: /node_modules/
  496. *
  497. * // ✅ Preferred: Use string pattern for better performance
  498. * sourcemapIgnoreList: "vendor"
  499. *
  500. * // ! Use sparingly: Function calls have high overhead
  501. * sourcemapIgnoreList: (source, sourcemapPath) => {
  502. * return source.includes('node_modules') || source.includes('.min.');
  503. * }
  504. * ```
  505. *
  506. * @default /node_modules/
  507. */
  508. sourcemapIgnoreList?: boolean | SourcemapIgnoreListOption | StringOrRegExp;
  509. /**
  510. * A transformation to apply to each path in a sourcemap.
  511. *
  512. * @example
  513. * ```js
  514. * export default defineConfig({
  515. * output: {
  516. * sourcemap: true,
  517. * sourcemapPathTransform: (source, sourcemapPath) => {
  518. * // Remove 'src/' prefix from all source paths
  519. * return source.replace(/^src\//, '');
  520. * },
  521. * },
  522. * });
  523. * ```
  524. */
  525. sourcemapPathTransform?: SourcemapPathTransformOption;
  526. /**
  527. * Whether to exclude the original source code from sourcemaps.
  528. *
  529. * When `true`, the `sourcesContent` field is omitted from the generated sourcemap,
  530. * reducing the sourcemap file size. The sourcemap will still contain source file paths
  531. * and mappings, so debugging works if the original files are available.
  532. *
  533. * @default false
  534. */
  535. sourcemapExcludeSources?: boolean;
  536. /**
  537. * A string to prepend to the bundle before {@linkcode Plugin.renderChunk | renderChunk} hook.
  538. *
  539. * See {@linkcode intro | output.intro}, {@linkcode postBanner | output.postBanner} as well.
  540. *
  541. *
  542. */
  543. banner?: string | AddonFunction;
  544. /**
  545. * A string to append to the bundle before {@linkcode Plugin.renderChunk | renderChunk} hook.
  546. *
  547. * See {@linkcode outro | output.outro}, {@linkcode postFooter | output.postFooter} as well.
  548. *
  549. *
  550. */
  551. footer?: string | AddonFunction;
  552. /**
  553. * A string to prepend to the bundle after {@linkcode Plugin.renderChunk | renderChunk} hook and minification.
  554. *
  555. * See {@linkcode banner | output.banner}, {@linkcode intro | output.intro} as well.
  556. *
  557. *
  558. */
  559. postBanner?: string | AddonFunction;
  560. /**
  561. * A string to append to the bundle after {@linkcode Plugin.renderChunk | renderChunk} hook and minification.
  562. *
  563. * See {@linkcode footer | output.footer}, {@linkcode outro | output.outro} as well.
  564. *
  565. *
  566. */
  567. postFooter?: string | AddonFunction;
  568. /**
  569. * A string to prepend inside any {@link OutputOptions.format | format}-specific wrapper.
  570. *
  571. * See {@linkcode banner | output.banner}, {@linkcode postBanner | output.postBanner} as well.
  572. *
  573. *
  574. */
  575. intro?: string | AddonFunction;
  576. /**
  577. * A string to append inside any {@link OutputOptions.format | format}-specific wrapper.
  578. *
  579. * See {@linkcode footer | output.footer}, {@linkcode postFooter | output.postFooter} as well.
  580. *
  581. *
  582. */
  583. outro?: string | AddonFunction;
  584. /**
  585. * Whether to extend the global variable defined by the {@linkcode OutputOptions.name | name} option in `umd` or `iife` {@link OutputOptions.format | formats}.
  586. *
  587. * When `true`, the global variable will be defined as `global.name = global.name || {}`.
  588. * When `false`, the global defined by name will be overwritten like `global.name = {}`.
  589. *
  590. * @default false
  591. */
  592. extend?: boolean;
  593. /**
  594. * Whether to add a `__esModule: true` property when generating exports for non-ES {@link OutputOptions.format | formats}.
  595. *
  596. * This property signifies that the exported value is the namespace of an ES module and that the default export of this module corresponds to the `.default` property of the exported object.
  597. *
  598. * - `true`: Always add the property when using {@link OutputOptions.exports | named exports mode}, which is similar to what other tools do.
  599. * - `"if-default-prop"`: Only add the property when using {@link OutputOptions.exports | named exports mode} and there also is a default export. The subtle difference is that if there is no default export, consumers of the CommonJS version of your library will get all named exports as default export instead of an error or `undefined`.
  600. * - `false`: Never add the property even if the default export would become a property `.default`.
  601. *
  602. * @default 'if-default-prop'
  603. *
  604. *
  605. */
  606. esModule?: boolean | "if-default-prop";
  607. /**
  608. * The pattern to use for naming custom emitted assets to include in the build output, or a function that is called per asset with {@linkcode PreRenderedAsset} to return such a pattern.
  609. *
  610. * Patterns support the following placeholders:
  611. * - `[extname]`: The file extension of the asset including a leading dot, e.g. `.css`.
  612. * - `[ext]`: The file extension without a leading dot, e.g. css.
  613. * - `[hash]`: A hash based on the content of the asset. You can also set a specific hash length via e.g. `[hash:10]`. By default, it will create a base-64 hash. If you need a reduced character set, see {@linkcode hashCharacters | output.hashCharacters}.
  614. * - `[name]`: The file name of the asset excluding any extension.
  615. *
  616. * Forward slashes (`/`) can be used to place files in sub-directories.
  617. *
  618. * See also {@linkcode chunkFileNames | output.chunkFileNames}, {@linkcode entryFileNames | output.entryFileNames}.
  619. *
  620. * @default 'assets/[name]-[hash][extname]'
  621. */
  622. assetFileNames?: string | AssetFileNamesFunction;
  623. /**
  624. * The pattern to use for chunks created from entry points, or a function that is called per entry chunk with {@linkcode PreRenderedChunk} to return such a pattern.
  625. *
  626. * Patterns support the following placeholders:
  627. * - `[format]`: The rendering format defined in the output options. The value is any of {@linkcode InternalModuleFormat}.
  628. * - `[hash]`: A hash based only on the content of the final generated chunk, including transformations in `renderChunk` and any referenced file hashes. You can also set a specific hash length via e.g. `[hash:10]`. By default, it will create a base-64 hash. If you need a reduced character set, see {@linkcode hashCharacters | output.hashCharacters}.
  629. * - `[name]`: The file name (without extension) of the entry point, unless the object form of input was used to define a different name.
  630. *
  631. * Forward slashes (`/`) can be used to place files in sub-directories. This pattern will also be used for every file when setting the {@linkcode preserveModules | output.preserveModules} option.
  632. *
  633. * See also {@linkcode assetFileNames | output.assetFileNames}, {@linkcode chunkFileNames | output.chunkFileNames}.
  634. *
  635. * @default '[name].js'
  636. */
  637. entryFileNames?: string | ChunkFileNamesFunction;
  638. /**
  639. * The pattern to use for naming shared chunks created when code-splitting, or a function that is called per chunk with {@linkcode PreRenderedChunk} to return such a pattern.
  640. *
  641. * Patterns support the following placeholders:
  642. * - `[format]`: The rendering format defined in the output options. The value is any of {@linkcode InternalModuleFormat}.
  643. * - `[hash]`: A hash based only on the content of the final generated chunk, including transformations in `renderChunk` and any referenced file hashes. You can also set a specific hash length via e.g. `[hash:10]`. By default, it will create a base-64 hash. If you need a reduced character set, see {@linkcode hashCharacters | output.hashCharacters}.
  644. * - `[name]`: The name of the chunk. This can be explicitly set via the {@linkcode codeSplitting | output.codeSplitting} option or when the chunk is created by a plugin via `this.emitFile`. Otherwise, it will be derived from the chunk contents.
  645. *
  646. * Forward slashes (`/`) can be used to place files in sub-directories.
  647. *
  648. * See also {@linkcode assetFileNames | output.assetFileNames}, {@linkcode entryFileNames | output.entryFileNames}.
  649. *
  650. * @default '[name]-[hash].js'
  651. */
  652. chunkFileNames?: string | ChunkFileNamesFunction;
  653. /**
  654. * Whether to enable chunk name sanitization (removal of non-URL-safe characters like `\0`, `?` and `*`).
  655. *
  656. * Set `false` to disable the sanitization. You can also provide a custom sanitization function.
  657. *
  658. * @default true
  659. */
  660. sanitizeFileName?: boolean | SanitizeFileNameFunction;
  661. /**
  662. * Control code minification
  663. *
  664. * Rolldown uses Oxc Minifier under the hood. See Oxc's [minification documentation](https://oxc.rs/docs/guide/usage/minifier#features) for more details.
  665. *
  666. * - `true`: Enable full minification including code compression and dead code elimination
  667. * - `false`: Disable minification
  668. * - `'dce-only'`: Only perform dead code elimination without code compression (default)
  669. * - `MinifyOptions`: Fine-grained control over minification settings
  670. *
  671. * @default 'dce-only'
  672. */
  673. minify?: boolean | "dce-only" | MinifyOptions;
  674. /**
  675. * Specifies the global variable name that contains the exports of `umd` / `iife` {@link OutputOptions.format | formats}.
  676. *
  677. * @example
  678. * ```js
  679. * export default defineConfig({
  680. * output: {
  681. * format: 'iife',
  682. * name: 'MyBundle',
  683. * }
  684. * });
  685. * ```
  686. * ```js
  687. * // output
  688. * var MyBundle = (function () {
  689. * // ...
  690. * })();
  691. * ```
  692. *
  693. *
  694. */
  695. name?: string;
  696. /**
  697. * Specifies `id: variableName` pairs necessary for {@link InputOptions.external | external} imports in `umd` / `iife` {@link OutputOptions.format | formats}.
  698. *
  699. * @example
  700. * ```js
  701. * export default defineConfig({
  702. * external: ['jquery'],
  703. * output: {
  704. * format: 'iife',
  705. * name: 'MyBundle',
  706. * globals: {
  707. * jquery: '$',
  708. * }
  709. * }
  710. * });
  711. * ```
  712. * ```js
  713. * // input
  714. * import $ from 'jquery';
  715. * ```
  716. * ```js
  717. * // output
  718. * var MyBundle = (function ($) {
  719. * // ...
  720. * })($);
  721. * ```
  722. */
  723. globals?: Record<string, string> | GlobalsFunction;
  724. /**
  725. * Maps {@link InputOptions.external | external} module IDs to paths.
  726. *
  727. * Allows customizing the path used when importing external dependencies.
  728. * This is particularly useful for loading dependencies from CDNs or custom locations.
  729. *
  730. * - Object form: Maps module IDs to their replacement paths
  731. * - Function form: Takes a module ID and returns its replacement path
  732. *
  733. * @example
  734. * ```js
  735. * {
  736. * paths: {
  737. * 'd3': 'https://cdn.jsdelivr.net/npm/d3@7'
  738. * }
  739. * }
  740. * ```
  741. *
  742. * @example
  743. * ```js
  744. * {
  745. * paths: (id) => {
  746. * if (id.startsWith('lodash')) {
  747. * return `https://cdn.jsdelivr.net/npm/${id}`
  748. * }
  749. * return id
  750. * }
  751. * }
  752. * ```
  753. */
  754. paths?: Record<string, string> | PathsFunction$1;
  755. /**
  756. * Which language features Rolldown can safely use in generated code.
  757. *
  758. * This will not transpile any user code but only change the code Rolldown uses in wrappers and helpers.
  759. */
  760. generatedCode?: Partial<GeneratedCodeOptions>;
  761. /**
  762. * Whether to generate code to support live bindings for {@link InputOptions.external | external} imports.
  763. *
  764. * With the default value of `true`, Rolldown will generate code to support live bindings for external imports.
  765. *
  766. * When set to `false`, Rolldown will assume that exports from external modules do not change. This will allow Rolldown to generate smaller code. Note that this can cause issues when there are circular dependencies involving an external dependency.
  767. *
  768. * @default true
  769. *
  770. *
  771. */
  772. externalLiveBindings?: boolean;
  773. /**
  774. * @deprecated Please use `codeSplitting: false` instead.
  775. *
  776. * Whether to inline dynamic imports instead of creating new chunks to create a single bundle.
  777. *
  778. * This option can be used only when a single input is provided.
  779. *
  780. * @default false
  781. */
  782. inlineDynamicImports?: boolean;
  783. /**
  784. * Whether to keep external dynamic imports as `import(...)` expressions in CommonJS output.
  785. *
  786. * If set to `false`, external dynamic imports will be rewritten to use `require(...)` calls.
  787. * This may be necessary to support environments that do not support dynamic `import()` in CommonJS modules like old Node.js versions.
  788. *
  789. * @default true
  790. */
  791. dynamicImportInCjs?: boolean;
  792. /**
  793. * Allows you to do manual chunking. Provided for Rollup compatibility.
  794. *
  795. * You could use this option for migration purpose. Under the hood,
  796. *
  797. * ```js
  798. * {
  799. * manualChunks: (moduleId, meta) => {
  800. * if (moduleId.includes('node_modules')) {
  801. * return 'vendor';
  802. * }
  803. * return null;
  804. * }
  805. * }
  806. * ```
  807. *
  808. * will be transformed to
  809. *
  810. * ```js
  811. * {
  812. * codeSplitting: {
  813. * groups: [
  814. * {
  815. * name(moduleId) {
  816. * if (moduleId.includes('node_modules')) {
  817. * return 'vendor';
  818. * }
  819. * return null;
  820. * },
  821. * },
  822. * ],
  823. * }
  824. * }
  825. *
  826. * ```
  827. *
  828. * Note that unlike Rollup, object form is not supported.
  829. *
  830. * @deprecated
  831. * Please use {@linkcode codeSplitting | output.codeSplitting} instead.
  832. *
  833. * :::warning
  834. * If `manualChunks` and `codeSplitting` are both specified, `manualChunks` option will be ignored.
  835. * :::
  836. */
  837. manualChunks?: ManualChunksFunction;
  838. /**
  839. * Controls how code splitting is performed.
  840. *
  841. * - `true`: Default behavior, automatic code splitting. **(default)**
  842. * - `false`: Inline all dynamic imports into a single bundle (equivalent to deprecated `inlineDynamicImports: true`).
  843. * - `object`: Advanced manual code splitting configuration.
  844. *
  845. * For deeper understanding, please refer to the in-depth [documentation](https://rolldown.rs/in-depth/manual-code-splitting).
  846. *
  847. *
  848. *
  849. * @example
  850. * **Basic vendor chunk**
  851. * ```js
  852. * export default defineConfig({
  853. * output: {
  854. * codeSplitting: {
  855. * minSize: 20000,
  856. * groups: [
  857. * {
  858. * name: 'vendor',
  859. * test: /node_modules/,
  860. * },
  861. * ],
  862. * },
  863. * },
  864. * });
  865. * ```
  866. *
  867. *
  868. * @default true
  869. */
  870. codeSplitting?: boolean | CodeSplittingOptions;
  871. /**
  872. * @deprecated Please use {@linkcode codeSplitting | output.codeSplitting} instead.
  873. *
  874. * Allows you to do manual chunking.
  875. *
  876. * :::warning
  877. * If `advancedChunks` and `codeSplitting` are both specified, `advancedChunks` option will be ignored.
  878. * :::
  879. */
  880. advancedChunks?: {
  881. includeDependenciesRecursively?: boolean;
  882. minSize?: number;
  883. maxSize?: number;
  884. maxModuleSize?: number;
  885. minModuleSize?: number;
  886. minShareCount?: number;
  887. groups?: CodeSplittingGroup[];
  888. };
  889. /**
  890. * Controls how legal comments are preserved in the output.
  891. *
  892. * - `none`: no legal comments
  893. * - `inline`: preserve legal comments that contain `@license`, `@preserve` or starts with `//!` `/*!`
  894. *
  895. * @deprecated Use `comments.legal` instead. When both `legalComments` and `comments.legal` are set, `comments.legal` takes priority.
  896. */
  897. legalComments?: "none" | "inline";
  898. /**
  899. * Control which comments are preserved in the output.
  900. *
  901. * - `true`: Preserve legal, annotation, and JSDoc comments (default)
  902. * - `false`: Strip all comments
  903. * - Object: Granular control over comment categories
  904. *
  905. * Note: Regular line and block comments without these markers
  906. * are always removed regardless of this option.
  907. *
  908. * When both `legalComments` and `comments.legal` are set, `comments.legal` takes priority.
  909. *
  910. * @default true
  911. */
  912. comments?: boolean | CommentsOptions;
  913. /**
  914. * The list of plugins to use only for this output.
  915. *
  916. * @see {@linkcode InputOptions.plugins | plugins}
  917. */
  918. plugins?: RolldownOutputPluginOption;
  919. /**
  920. * Whether to add a polyfill for `require()` function in non-CommonJS formats.
  921. *
  922. * This option is useful when you want to inject your own `require` implementation.
  923. *
  924. * @default true
  925. */
  926. polyfillRequire?: boolean;
  927. /**
  928. * This option is not implemented yet.
  929. * @hidden
  930. */
  931. hoistTransitiveImports?: false;
  932. /**
  933. * Whether to use preserve modules mode.
  934. *
  935. *
  936. *
  937. * @default false
  938. */
  939. preserveModules?: boolean;
  940. /**
  941. * Specifies the directory name for "virtual" files that might be emitted by plugins when using {@link OutputOptions.preserveModules | preserve modules mode}.
  942. *
  943. * @default '_virtual'
  944. */
  945. virtualDirname?: string;
  946. /**
  947. * A directory path to input modules that should be stripped away from {@linkcode dir | output.dir} when using {@link OutputOptions.preserveModules | preserve modules mode}.
  948. *
  949. *
  950. */
  951. preserveModulesRoot?: string;
  952. /**
  953. * Whether to convert top-level `let` and `const` declarations into `var` declarations.
  954. *
  955. * Enabling this option can improve runtime performance of the generated code in
  956. * certain environments by avoiding Temporal Dead Zone (TDZ) checks. Only declarations
  957. * in the module's top-level scope are rewritten — declarations inside nested scopes
  958. * (functions, blocks, etc.) are left as-is.
  959. *
  960. * Note:
  961. * - Top-level `class X {}` declarations are always emitted as `var X = class {}` so
  962. * rolldown can hoist them alongside other top-level bindings; this transform is
  963. * independent of `topLevelVar`.
  964. * - Top-level `function` declarations are never rewritten.
  965. *
  966. * @default false
  967. *
  968. *
  969. */
  970. topLevelVar?: boolean;
  971. /**
  972. * Whether to minify internal exports as single letter variables to allow for better minification.
  973. *
  974. * @default
  975. * `true` for format `es` or if `output.minify` is `true` or object, `false` otherwise
  976. *
  977. *
  978. */
  979. minifyInternalExports?: boolean;
  980. /**
  981. * Clean output directory ({@linkcode dir | output.dir}) before emitting output.
  982. *
  983. * @default false
  984. *
  985. *
  986. */
  987. cleanDir?: boolean;
  988. /**
  989. * Keep `name` property of functions and classes after bundling.
  990. *
  991. * When enabled, the bundler will preserve the original `name` property value of functions and
  992. * classes in the output. This is useful for debugging and some frameworks that rely on it for
  993. * registration and binding purposes.
  994. *
  995. *
  996. *
  997. * @default false
  998. */
  999. keepNames?: boolean;
  1000. /**
  1001. * Preserve source module execution order across generated chunks.
  1002. *
  1003. * When enabled, Rolldown wraps ESM modules so their bodies run in source order regardless of chunk placement. Interop wrappers for CommonJS and require-of-ESM modules are unchanged, and external modules are not affected. `experimental.onDemandWrapping` replaces wrap-all with a conservative plan derived from predicted chunk execution hazards.
  1004. *
  1005. * > [!WARNING]
  1006. * > Enabling this option increases bundle size because wrapped modules need runtime init helpers.
  1007. *
  1008. * {@linkcode CodeSplittingOptions.experimentalInlineCommonChunks | experimentalInlineCommonChunks}
  1009. * with a `maxSize` above `0` turns this option on when it is omitted.
  1010. *
  1011. * @default false
  1012. */
  1013. strictExecutionOrder?: boolean;
  1014. /**
  1015. * Whether to always output `"use strict"` directive in non-ES module outputs.
  1016. *
  1017. * - `true` - Always emit `"use strict"` at the top of the output (not applicable for ESM format since ESM is always strict).
  1018. * - `false` - Never emit `"use strict"` in the output.
  1019. * - `'auto'` - Respect the `"use strict"` directives from the source code.
  1020. *
  1021. * See [In-depth directive guide](https://rolldown.rs/in-depth/directives) for more details.
  1022. *
  1023. * @default 'auto'
  1024. */
  1025. strict?: boolean | "auto";
  1026. }
  1027. /**
  1028. * Built-in module tag names computed by rolldown.
  1029. *
  1030. * - `'$initial'` — the module is statically imported by at least one user-defined entry point, or is part of its static dependency chain.
  1031. *
  1032. * @category Code Splitting
  1033. */
  1034. type BuiltinModuleTag = "$initial";
  1035. /** @category Code Splitting */
  1036. type CodeSplittingGroup = {
  1037. /**
  1038. * `debugName` gives this group a label in the bundler timing report.
  1039. *
  1040. * Set this option when `name` is a function. This option does not change the chunk name.
  1041. */
  1042. debugName?: string;
  1043. /**
  1044. * Name of the group. It will be also used as the name of the chunk and replace the `[name]` placeholder in the {@linkcode OutputOptions.chunkFileNames | output.chunkFileNames} option.
  1045. *
  1046. * For example,
  1047. *
  1048. * ```js
  1049. * import { defineConfig } from 'rolldown';
  1050. *
  1051. * export default defineConfig({
  1052. * output: {
  1053. * codeSplitting: {
  1054. * groups: [
  1055. * {
  1056. * name: 'libs',
  1057. * test: /node_modules/,
  1058. * },
  1059. * ],
  1060. * },
  1061. * },
  1062. * });
  1063. * ```
  1064. * will create a chunk named `libs-[hash].js` in the end.
  1065. *
  1066. * It's ok to have the same name for different groups. Rolldown will deduplicate the chunk names if necessary.
  1067. *
  1068. * #### Dynamic `name()`
  1069. *
  1070. * If `name` is a function, it will be called with the module id as the argument. The function should return a string or `null`. If it returns `null`, the module will be ignored by this group.
  1071. *
  1072. * Notice, each returned new name will be treated as a separate group.
  1073. *
  1074. * For example,
  1075. *
  1076. * ```js
  1077. * import { defineConfig } from 'rolldown';
  1078. *
  1079. * export default defineConfig({
  1080. * output: {
  1081. * codeSplitting: {
  1082. * groups: [
  1083. * {
  1084. * name: (moduleId) => moduleId.includes('node_modules') ? 'libs' : 'app',
  1085. * minSize: 100 * 1024,
  1086. * },
  1087. * ],
  1088. * },
  1089. * },
  1090. * });
  1091. * ```
  1092. *
  1093. * :::warning
  1094. * Constraints like `minSize`, `maxSize`, etc. are applied separately for different names returned by the function.
  1095. * :::
  1096. *
  1097. * :::warning
  1098. * Rolldown calls a function `name` once for each captured module, in a deterministic order. It calls `test` for every candidate module of the group first. Do not read a "current module" variable that `test` wrote, because that variable holds the last module `test` saw. Store such state under the module id instead.
  1099. * :::
  1100. */
  1101. name: string | CodeSplittingNameFunction;
  1102. /**
  1103. * Controls which modules are captured in this group.
  1104. *
  1105. * - If `test` is a string, the module whose id contains the string will be captured.
  1106. * - If `test` is a regular expression, the module whose id matches the regular expression will be captured.
  1107. * - If `test` is a function, modules for which `test(id)` returns `true` will be captured.
  1108. * - If `test` is empty, any module will be considered as matched.
  1109. *
  1110. * :::warning
  1111. * When using regular expression, it's recommended to use `[\\/]` to match the path separator instead of `/` to avoid potential issues on Windows.
  1112. * - ✅ Recommended: `/node_modules[\\/]react/`
  1113. * - ❌ Not recommended: `/node_modules/react/`
  1114. * :::
  1115. *
  1116. * :::warning
  1117. * Rolldown calls a function `test` once for each candidate module, in a deterministic order. It makes every `test` call of a group before it makes the first `name` call of that group. Rolldown processes the groups in the order that you declare them.
  1118. * :::
  1119. */
  1120. test?: StringOrRegExp | CodeSplittingTestFunction;
  1121. /**
  1122. * Priority of the group. Group with higher priority will be chosen first to match modules and create chunks. When converting the group to a chunk, modules of that group will be removed from other groups.
  1123. *
  1124. * If two groups have the same priority, the group whose index is smaller will be chosen.
  1125. *
  1126. * @example
  1127. * ```js
  1128. * import { defineConfig } from 'rolldown';
  1129. *
  1130. * export default defineConfig({
  1131. * output: {
  1132. * codeSplitting: {
  1133. * groups: [
  1134. * {
  1135. * name: 'react',
  1136. * test: /node_modules[\\/]react/,
  1137. * priority: 2,
  1138. * },
  1139. * {
  1140. * name: 'other-libs',
  1141. * test: /node_modules/,
  1142. * priority: 1,
  1143. * },
  1144. * ],
  1145. * },
  1146. * },
  1147. * });
  1148. * ```
  1149. *
  1150. * @default 0
  1151. */
  1152. priority?: number;
  1153. /**
  1154. * Minimum size in bytes of the desired chunk. If the accumulated size of the captured modules by this group is smaller than this value, it will be ignored. Modules in this group will fall back to the `automatic chunking` if they are not captured by any other group.
  1155. *
  1156. * @default 0
  1157. */
  1158. minSize?: number;
  1159. /**
  1160. * Controls if a module should be captured based on how many entry chunks reference it.
  1161. *
  1162. * @default 1
  1163. */
  1164. minShareCount?: number;
  1165. /**
  1166. * If the accumulated size in bytes of the captured modules by this group is larger than this value, this group will be split into multiple groups that each has size close to this value.
  1167. *
  1168. * @default Infinity
  1169. */
  1170. maxSize?: number;
  1171. /**
  1172. * Controls whether a module can only be captured if its size in bytes is smaller than or equal to this value.
  1173. *
  1174. * @default Infinity
  1175. */
  1176. maxModuleSize?: number;
  1177. /**
  1178. * Controls whether a module can only be captured if its size in bytes is larger than or equal to this value.
  1179. *
  1180. * @default 0
  1181. */
  1182. minModuleSize?: number;
  1183. /**
  1184. * When `false` (default), all matching modules are merged into a single chunk.
  1185. * Every entry that uses any of these modules must load the entire chunk — even
  1186. * modules it doesn't need.
  1187. *
  1188. * When `true`, matching modules are grouped by which entries actually import them.
  1189. * Modules shared by the same set of entries go into the same chunk, while modules
  1190. * shared by a different set go into a separate chunk. This way, each entry only
  1191. * loads the code it actually uses.
  1192. *
  1193. * Example: entries A, B, C all match a `"vendor"` group.
  1194. * - `moduleX` is used by A, B, C
  1195. * - `moduleY` is used by A, B only
  1196. *
  1197. * With `entriesAware: false` → one `vendor.js` chunk with both modules; C loads `moduleY` unnecessarily.
  1198. * With `entriesAware: true` → `vendor.js` (moduleX, loaded by all) + `vendor2.js` (moduleY, loaded by A and B only).
  1199. *
  1200. * @default false
  1201. */
  1202. entriesAware?: boolean;
  1203. /**
  1204. * Size threshold in bytes for merging small `entriesAware` subgroups into the
  1205. * closest neighboring subgroup.
  1206. *
  1207. * This option only works when {@linkcode CodeSplittingGroup.entriesAware | entriesAware}
  1208. * is `true`. Set to `0` to disable subgroup merging.
  1209. *
  1210. * @default 0
  1211. */
  1212. entriesAwareMergeThreshold?: number;
  1213. /**
  1214. * Whether to include captured modules' dependencies.
  1215. *
  1216. * Enabling this option reduces the chance of generating circular chunks.
  1217. *
  1218. * If you want to disable this behavior, it's recommended to both set
  1219. * - {@linkcode InputOptions.preserveEntrySignatures | preserveEntrySignatures}: `false | 'allow-extension'`
  1220. * - {@linkcode OutputOptions.strictExecutionOrder | strictExecutionOrder}: `true`
  1221. *
  1222. * to avoid generating invalid chunks.
  1223. *
  1224. * @default true
  1225. */
  1226. includeDependenciesRecursively?: boolean;
  1227. /**
  1228. * Filter modules by tags. Only modules that have **all** specified tags
  1229. * are captured by this group. Combines with `test` and other filters —
  1230. * a module must match all criteria.
  1231. *
  1232. * Built-in tags: `'$initial'` (module is statically imported by a user-defined entry or part of its dependency chain).
  1233. *
  1234. * @see {@link https://rolldown.rs/in-depth/manual-code-splitting | Manual Code Splitting}
  1235. *
  1236. * @example
  1237. * ```js
  1238. * { name: 'initial-deps', tags: ['$initial'], maxSize: 1048576 }
  1239. * ```
  1240. */
  1241. tags?: BuiltinModuleTag[];
  1242. };
  1243. /**
  1244. * Alias for {@linkcode CodeSplittingGroup}. Use this type for the `codeSplitting.groups` option.
  1245. *
  1246. * @deprecated Please use {@linkcode CodeSplittingGroup} instead.
  1247. *
  1248. * @category Code Splitting
  1249. */
  1250. type AdvancedChunksGroup = CodeSplittingGroup;
  1251. /**
  1252. * Options for `codeSplitting.experimentalInlineCommonChunks`.
  1253. *
  1254. * Small common chunks produced by automatic code splitting are replaced by a factory function
  1255. * that is copied into the chunks reading them (a chunk whose static dependency already carries the
  1256. * factory uses that copy). A registry in the runtime chunk makes sure the chunk's modules keep one
  1257. * state, one execution and one set of export identities across all copies, so no entry downloads
  1258. * code it could not reach with the option off.
  1259. *
  1260. * Before enabling it, check the plugins and code shapes that see a chunk's modules as one file:
  1261. *
  1262. * - A module of an inlined chunk appears in the `moduleIds` and `modules` of every chunk that
  1263. * prints a copy, so a plugin that asks which chunk owns a module gets several answers. Vite's
  1264. * CSS plugin, for example, emits a style module's CSS from every chunk whose `moduleIds` list
  1265. * it; a Vite build passes `exclude: /\.(css|scss|sass|less|styl|stylus|pcss|postcss|sss)(\?|$)/`
  1266. * so chunks holding styles stay files.
  1267. * - A `renderChunk` hook whose rewrite yields different values in different directories makes
  1268. * the copies differ, and the first chunk to run decides which text every reader sees; exclude
  1269. * the modules concerned. Vite's asset URLs under a relative `base` resolve through
  1270. * `import.meta.url` to the same URL from every copy and are not affected.
  1271. * - The option turns `strictExecutionOrder` on when it is omitted. Strict execution order has an
  1272. * open issue with top-level await inside static import cycles (rolldown/rolldown#9548), so run
  1273. * the application under `strictExecutionOrder: true` before adding this option.
  1274. * - Addons (`banner`, `intro`, `outro` and `footer`), including plugin hooks, apply to emitted
  1275. * files. An inlined chunk shares the addon bindings of the file that registers its factory
  1276. * first. Exclude modules that depend on separate file-local bindings or addon initialization order.
  1277. * - A chunk that prints an inlined chunk names both sets of modules together, so a function or
  1278. * class in either can get a `$1`-style suffix when the other declares the same name, and the
  1279. * `.name` of an inlined chunk's function or class depends on which chunk loads first (under
  1280. * `minify`, the mangled name does too). `output.keepNames` keeps every name.
  1281. *
  1282. * @experimental This feature is experimental. Its behavior and option shape may change in any release.
  1283. *
  1284. * @category Code Splitting
  1285. */
  1286. type ExperimentalInlineCommonChunksOptions = {
  1287. /**
  1288. * Common chunks whose pre-render size (the sum of the transformed source sizes of their modules,
  1289. * in bytes) is strictly smaller than this value are candidates for inlining.
  1290. * Use `Infinity` to remove the size limit.
  1291. *
  1292. * A value greater than `0` requires `output.format: 'es'`, an explicit
  1293. * `preserveEntrySignatures: false` and code splitting, and it turns on
  1294. * {@linkcode OutputOptions.strictExecutionOrder | strictExecutionOrder} when that option is
  1295. * omitted. `output.strictExecutionOrder: false` is an error, `output.preserveModules`,
  1296. * `experimental.devMode` and `experimental.onDemandWrapping` must be off.
  1297. *
  1298. * @default 0
  1299. */
  1300. maxSize?: number;
  1301. /**
  1302. * A matcher for module ids, or an array of them: a string (matched as a regular expression), a
  1303. * RegExp, or a function, each applied like {@linkcode CodeSplittingGroup.test | test}. A common
  1304. * chunk is kept as a file when any of its modules matches any matcher.
  1305. */
  1306. exclude?: StringOrRegExp | CodeSplittingTestFunction | Array<StringOrRegExp | CodeSplittingTestFunction>;
  1307. };
  1308. /**
  1309. * Configuration options for advanced code splitting.
  1310. *
  1311. * @category Code Splitting
  1312. */
  1313. type CodeSplittingOptions = {
  1314. /**
  1315. * Global fallback of {@linkcode CodeSplittingGroup.includeDependenciesRecursively | group.includeDependenciesRecursively}, if it's not specified in the group.
  1316. */
  1317. includeDependenciesRecursively?: boolean;
  1318. /**
  1319. * Global fallback of {@linkcode CodeSplittingGroup.minSize | group.minSize}, if it's not specified in the group.
  1320. */
  1321. minSize?: number;
  1322. /**
  1323. * Global fallback of {@linkcode CodeSplittingGroup.maxSize | group.maxSize}, if it's not specified in the group.
  1324. */
  1325. maxSize?: number;
  1326. /**
  1327. * Global fallback of {@linkcode CodeSplittingGroup.maxModuleSize | group.maxModuleSize}, if it's not specified in the group.
  1328. */
  1329. maxModuleSize?: number;
  1330. /**
  1331. * Global fallback of {@linkcode CodeSplittingGroup.minModuleSize | group.minModuleSize}, if it's not specified in the group.
  1332. */
  1333. minModuleSize?: number;
  1334. /**
  1335. * Global fallback of {@linkcode CodeSplittingGroup.minShareCount | group.minShareCount}, if it's not specified in the group.
  1336. */
  1337. minShareCount?: number;
  1338. /**
  1339. * Groups to be used for code splitting.
  1340. */
  1341. groups?: CodeSplittingGroup[];
  1342. /**
  1343. * Replace small automatic common chunks with factory copies in their consumers.
  1344. *
  1345. * @experimental This feature is experimental. Its behavior and option shape may change in any release.
  1346. */
  1347. experimentalInlineCommonChunks?: ExperimentalInlineCommonChunksOptions;
  1348. };
  1349. /**
  1350. * Alias for {@linkcode CodeSplittingOptions}. Use this type for the `codeSplitting` option.
  1351. *
  1352. * @deprecated Please use {@linkcode CodeSplittingOptions} instead.
  1353. *
  1354. * @category Code Splitting
  1355. */
  1356. type AdvancedChunksOptions = CodeSplittingOptions;
  1357. //#endregion
  1358. //#region src/api/build.d.ts
  1359. /**
  1360. * The options for {@linkcode build} function.
  1361. *
  1362. * @experimental
  1363. * @category Programmatic APIs
  1364. */
  1365. type BuildOptions = InputOptions & {
  1366. /**
  1367. * Write the output to the file system
  1368. *
  1369. * @default true
  1370. */
  1371. write?: boolean;
  1372. output?: OutputOptions;
  1373. };
  1374. /**
  1375. * Build a single output.
  1376. *
  1377. * @param options The build options.
  1378. * @returns A Promise that resolves to the build output.
  1379. */
  1380. declare function build(options: BuildOptions): Promise<RolldownOutput>;
  1381. /**
  1382. * Build multiple outputs __sequentially__.
  1383. *
  1384. * @param options The build options.
  1385. * @returns A Promise that resolves to the build outputs for each option.
  1386. */
  1387. declare function build(options: BuildOptions[]): Promise<RolldownOutput[]>;
  1388. //#endregion
  1389. //#region src/api/rolldown/rolldown-build.d.ts
  1390. /**
  1391. * The bundle object returned by {@linkcode rolldown} function.
  1392. *
  1393. * @category Programmatic APIs
  1394. */
  1395. declare class RolldownBuild {
  1396. #private;
  1397. /** @hidden should not be used directly */
  1398. constructor(inputOptions: InputOptions);
  1399. /**
  1400. * Whether the bundle has been closed.
  1401. *
  1402. * If the bundle is closed, calling other methods will throw an error.
  1403. */
  1404. get closed(): boolean;
  1405. /**
  1406. * Generate bundles in-memory.
  1407. *
  1408. * If you directly want to write bundles to disk, use the {@linkcode write} method instead.
  1409. *
  1410. * @param outputOptions The output options.
  1411. * @returns The generated bundle.
  1412. * @throws {@linkcode BundleError} When an error occurs during the build.
  1413. */
  1414. generate(outputOptions?: OutputOptions): Promise<RolldownOutput>;
  1415. /**
  1416. * Generate and write bundles to disk.
  1417. *
  1418. * If you want to generate bundles in-memory, use the {@linkcode generate} method instead.
  1419. *
  1420. * @param outputOptions The output options.
  1421. * @returns The generated bundle.
  1422. * @throws {@linkcode BundleError} When an error occurs during the build.
  1423. */
  1424. write(outputOptions?: OutputOptions): Promise<RolldownOutput>;
  1425. /**
  1426. * Close the bundle and free resources.
  1427. *
  1428. * This method should be called even if the {@linkcode generate} method
  1429. * or the {@linkcode write} method threw an error. It should be called
  1430. * even if neither of the methods are called.
  1431. *
  1432. * This method is called automatically when using `using` syntax.
  1433. *
  1434. * @example
  1435. * ```js
  1436. * import { rolldown } from 'rolldown';
  1437. *
  1438. * {
  1439. * using bundle = await rolldown({ input: 'src/main.js' });
  1440. * const output = await bundle.generate({ format: 'esm' });
  1441. * console.log(output);
  1442. * // bundle.close() is called automatically here
  1443. * }
  1444. * ```
  1445. */
  1446. close(): Promise<void>;
  1447. /** @hidden documented in close method */
  1448. [Symbol.asyncDispose](): Promise<void>;
  1449. /**
  1450. * @experimental
  1451. * @hidden not ready for public usage yet
  1452. */
  1453. get watchFiles(): Promise<string[]>;
  1454. }
  1455. //#endregion
  1456. //#region src/api/rolldown/index.d.ts
  1457. /**
  1458. * The API compatible with Rollup's `rollup` function.
  1459. *
  1460. * Unlike Rollup, the module graph is not built until the methods of the bundle object are called.
  1461. *
  1462. * @param input The input options object.
  1463. * @returns A Promise that resolves to a bundle object.
  1464. *
  1465. * @example
  1466. * ```js
  1467. * import { rolldown } from 'rolldown';
  1468. *
  1469. * let bundle, failed = false;
  1470. * try {
  1471. * bundle = await rolldown({
  1472. * input: 'src/main.js',
  1473. * });
  1474. * await bundle.write({
  1475. * format: 'esm',
  1476. * });
  1477. * } catch (e) {
  1478. * console.error(e);
  1479. * failed = true;
  1480. * }
  1481. * if (bundle) {
  1482. * await bundle.close();
  1483. * }
  1484. * process.exitCode = failed ? 1 : 0;
  1485. * ```
  1486. *
  1487. * @category Programmatic APIs
  1488. */
  1489. declare const rolldown: (input: InputOptions) => Promise<RolldownBuild>;
  1490. //#endregion
  1491. //#region src/options/watch-options.d.ts
  1492. /** @category Programmatic APIs */
  1493. interface WatchOptions extends InputOptions {
  1494. output?: OutputOptions | OutputOptions[];
  1495. }
  1496. //#endregion
  1497. //#region src/api/watch/watch-emitter.d.ts
  1498. type ChangeEvent$1 = "create" | "update" | "delete";
  1499. type RolldownWatchBuild = BindingWatcherBundler;
  1500. /**
  1501. * - `START`: the watcher is (re)starting
  1502. * - `BUNDLE_START`: building an individual bundle
  1503. * - `BUNDLE_END`: finished building a bundle
  1504. * - `duration`: the build duration in milliseconds
  1505. * - `output`: an array of the {@linkcode OutputOptions.file | file} or {@linkcode OutputOptions.dir | dir} option values of the generated outputs
  1506. * - `result`: the bundle object that can be used to generate additional outputs. This is especially important when the watch.skipWrite option is used. You should call `event.result.close()` once you are done generating outputs, or if you do not generate outputs. This will allow plugins to clean up resources via the `closeBundle` hook.
  1507. * - `END`: finished building all bundles
  1508. * - `ERROR`: encountered an error while bundling
  1509. * - `error`: the error that was thrown
  1510. * - `result`: the bundle object
  1511. *
  1512. * @category Programmatic APIs
  1513. */
  1514. type RolldownWatcherEvent = {
  1515. code: "START";
  1516. } | {
  1517. code: "BUNDLE_START";
  1518. } | {
  1519. code: "BUNDLE_END";
  1520. duration: number;
  1521. output: readonly string[];
  1522. result: RolldownWatchBuild;
  1523. } | {
  1524. code: "END";
  1525. } | {
  1526. code: "ERROR";
  1527. error: Error;
  1528. result: RolldownWatchBuild;
  1529. };
  1530. /**
  1531. *
  1532. * @category Programmatic APIs
  1533. */
  1534. type RolldownWatcherWatcherEventMap = {
  1535. event: [data: RolldownWatcherEvent];
  1536. /** a file was modified */
  1537. change: [id: string, change: {
  1538. event: ChangeEvent$1;
  1539. }];
  1540. /** a new run was triggered */
  1541. restart: [];
  1542. /** the watcher was closed */
  1543. close: [];
  1544. };
  1545. /**
  1546. * @category Programmatic APIs
  1547. */
  1548. interface RolldownWatcher {
  1549. /**
  1550. * Register a listener for events defined in {@linkcode RolldownWatcherWatcherEventMap}.
  1551. */
  1552. on<E extends keyof RolldownWatcherWatcherEventMap>(event: E, listener: (...args: RolldownWatcherWatcherEventMap[E]) => MaybePromise<void>): this;
  1553. /**
  1554. * Unregister a listener for events defined in {@linkcode RolldownWatcherWatcherEventMap}.
  1555. */
  1556. off<E extends keyof RolldownWatcherWatcherEventMap>(event: E, listener: (...args: RolldownWatcherWatcherEventMap[E]) => MaybePromise<void>): this;
  1557. /**
  1558. * Unregister all listeners for a specific event defined in {@linkcode RolldownWatcherWatcherEventMap}.
  1559. */
  1560. clear<E extends keyof RolldownWatcherWatcherEventMap>(event: E): void;
  1561. /**
  1562. * Close the watcher and stop listening for file changes.
  1563. */
  1564. close(): Promise<void>;
  1565. }
  1566. //#endregion
  1567. //#region src/api/watch/index.d.ts
  1568. /**
  1569. * The API compatible with Rollup's `watch` function.
  1570. *
  1571. * This function will rebuild the bundle when it detects that the individual modules have changed on disk.
  1572. *
  1573. * Note that when using this function, it is your responsibility to call `event.result.close()` in response to the `BUNDLE_END` event to avoid resource leaks.
  1574. *
  1575. * @param input The watch options object or the list of them.
  1576. * @returns A watcher object.
  1577. *
  1578. * @example
  1579. * ```js
  1580. * import { watch } from 'rolldown';
  1581. *
  1582. * const watcher = watch({ /* ... *\/ });
  1583. * watcher.on('event', (event) => {
  1584. * if (event.code === 'BUNDLE_END') {
  1585. * console.log(event.duration);
  1586. * event.result.close();
  1587. * }
  1588. * });
  1589. *
  1590. * // Stop watching
  1591. * watcher.close();
  1592. * ```
  1593. *
  1594. * @experimental
  1595. * @category Programmatic APIs
  1596. */
  1597. declare function watch(input: WatchOptions | WatchOptions[]): RolldownWatcher;
  1598. //#endregion
  1599. //#region src/binding-magic-string.d.ts
  1600. interface RolldownMagicString extends BindingMagicString {
  1601. readonly isRolldownMagicString: true;
  1602. /** Accepts a string or RegExp pattern. RegExp supports `$&`, `$$`, and `$N` substitutions. */
  1603. replace(from: string | RegExp, to: string): this;
  1604. /** Accepts a string or RegExp pattern. RegExp must have the global (`g`) flag. */
  1605. replaceAll(from: string | RegExp, to: string): this;
  1606. }
  1607. type RolldownMagicStringConstructor = Omit<typeof BindingMagicString, "prototype"> & {
  1608. new (...args: ConstructorParameters<typeof BindingMagicString>): RolldownMagicString;
  1609. prototype: RolldownMagicString;
  1610. };
  1611. /**
  1612. * A native MagicString implementation powered by Rust.
  1613. *
  1614. * @experimental
  1615. */
  1616. declare const RolldownMagicString: RolldownMagicStringConstructor;
  1617. //#endregion
  1618. //#region src/log/log-handler.d.ts
  1619. type LoggingFunction = (log: RolldownLog | string | (() => RolldownLog | string)) => void;
  1620. type LoggingFunctionWithPosition = (log: RolldownLog | string | (() => RolldownLog | string), pos?: number | {
  1621. column: number;
  1622. line: number;
  1623. }) => void;
  1624. type WarningHandlerWithDefault = (warning: RolldownLog, defaultHandler: LoggingFunction) => void;
  1625. //#endregion
  1626. //#region src/options/generated/checks-options.d.ts
  1627. interface ChecksOptions {
  1628. /**
  1629. * Whether to emit warnings when detecting circular dependency.
  1630. *
  1631. * Circular dependencies lead to a bigger bundle size and sometimes cause execution order issues and are better to avoid.
  1632. *
  1633. *
  1634. * @default false
  1635. * */
  1636. circularDependency?: boolean;
  1637. /**
  1638. * Whether to emit warnings when detecting uses of direct `eval`s.
  1639. *
  1640. * See [Avoiding Direct `eval` in Troubleshooting page](https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval) for more details.
  1641. * @default true
  1642. * */
  1643. eval?: boolean;
  1644. /**
  1645. * Whether to emit warnings when the `output.globals` option is missing when needed.
  1646. *
  1647. * See [`output.globals`](https://rolldown.rs/reference/OutputOptions.globals).
  1648. * @default true
  1649. * */
  1650. missingGlobalName?: boolean;
  1651. /**
  1652. * Whether to emit warnings when the `output.name` option is missing when needed.
  1653. *
  1654. * See [`output.name`](https://rolldown.rs/reference/OutputOptions.name).
  1655. * @default true
  1656. * */
  1657. missingNameOptionForIifeExport?: boolean;
  1658. /**
  1659. * Whether to emit warnings when a `#__PURE__` / `@__PURE__` annotation has no effect due to its position.
  1660. *
  1661. * Annotations placed where they cannot annotate a call expression (e.g. before a non-call expression,
  1662. * before a statement declaration, or between an identifier and `=` in a variable declarator) are
  1663. * ignored by the parser. Matches Rollup's `INVALID_ANNOTATION` log code.
  1664. *
  1665. * By default, warnings are emitted only for local project files inside `cwd` and outside
  1666. * `node_modules`. Set this option to `false` to disable the warning entirely.
  1667. * @default true
  1668. * */
  1669. invalidAnnotation?: boolean;
  1670. /**
  1671. * Whether to emit warnings when the way to export values is ambiguous.
  1672. *
  1673. * See [`output.exports`](https://rolldown.rs/reference/OutputOptions.exports).
  1674. * @default true
  1675. * */
  1676. mixedExports?: boolean;
  1677. /**
  1678. * Whether to emit warnings when an entrypoint cannot be resolved.
  1679. * @default true
  1680. * */
  1681. unresolvedEntry?: boolean;
  1682. /**
  1683. * Whether to emit warnings when an import cannot be resolved.
  1684. * @default true
  1685. * */
  1686. unresolvedImport?: boolean;
  1687. /**
  1688. * Whether to emit warnings when files generated have the same name with different contents.
  1689. *
  1690. *
  1691. * @default true
  1692. * */
  1693. filenameConflict?: boolean;
  1694. /**
  1695. * Whether to emit warnings for module-level directives other than `use strict`.
  1696. * @default true
  1697. * */
  1698. moduleLevelDirective?: boolean;
  1699. /**
  1700. * Whether to emit warnings when a CommonJS variable is used in an ES module.
  1701. *
  1702. * CommonJS variables like `module` and `exports` are treated as global variables in ES modules and may not work as expected.
  1703. *
  1704. *
  1705. * @default true
  1706. * */
  1707. commonJsVariableInEsm?: boolean;
  1708. /**
  1709. * Whether to emit warnings when an imported variable is not exported.
  1710. *
  1711. * If the code is importing a variable that is not exported by the imported module, the value will always be `undefined`. This might be a mistake in the code.
  1712. *
  1713. *
  1714. * @default true
  1715. * */
  1716. importIsUndefined?: boolean;
  1717. /**
  1718. * Whether to emit warnings when `import.meta` is not supported with the output format and is replaced with an empty object (`{}`).
  1719. *
  1720. * See [`import.meta` in Non-ESM Output Formats page](https://rolldown.rs/in-depth/non-esm-output-formats#import-meta) for more details.
  1721. * @default true
  1722. * */
  1723. emptyImportMeta?: boolean;
  1724. /**
  1725. * Whether to emit warnings when detecting tolerated transform.
  1726. * @default true
  1727. * */
  1728. toleratedTransform?: boolean;
  1729. /**
  1730. * Whether to emit warnings when a namespace is called as a function.
  1731. *
  1732. * A module namespace object is an object and not a function. Calling it as a function will cause a runtime error.
  1733. *
  1734. *
  1735. * @default true
  1736. * */
  1737. cannotCallNamespace?: boolean;
  1738. /**
  1739. * Whether to emit warnings when a config value is overridden by another config value with a higher priority.
  1740. *
  1741. *
  1742. * @default true
  1743. * */
  1744. configurationFieldConflict?: boolean;
  1745. /**
  1746. * Whether to emit warnings when a plugin that is covered by a built-in feature is used.
  1747. *
  1748. * Using built-in features is generally more performant than using plugins.
  1749. * @default true
  1750. * */
  1751. preferBuiltinFeature?: boolean;
  1752. /**
  1753. * Whether to emit warnings when Rolldown could not clean the output directory.
  1754. *
  1755. * See [`output.cleanDir`](https://rolldown.rs/reference/OutputOptions.cleanDir).
  1756. * @default true
  1757. * */
  1758. couldNotCleanDirectory?: boolean;
  1759. /**
  1760. * Whether to emit warnings when plugins and option callbacks take significant time during the build process.
  1761. *
  1762. *
  1763. * @default true
  1764. * */
  1765. bundlerTimings?: boolean;
  1766. /**
  1767. * @deprecated Use {@linkcode bundlerTimings}. If `bundlerTimings` and `pluginTimings` have values, Rolldown uses `bundlerTimings`.
  1768. */
  1769. pluginTimings?: boolean;
  1770. /**
  1771. * Whether to emit warnings when both the code and postBanner contain shebang
  1772. *
  1773. * Having multiple shebangs in a file is a syntax error.
  1774. * @default true
  1775. * */
  1776. duplicateShebang?: boolean;
  1777. /**
  1778. * Whether to emit warnings when a tsconfig option or combination of options is not supported.
  1779. * @default true
  1780. * */
  1781. unsupportedTsconfigOption?: boolean;
  1782. /**
  1783. * Whether to emit warnings when a module is dynamically imported but also statically imported, making the dynamic import ineffective for code splitting.
  1784. * @default true
  1785. * */
  1786. ineffectiveDynamicImport?: boolean;
  1787. /**
  1788. * Whether to emit info logs when a barrel module has a very large number of re-exports (more than 5000).
  1789. *
  1790. * Such modules can significantly slow down module resolution. Consider using
  1791. * [`@rolldown/plugin-transform-imports`](https://github.com/rolldown/plugins/tree/main/packages/transform-imports)
  1792. * to rewrite barrel imports at the source level so the barrel file is never loaded.
  1793. *
  1794. * See [Large barrel modules](https://rolldown.rs/in-depth/lazy-barrel-optimization#large-barrel-modules) for more details.
  1795. * @default true
  1796. * */
  1797. largeBarrelModules?: boolean;
  1798. /**
  1799. * Whether to emit warnings when a plugin transforms code without generating a sourcemap.
  1800. * @default true
  1801. * */
  1802. sourcemapBroken?: boolean;
  1803. /**
  1804. * Whether to emit warnings when multiple star re-exports provide the same name from different modules.
  1805. * @default true
  1806. * */
  1807. namespaceConflict?: boolean;
  1808. }
  1809. //#endregion
  1810. //#region src/options/transform-options.d.ts
  1811. interface TransformOptions extends Omit<TransformOptions$1, "sourceType" | "lang" | "cwd" | "sourcemap" | "define" | "inject" | "jsx"> {
  1812. /**
  1813. * Replace global variables or [property accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) with the provided values.
  1814. *
  1815. * See Oxc's [`define` option](https://oxc.rs/docs/guide/usage/transformer/global-variable-replacement.html#define) for more details.
  1816. *
  1817. * @example
  1818. * **Replace the global variable `IS_PROD` with `true`**
  1819. * ```js [rolldown.config.js]
  1820. * export default defineConfig({
  1821. * transform: { define: { IS_PROD: 'true' } }
  1822. * })
  1823. * ```
  1824. * Result:
  1825. * ```js
  1826. * // Input
  1827. * if (IS_PROD) {
  1828. * console.log('Production mode')
  1829. * }
  1830. *
  1831. * // After bundling
  1832. * if (true) {
  1833. * console.log('Production mode')
  1834. * }
  1835. * ```
  1836. *
  1837. * **Replace the property accessor `process.env.NODE_ENV` with `'production'`**
  1838. * ```js [rolldown.config.js]
  1839. * export default defineConfig({
  1840. * transform: { define: { 'process.env.NODE_ENV': "'production'" } }
  1841. * })
  1842. * ```
  1843. * Result:
  1844. * ```js
  1845. * // Input
  1846. * if (process.env.NODE_ENV === 'production') {
  1847. * console.log('Production mode')
  1848. * }
  1849. *
  1850. * // After bundling
  1851. * if ('production' === 'production') {
  1852. * console.log('Production mode')
  1853. * }
  1854. * ```
  1855. */
  1856. define?: Record<string, string>;
  1857. /**
  1858. * Inject import statements on demand.
  1859. *
  1860. * The API is aligned with `@rollup/plugin-inject`.
  1861. *
  1862. * See Oxc's [`inject` option](https://oxc.rs/docs/guide/usage/transformer/global-variable-replacement.html#inject) for more details.
  1863. *
  1864. * #### Supported patterns
  1865. * ```js
  1866. * {
  1867. * // import { Promise } from 'es6-promise'
  1868. * Promise: ['es6-promise', 'Promise'],
  1869. *
  1870. * // import { Promise as P } from 'es6-promise'
  1871. * P: ['es6-promise', 'Promise'],
  1872. *
  1873. * // import $ from 'jquery'
  1874. * $: 'jquery',
  1875. *
  1876. * // import * as fs from 'node:fs'
  1877. * fs: ['node:fs', '*'],
  1878. *
  1879. * // Inject shims for property access pattern
  1880. * 'Object.assign': path.resolve( 'src/helpers/object-assign.js' ),
  1881. * }
  1882. * ```
  1883. */
  1884. inject?: Record<string, string | [string, string]>;
  1885. /**
  1886. * Remove labeled statements with these label names.
  1887. *
  1888. * Labeled statements are JavaScript statements prefixed with a label identifier.
  1889. * This option allows you to strip specific labeled statements from the output,
  1890. * which is useful for removing debug-only code in production builds.
  1891. *
  1892. * @example
  1893. * ```js rolldown.config.js
  1894. * export default defineConfig({
  1895. * transform: { dropLabels: ['DEBUG', 'DEV'] }
  1896. * })
  1897. * ```
  1898. * Result:
  1899. * ```js
  1900. * // Input
  1901. * DEBUG: console.log('Debug info');
  1902. * DEV: {
  1903. * console.log('Development mode');
  1904. * }
  1905. * console.log('Production code');
  1906. *
  1907. * // After bundling
  1908. * console.log('Production code');
  1909. * ```
  1910. */
  1911. dropLabels?: string[];
  1912. /**
  1913. * Controls how JSX syntax is transformed.
  1914. *
  1915. * - If set to `false`, an error will be thrown if JSX syntax is encountered.
  1916. * - If set to `'react'`, JSX syntax will be transformed to classic runtime React code.
  1917. * - If set to `'react-jsx'`, JSX syntax will be transformed to automatic runtime React code.
  1918. * - If set to `'preserve'`, JSX syntax will be preserved as-is.
  1919. */
  1920. jsx?: false | "react" | "react-jsx" | "preserve" | JsxOptions;
  1921. }
  1922. //#endregion
  1923. //#region src/options/normalized-input-options.d.ts
  1924. /** @category Plugin APIs */
  1925. interface NormalizedInputOptions {
  1926. /** @see {@linkcode InputOptions.input | input} */
  1927. input: string[] | Record<string, string>;
  1928. /** @see {@linkcode InputOptions.cwd | cwd} */
  1929. cwd: string;
  1930. /** @see {@linkcode InputOptions.platform | platform} */
  1931. platform: InputOptions["platform"];
  1932. /** @see {@linkcode InputOptions.shimMissingExports | shimMissingExports} */
  1933. shimMissingExports: boolean;
  1934. /** @see {@linkcode InputOptions.context | context} */
  1935. context: string;
  1936. /** @see {@linkcode InputOptions.plugins | plugins} */
  1937. plugins: RolldownPlugin[];
  1938. }
  1939. //#endregion
  1940. //#region src/options/normalized-output-options.d.ts
  1941. type PathsFunction = (id: string) => string;
  1942. /**
  1943. * A normalized version of {@linkcode ModuleFormat}.
  1944. * @category Plugin APIs
  1945. */
  1946. type InternalModuleFormat = "es" | "cjs" | "iife" | "umd";
  1947. /** @category Plugin APIs */
  1948. interface NormalizedOutputOptions {
  1949. /** @see {@linkcode OutputOptions.name | name} */
  1950. name: string | undefined;
  1951. /** @see {@linkcode OutputOptions.file | file} */
  1952. file: string | undefined;
  1953. /** @see {@linkcode OutputOptions.dir | dir} */
  1954. dir: string | undefined;
  1955. /** @see {@linkcode OutputOptions.entryFileNames | entryFileNames} */
  1956. entryFileNames: string | ChunkFileNamesFunction;
  1957. /** @see {@linkcode OutputOptions.sourcemapFileNames | sourcemapFileNames} */
  1958. sourcemapFileNames: string | ChunkFileNamesFunction | undefined;
  1959. /** @see {@linkcode OutputOptions.chunkFileNames | chunkFileNames} */
  1960. chunkFileNames: string | ChunkFileNamesFunction;
  1961. /** @see {@linkcode OutputOptions.assetFileNames | assetFileNames} */
  1962. assetFileNames: string | AssetFileNamesFunction;
  1963. /** @see {@linkcode OutputOptions.format | format} */
  1964. format: InternalModuleFormat;
  1965. /** @see {@linkcode OutputOptions.exports | exports} */
  1966. exports: NonNullable<OutputOptions["exports"]>;
  1967. /** @see {@linkcode OutputOptions.sourcemap | sourcemap} */
  1968. sourcemap: boolean | "inline" | "hidden";
  1969. /** @see {@linkcode OutputOptions.sourcemapBaseUrl | sourcemapBaseUrl} */
  1970. sourcemapBaseUrl: string | undefined;
  1971. /** @see {@linkcode OutputOptions.codeSplitting | codeSplitting} */
  1972. codeSplitting: boolean;
  1973. /** @deprecated Use `codeSplitting` instead. */
  1974. inlineDynamicImports: boolean;
  1975. /** @see {@linkcode OutputOptions.dynamicImportInCjs | dynamicImportInCjs} */
  1976. dynamicImportInCjs: boolean;
  1977. /** @see {@linkcode OutputOptions.externalLiveBindings | externalLiveBindings} */
  1978. externalLiveBindings: boolean;
  1979. /** @see {@linkcode OutputOptions.banner | banner} */
  1980. banner: AddonFunction;
  1981. /** @see {@linkcode OutputOptions.footer | footer} */
  1982. footer: AddonFunction;
  1983. /** @see {@linkcode OutputOptions.postBanner | postBanner} */
  1984. postBanner: AddonFunction;
  1985. /** @see {@linkcode OutputOptions.postFooter | postFooter} */
  1986. postFooter: AddonFunction;
  1987. /** @see {@linkcode OutputOptions.intro | intro} */
  1988. intro: AddonFunction;
  1989. /** @see {@linkcode OutputOptions.outro | outro} */
  1990. outro: AddonFunction;
  1991. /** @see {@linkcode OutputOptions.esModule | esModule} */
  1992. esModule: boolean | "if-default-prop";
  1993. /** @see {@linkcode OutputOptions.extend | extend} */
  1994. extend: boolean;
  1995. /** @see {@linkcode OutputOptions.globals | globals} */
  1996. globals: Record<string, string> | GlobalsFunction;
  1997. /** @see {@linkcode OutputOptions.paths | paths} */
  1998. paths: Record<string, string> | PathsFunction | undefined;
  1999. /** @see {@linkcode OutputOptions.hashCharacters | hashCharacters} */
  2000. hashCharacters: "base64" | "base36" | "hex";
  2001. /** @see {@linkcode OutputOptions.sourcemapDebugIds | sourcemapDebugIds} */
  2002. sourcemapDebugIds: boolean;
  2003. /** @see {@linkcode OutputOptions.sourcemapExcludeSources | sourcemapExcludeSources} */
  2004. sourcemapExcludeSources: boolean;
  2005. /** @see {@linkcode OutputOptions.sourcemapIgnoreList | sourcemapIgnoreList} */
  2006. sourcemapIgnoreList: boolean | SourcemapIgnoreListOption | StringOrRegExp | undefined;
  2007. /** @see {@linkcode OutputOptions.sourcemapPathTransform | sourcemapPathTransform} */
  2008. sourcemapPathTransform: SourcemapPathTransformOption | undefined;
  2009. /** @see {@linkcode OutputOptions.minify | minify} */
  2010. minify: false | MinifyOptions | "dce-only";
  2011. /**
  2012. * @deprecated Use `comments.legal` instead.
  2013. * @see {@linkcode OutputOptions.legalComments | legalComments}
  2014. */
  2015. legalComments: "none" | "inline";
  2016. /** @see {@linkcode OutputOptions.comments | comments} */
  2017. comments: Required<CommentsOptions>;
  2018. /** @see {@linkcode OutputOptions.polyfillRequire | polyfillRequire} */
  2019. polyfillRequire: boolean;
  2020. /** @see {@linkcode OutputOptions.plugins | plugins} */
  2021. plugins: RolldownPlugin[];
  2022. /** @see {@linkcode OutputOptions.preserveModules | preserveModules} */
  2023. preserveModules: boolean;
  2024. /** @see {@linkcode OutputOptions.virtualDirname | virtualDirname} */
  2025. virtualDirname: string;
  2026. /** @see {@linkcode OutputOptions.preserveModulesRoot | preserveModulesRoot} */
  2027. preserveModulesRoot?: string;
  2028. /** @see {@linkcode OutputOptions.topLevelVar | topLevelVar} */
  2029. topLevelVar?: boolean;
  2030. /** @see {@linkcode OutputOptions.minifyInternalExports | minifyInternalExports} */
  2031. minifyInternalExports?: boolean;
  2032. }
  2033. //#endregion
  2034. //#region src/plugin/fs.d.ts
  2035. /** @category Plugin APIs */
  2036. interface RolldownFsModule {
  2037. appendFile(path: string, data: string | Uint8Array, options?: {
  2038. encoding?: BufferEncoding | null;
  2039. mode?: string | number;
  2040. flag?: string | number;
  2041. }): Promise<void>;
  2042. copyFile(source: string, destination: string, mode?: string | number): Promise<void>;
  2043. mkdir(path: string, options?: {
  2044. recursive?: boolean;
  2045. mode?: string | number;
  2046. }): Promise<void>;
  2047. mkdtemp(prefix: string): Promise<string>;
  2048. readdir(path: string, options?: {
  2049. withFileTypes?: false;
  2050. }): Promise<string[]>;
  2051. readdir(path: string, options?: {
  2052. withFileTypes: true;
  2053. }): Promise<RolldownDirectoryEntry[]>;
  2054. readFile(path: string, options?: {
  2055. encoding?: null;
  2056. flag?: string | number;
  2057. signal?: AbortSignal;
  2058. }): Promise<Uint8Array>;
  2059. readFile(path: string, options?: {
  2060. encoding: BufferEncoding;
  2061. flag?: string | number;
  2062. signal?: AbortSignal;
  2063. }): Promise<string>;
  2064. realpath(path: string): Promise<string>;
  2065. rename(oldPath: string, newPath: string): Promise<void>;
  2066. rmdir(path: string, options?: {
  2067. recursive?: boolean;
  2068. }): Promise<void>;
  2069. stat(path: string): Promise<RolldownFileStats>;
  2070. lstat(path: string): Promise<RolldownFileStats>;
  2071. unlink(path: string): Promise<void>;
  2072. writeFile(path: string, data: string | Uint8Array, options?: {
  2073. encoding?: BufferEncoding | null;
  2074. mode?: string | number;
  2075. flag?: string | number;
  2076. }): Promise<void>;
  2077. }
  2078. /** @category Plugin APIs */
  2079. type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "base64url" | "latin1" | "binary" | "hex";
  2080. /** @category Plugin APIs */
  2081. interface RolldownDirectoryEntry {
  2082. isFile(): boolean;
  2083. isDirectory(): boolean;
  2084. isSymbolicLink(): boolean;
  2085. name: string;
  2086. }
  2087. /** @category Plugin APIs */
  2088. interface RolldownFileStats {
  2089. isFile(): boolean;
  2090. isDirectory(): boolean;
  2091. isSymbolicLink(): boolean;
  2092. size: number;
  2093. mtime: Date;
  2094. ctime: Date;
  2095. atime: Date;
  2096. birthtime: Date;
  2097. }
  2098. //#endregion
  2099. //#region src/plugin/hook-filter.d.ts
  2100. /** @category Plugin APIs */
  2101. type GeneralHookFilter<Value = StringOrRegExp> = MaybeArray<Value> | {
  2102. include?: MaybeArray<Value>;
  2103. exclude?: MaybeArray<Value>;
  2104. };
  2105. interface FormalModuleTypeFilter {
  2106. include?: ModuleType[];
  2107. }
  2108. /** @category Plugin APIs */
  2109. type ModuleTypeFilter = ModuleType[] | FormalModuleTypeFilter;
  2110. /**
  2111. * A filter to be used to do a pre-test to determine whether the hook should be called.
  2112. *
  2113. * See [Plugin Hook Filters page](https://rolldown.rs/apis/plugin-api/hook-filters) for more details.
  2114. *
  2115. * @category Plugin APIs
  2116. */
  2117. interface HookFilter {
  2118. /**
  2119. * A filter based on the module `id`.
  2120. *
  2121. * If the value is a string, it is treated as a glob pattern.
  2122. * The string type is not available for {@linkcode Plugin.resolveId | resolveId} hook.
  2123. *
  2124. * If the value is a regular expression, it is tested after the `id`'s path separators are normalized to forward slashes (`/`).
  2125. * This keeps the filter portable across operating systems without requiring the regular expression to match both `/` and `\`.
  2126. *
  2127. * @example
  2128. * Include all `id`s that contain `node_modules` in the path.
  2129. * ```js
  2130. * { id: '**'+'/node_modules/**' }
  2131. * ```
  2132. * @example
  2133. * Include all `id`s that contain `node_modules` or `src` in the path.
  2134. * ```js
  2135. * { id: ['**'+'/node_modules/**', '**'+'/src/**'] }
  2136. * ```
  2137. * @example
  2138. * Include all `id`s that start with `http`
  2139. * ```js
  2140. * { id: /^http/ }
  2141. * ```
  2142. * @example
  2143. * Exclude all `id`s that contain `node_modules` in the path.
  2144. * ```js
  2145. * { id: { exclude: '**'+'/node_modules/**' } }
  2146. * ```
  2147. * @example
  2148. * Formal pattern to define includes and excludes.
  2149. * ```js
  2150. * { id : {
  2151. * include: ['**'+'/foo/**', /bar/],
  2152. * exclude: ['**'+'/baz/**', /qux/]
  2153. * }}
  2154. * ```
  2155. */
  2156. id?: GeneralHookFilter;
  2157. /**
  2158. * A filter based on the module's `moduleType`.
  2159. *
  2160. * Only available for {@linkcode Plugin.transform | transform} hook.
  2161. */
  2162. moduleType?: ModuleTypeFilter;
  2163. /**
  2164. * A filter based on the module's code.
  2165. *
  2166. * Only available for {@linkcode Plugin.transform | transform} hook.
  2167. */
  2168. code?: GeneralHookFilter;
  2169. }
  2170. //#endregion
  2171. //#region src/plugin/minimal-plugin-context.d.ts
  2172. /** @category Plugin APIs */
  2173. interface PluginContextMeta {
  2174. /**
  2175. * A property for Rollup compatibility. A dummy value is set by Rolldown.
  2176. * @example `'4.23.0'`
  2177. */
  2178. rollupVersion: string;
  2179. /**
  2180. * The currently running version of Rolldown.
  2181. * @example `'1.0.0'`
  2182. */
  2183. rolldownVersion: string;
  2184. /**
  2185. * Whether Rolldown was started via {@linkcode watch | rolldown.watch()} or
  2186. * from the command line with `--watch`.
  2187. */
  2188. watchMode: boolean;
  2189. }
  2190. /** @category Plugin APIs */
  2191. interface MinimalPluginContext {
  2192. /**
  2193. * Similar to {@linkcode warn | this.warn}, except that it will also abort
  2194. * the bundling process with an error.
  2195. *
  2196. * If an Error instance is passed, it will be used as-is, otherwise a new Error
  2197. * instance will be created with the given error message and all additional
  2198. * provided properties.
  2199. *
  2200. * In all hooks except the {@linkcode Plugin.onLog | onLog} hook, the error will
  2201. * be augmented with {@linkcode RolldownLog.code | code: "PLUGIN_ERROR"} and
  2202. * {@linkcode RolldownLog.plugin | plugin: plugin.name} properties.
  2203. * If a `code` property already exists and the code does not start with `PLUGIN_`,
  2204. * it will be renamed to {@linkcode RolldownLog.pluginCode | pluginCode}.
  2205. *
  2206. * @group Logging Methods
  2207. */
  2208. error: (e: RolldownError | string) => never;
  2209. /**
  2210. * Generate a `"info"` level log.
  2211. *
  2212. * {@linkcode RolldownLog.code | code} will be set to `"PLUGIN_LOG"` by Rolldown.
  2213. * As these logs are displayed by default, use them for information that is not a warning
  2214. * but makes sense to display to all users on every build.
  2215. *
  2216. *
  2217. *
  2218. * @inlineType LoggingFunction
  2219. * @group Logging Methods
  2220. */
  2221. info: LoggingFunction;
  2222. /**
  2223. * Generate a `"warn"` level log.
  2224. *
  2225. * Just like internally generated warnings, these logs will be first passed to and
  2226. * filtered by plugin {@linkcode Plugin.onLog | onLog} hooks before they are forwarded
  2227. * to custom {@linkcode InputOptions.onLog | onLog} or
  2228. * {@linkcode InputOptions.onwarn | onwarn} handlers or printed to the console.
  2229. *
  2230. * We encourage you to use objects with a {@linkcode RolldownLog.pluginCode | pluginCode}
  2231. * property as that will allow users to easily filter for those logs in an `onLog` handler.
  2232. *
  2233. *
  2234. *
  2235. * @inlineType LoggingFunction
  2236. * @group Logging Methods
  2237. */
  2238. warn: LoggingFunction;
  2239. /**
  2240. * Generate a `"debug"` level log.
  2241. *
  2242. * {@linkcode RolldownLog.code | code} will be set to `"PLUGIN_LOG"` by Rolldown.
  2243. * Make sure to add a distinctive {@linkcode RolldownLog.pluginCode | pluginCode} to
  2244. * those logs for easy filtering.
  2245. *
  2246. *
  2247. *
  2248. * @inlineType LoggingFunction
  2249. * @group Logging Methods
  2250. */
  2251. debug: LoggingFunction;
  2252. /** An object containing potentially useful metadata. */
  2253. meta: PluginContextMeta;
  2254. }
  2255. //#endregion
  2256. //#region src/plugin/parallel-plugin.d.ts
  2257. type ParallelPlugin = {
  2258. _parallel: {
  2259. fileUrl: string;
  2260. options: unknown;
  2261. };
  2262. };
  2263. /** @internal */
  2264. type DefineParallelPluginResult<Options> = (options: Options) => ParallelPlugin;
  2265. declare function defineParallelPlugin<Options>(pluginPath: string): DefineParallelPluginResult<Options>;
  2266. //#endregion
  2267. //#region src/plugin/plugin-context.d.ts
  2268. /**
  2269. * Either a {@linkcode name} or a {@linkcode fileName} can be supplied.
  2270. * If a {@linkcode fileName} is provided, it will be used unmodified as the name
  2271. * of the generated file, throwing an error if this causes a conflict.
  2272. * Otherwise, if a {@linkcode name} is supplied, this will be used as substitution
  2273. * for `[name]` in the corresponding
  2274. * {@linkcode OutputOptions.assetFileNames | output.assetFileNames} pattern, possibly
  2275. * adding a unique number to the end of the file name to avoid conflicts.
  2276. * If neither a {@linkcode name} nor {@linkcode fileName} is supplied, a default name will be used.
  2277. *
  2278. * @category Plugin APIs
  2279. */
  2280. interface EmittedAsset {
  2281. type: "asset";
  2282. name?: string;
  2283. fileName?: string;
  2284. /**
  2285. * An absolute path to the original file if this asset corresponds to a file on disk.
  2286. *
  2287. * This property will be passed on to subsequent plugin hooks that receive a
  2288. * {@linkcode PreRenderedAsset} or an {@linkcode OutputAsset} like
  2289. * {@linkcode Plugin.generateBundle | generateBundle}.
  2290. * In watch mode, Rolldown will also automatically watch this file for changes and
  2291. * trigger a rebuild if it changes. Therefore, it is not necessary to call
  2292. * {@linkcode PluginContext.addWatchFile | this.addWatchFile} for this file.
  2293. */
  2294. originalFileName?: string;
  2295. source: AssetSource;
  2296. }
  2297. /**
  2298. * Either a {@linkcode name} or a {@linkcode fileName} can be supplied.
  2299. * If a {@linkcode fileName} is provided, it will be used unmodified as the name
  2300. * of the generated file, throwing an error if this causes a conflict.
  2301. * Otherwise, if a {@linkcode name} is supplied, this will be used as substitution
  2302. * for `[name]` in the corresponding
  2303. * {@linkcode OutputOptions.chunkFileNames | output.chunkFileNames} pattern, possibly
  2304. * adding a unique number to the end of the file name to avoid conflicts.
  2305. * If neither a {@linkcode name} nor {@linkcode fileName} is supplied, a default name will be used.
  2306. *
  2307. * @category Plugin APIs
  2308. */
  2309. interface EmittedChunk {
  2310. type: "chunk";
  2311. name?: string;
  2312. fileName?: string;
  2313. /**
  2314. * When provided, this will override
  2315. * {@linkcode InputOptions.preserveEntrySignatures | preserveEntrySignatures} for this particular
  2316. * chunk.
  2317. */
  2318. preserveSignature?: "strict" | "allow-extension" | "exports-only" | false;
  2319. /**
  2320. * The module id of the entry point of the chunk.
  2321. *
  2322. * It will be passed through build hooks just like regular entry points,
  2323. * starting with {@linkcode Plugin.resolveId | resolveId}.
  2324. */
  2325. id: string;
  2326. /**
  2327. * The value to be passed to {@linkcode Plugin.resolveId | resolveId}'s {@linkcode importer} parameter when resolving the entry point.
  2328. * This is important to properly resolve relative paths. If it is not provided,
  2329. * paths will be resolved relative to the current working directory.
  2330. */
  2331. importer?: string;
  2332. }
  2333. /** @category Plugin APIs */
  2334. interface EmittedPrebuiltChunk {
  2335. type: "prebuilt-chunk";
  2336. fileName: string;
  2337. /**
  2338. * A semantic name for the chunk. If not provided, `fileName` will be used.
  2339. */
  2340. name?: string;
  2341. /**
  2342. * The code of this chunk.
  2343. */
  2344. code: string;
  2345. /**
  2346. * The list of exported variable names from this chunk.
  2347. *
  2348. * This should be provided if the chunk exports any variables.
  2349. */
  2350. exports?: string[];
  2351. /**
  2352. * The corresponding source map for this chunk.
  2353. */
  2354. map?: SourceMap;
  2355. sourcemapFileName?: string;
  2356. /**
  2357. * The module id of the facade module for this chunk, if any.
  2358. */
  2359. facadeModuleId?: string;
  2360. /**
  2361. * Whether this chunk corresponds to an entry point.
  2362. */
  2363. isEntry?: boolean;
  2364. /**
  2365. * Whether this chunk corresponds to a dynamic entry point.
  2366. */
  2367. isDynamicEntry?: boolean;
  2368. }
  2369. /** @inline @category Plugin APIs */
  2370. type EmittedFile = EmittedAsset | EmittedChunk | EmittedPrebuiltChunk;
  2371. /** @category Plugin APIs */
  2372. interface PluginContextResolveOptions {
  2373. /**
  2374. * The value for {@linkcode ResolveIdExtraOptions.kind | kind} passed to
  2375. * {@linkcode Plugin.resolveId | resolveId} hooks.
  2376. */
  2377. kind?: BindingPluginContextResolveOptions["importKind"];
  2378. /**
  2379. * The value for {@linkcode ResolveIdExtraOptions.isEntry | isEntry} passed to
  2380. * {@linkcode Plugin.resolveId | resolveId} hooks.
  2381. *
  2382. * @default `false` if there's an importer, `true` otherwise.
  2383. */
  2384. isEntry?: boolean;
  2385. /**
  2386. * Whether the {@linkcode Plugin.resolveId | resolveId} hook of the plugin from
  2387. * which {@linkcode PluginContext.resolve | this.resolve} is called will be skipped
  2388. * when resolving.
  2389. *
  2390. *
  2391. *
  2392. * @default true
  2393. */
  2394. skipSelf?: boolean;
  2395. /**
  2396. * Plugin-specific options.
  2397. *
  2398. * See [Custom resolver options section](https://rolldown.rs/apis/plugin-api/inter-plugin-communication#custom-resolver-options) for more details.
  2399. */
  2400. custom?: CustomPluginOptions;
  2401. }
  2402. /** @inline */
  2403. type GetModuleInfo = (moduleId: string) => ModuleInfo | null;
  2404. /** @category Plugin APIs */
  2405. interface PluginContext extends MinimalPluginContext {
  2406. /**
  2407. * Provides abstract access to the file system.
  2408. */
  2409. fs: RolldownFsModule;
  2410. /**
  2411. * Emits a new file that is included in the build output.
  2412. * You can emit chunks, prebuilt chunks or assets.
  2413. *
  2414. *
  2415. *
  2416. * @returns A `referenceId` for the emitted file that can be used in various places to reference the emitted file.
  2417. */
  2418. emitFile(file: EmittedFile): string;
  2419. /**
  2420. * Get the file name of a chunk or asset that has been emitted via
  2421. * {@linkcode emitFile | this.emitFile}.
  2422. *
  2423. * @returns The file name of the emitted file. Relative to {@linkcode OutputOptions.dir | output.dir}.
  2424. */
  2425. getFileName(referenceId: string): string;
  2426. /**
  2427. * Get all module ids in the current module graph.
  2428. *
  2429. * @returns
  2430. * An iterator of module ids. It can be iterated via
  2431. * ```js
  2432. * for (const moduleId of this.getModuleIds()) {
  2433. * // ...
  2434. * }
  2435. * ```
  2436. * or converted into an array via `Array.from(this.getModuleIds())`.
  2437. */
  2438. getModuleIds(): IterableIterator<string>;
  2439. /**
  2440. * Get additional information about the module in question.
  2441. *
  2442. *
  2443. *
  2444. * @returns Module information for that module. `null` if the module could not be found.
  2445. * @group Methods
  2446. */
  2447. getModuleInfo: GetModuleInfo;
  2448. /**
  2449. * Adds additional files to be monitored in watch mode so that changes to these files will trigger rebuilds.
  2450. *
  2451. *
  2452. */
  2453. addWatchFile(id: string): void;
  2454. /**
  2455. * Loads and parses the module corresponding to the given id, attaching additional
  2456. * meta information to the module if provided. This will trigger the same
  2457. * {@linkcode Plugin.load | load}, {@linkcode Plugin.transform | transform} and
  2458. * {@linkcode Plugin.moduleParsed | moduleParsed} hooks as if the module was imported
  2459. * by another module.
  2460. *
  2461. *
  2462. */
  2463. load(options: {
  2464. id: string;
  2465. resolveDependencies?: boolean;
  2466. } & Partial<PartialNull<ModuleOptions>>): Promise<ModuleInfo>;
  2467. /**
  2468. * Use Rolldown's internal parser to parse code to an [ESTree-compatible](https://github.com/estree/estree) AST.
  2469. */
  2470. parse(input: string, options?: ParserOptions | null): Program;
  2471. /**
  2472. * Resolve imports to module ids (i.e. file names) using the same plugins that Rolldown uses,
  2473. * and determine if an import should be external.
  2474. *
  2475. * When calling this function from a {@linkcode Plugin.resolveId | resolveId} hook, you should
  2476. * always check if it makes sense for you to pass along the
  2477. * {@link PluginContextResolveOptions | options}.
  2478. *
  2479. * @returns
  2480. * If `Promise<null>` is returned, the import could not be resolved by Rolldown or any plugin
  2481. * but was not explicitly marked as external by the user.
  2482. * If an absolute external id is returned that should remain absolute in the output either
  2483. * via the
  2484. * {@linkcode InputOptions.makeAbsoluteExternalsRelative | makeAbsoluteExternalsRelative}
  2485. * option or by explicit plugin choice in the {@linkcode Plugin.resolveId | resolveId} hook,
  2486. * `external` will be `"absolute"` instead of `true`.
  2487. */
  2488. resolve(source: string, importer?: string, options?: PluginContextResolveOptions): Promise<ResolvedId | null>;
  2489. }
  2490. //#endregion
  2491. //#region src/plugin/transform-plugin-context.d.ts
  2492. /** @category Plugin APIs */
  2493. interface TransformPluginContext extends PluginContext {
  2494. /**
  2495. * Same as {@linkcode PluginContext.debug}, but a `position` param can be supplied.
  2496. *
  2497. * @inlineType LoggingFunctionWithPosition
  2498. * @group Logging Methods
  2499. */
  2500. debug: LoggingFunctionWithPosition;
  2501. /**
  2502. * Same as {@linkcode PluginContext.info}, but a `position` param can be supplied.
  2503. *
  2504. * @inlineType LoggingFunctionWithPosition
  2505. * @group Logging Methods
  2506. */
  2507. info: LoggingFunctionWithPosition;
  2508. /**
  2509. * Same as {@linkcode PluginContext.warn}, but a `position` param can be supplied.
  2510. *
  2511. * @inlineType LoggingFunctionWithPosition
  2512. * @group Logging Methods
  2513. */
  2514. warn: LoggingFunctionWithPosition;
  2515. /**
  2516. * Same as {@linkcode PluginContext.error}, but the `id` of the current module will
  2517. * also be added and a `position` param can be supplied.
  2518. */
  2519. error(e: RolldownError | string, pos?: number | {
  2520. column: number;
  2521. line: number;
  2522. }): never;
  2523. /**
  2524. * Get the combined source maps of all previous plugins.
  2525. */
  2526. getCombinedSourcemap(): SourceMap;
  2527. }
  2528. //#endregion
  2529. //#region src/types/module-side-effects.d.ts
  2530. interface ModuleSideEffectsRule {
  2531. test?: RegExp;
  2532. external?: boolean;
  2533. sideEffects: boolean;
  2534. }
  2535. type ModuleSideEffectsOption = boolean | readonly string[] | ModuleSideEffectsRule[] | ((id: string, external: boolean) => boolean | undefined) | "no-external";
  2536. /**
  2537. * When passing an object, you can fine-tune the tree-shaking behavior.
  2538. */
  2539. type TreeshakingOptions = {
  2540. /**
  2541. * **Values:**
  2542. *
  2543. * - **`true`**: All modules are assumed to have side effects and will be included in the bundle even if none of their exports are used.
  2544. * - **`false`**: No modules have side effects. This enables aggressive tree-shaking, removing any modules whose exports are not used.
  2545. * - **`string[]`**: Array of module IDs that have side effects. Only modules in this list will be preserved if unused; all others can be tree-shaken when their exports are unused.
  2546. * - **`'no-external'`**: Assumes no external modules have side effects while preserving the default behavior for local modules.
  2547. * - **`ModuleSideEffectsRule[]`**: Array of rules with `test`, `external`, and `sideEffects` properties for fine-grained control.
  2548. * - **`function`**: Function that receives `(id, external)` and returns whether the module has side effects.
  2549. *
  2550. * **Important:** Setting this to `false` or using an array/string assumes that your modules and their dependencies have no side effects other than their exports. Only use this if you're certain that removing unused modules won't break your application.
  2551. *
  2552. * > [!NOTE]
  2553. * > **Performance: Prefer `ModuleSideEffectsRule[]` over functions**
  2554. * >
  2555. * > When possible, use rule-based configuration instead of functions. Rules are processed entirely in Rust, while JavaScript functions require runtime calls between Rust and JavaScript, which can hurt CPU utilization during builds.
  2556. * >
  2557. * > **Functions should be a last resort**: Only use the function signature when your logic cannot be expressed with patterns or simple string matching.
  2558. * >
  2559. * > **Rule advantages**: `ModuleSideEffectsRule[]` provides better performance by avoiding Rust-JavaScript runtime calls, clearer intent, and easier maintenance.
  2560. *
  2561. * @example
  2562. * ```js
  2563. * // Assume no modules have side effects (aggressive tree-shaking)
  2564. * treeshake: {
  2565. * moduleSideEffects: false
  2566. * }
  2567. *
  2568. * // Only specific modules have side effects (string array)
  2569. * treeshake: {
  2570. * moduleSideEffects: [
  2571. * 'lodash',
  2572. * 'react-dom',
  2573. * ]
  2574. * }
  2575. *
  2576. * // Use rules for pattern matching and granular control
  2577. * treeshake: {
  2578. * moduleSideEffects: [
  2579. * { test: /^node:/, sideEffects: true },
  2580. * { test: /\.css$/, sideEffects: true },
  2581. * { test: /some-package/, sideEffects: false, external: false },
  2582. * ]
  2583. * }
  2584. *
  2585. * // Custom function to determine side effects
  2586. * treeshake: {
  2587. * moduleSideEffects: (id, external) => {
  2588. * if (external) return false; // external modules have no side effects
  2589. * return id.includes('/side-effects/') || id.endsWith('.css');
  2590. * }
  2591. * }
  2592. *
  2593. * // Assume no external modules have side effects
  2594. * treeshake: {
  2595. * moduleSideEffects: 'no-external',
  2596. * }
  2597. * ```
  2598. *
  2599. * **Common Use Cases:**
  2600. * - **CSS files**: `{ test: /\.css$/, sideEffects: true }` - preserve CSS imports
  2601. * - **Polyfills**: Add specific polyfill modules to the array
  2602. * - **Plugins**: Modules that register themselves globally on import
  2603. * - **Library development**: Set to `false` for libraries where unused exports should be removed
  2604. *
  2605. * @default true
  2606. */
  2607. moduleSideEffects?: ModuleSideEffectsOption;
  2608. /**
  2609. * Whether to respect `/*@__PURE__*\/` annotations and other tree-shaking hints in the code.
  2610. *
  2611. * See [related Oxc documentation](https://oxc.rs/docs/guide/usage/minifier/dead-code-elimination#pure-annotations) for more details.
  2612. *
  2613. * @default true
  2614. */
  2615. annotations?: boolean;
  2616. /**
  2617. * Array of function names that should be considered pure (no side effects) even if they can't be automatically detected as pure.
  2618. *
  2619. * See [related Oxc documentation](https://oxc.rs/docs/guide/usage/minifier/dead-code-elimination#define-pure-functions) for more details.
  2620. *
  2621. * @example
  2622. * ```js
  2623. * treeshake: {
  2624. * manualPureFunctions: ['console.log', 'debug.trace']
  2625. * }
  2626. * ```
  2627. * @default []
  2628. */
  2629. manualPureFunctions?: readonly string[];
  2630. /**
  2631. * Whether to assume that accessing unknown global properties might have side effects.
  2632. *
  2633. * See [related Oxc documentation](https://oxc.rs/docs/guide/usage/minifier/dead-code-elimination#ignoring-global-variable-access-side-effects) for more details.
  2634. *
  2635. * @default true
  2636. */
  2637. unknownGlobalSideEffects?: boolean;
  2638. /**
  2639. * Whether to assume that invalid import statements might have side effects.
  2640. *
  2641. * See [related Oxc documentation](https://oxc.rs/docs/guide/usage/minifier/dead-code-elimination#ignoring-invalid-import-statement-side-effects) for more details.
  2642. *
  2643. * @default false
  2644. */
  2645. invalidImportSideEffects?: boolean;
  2646. /**
  2647. * Whether to enable tree-shaking for CommonJS modules. When `true`, unused exports from CommonJS modules can be eliminated from the bundle, similar to ES modules. When disabled, CommonJS modules will always be included in their entirety.
  2648. *
  2649. * This option allows rolldown to analyze `exports.property` assignments in CommonJS modules and remove unused exports while preserving the module's side effects.
  2650. *
  2651. * @example
  2652. * ```js
  2653. * // source.js (CommonJS)
  2654. * exports.used = 'This will be kept';
  2655. * exports.unused = 'This will be tree-shaken away';
  2656. *
  2657. * // main.js
  2658. * import { used } from './source.js';
  2659. * // With commonjs: true, only the 'used' export is included in the bundle
  2660. * // With commonjs: false, both exports are included
  2661. * ```
  2662. * @default true
  2663. */
  2664. commonjs?: boolean;
  2665. /**
  2666. * Controls whether reading properties from objects is considered to have side effects.
  2667. *
  2668. * Set to `false` for more aggressive tree-shaking behavior.
  2669. *
  2670. * See [related Oxc documentation](https://oxc.rs/docs/guide/usage/minifier/dead-code-elimination#ignoring-property-read-side-effects) for more details.
  2671. *
  2672. * @default 'always'
  2673. */
  2674. propertyReadSideEffects?: false | "always";
  2675. /**
  2676. * Controls whether writing properties to objects is considered to have side effects.
  2677. *
  2678. * Set to `false` for more aggressive behavior.
  2679. *
  2680. * @default 'always'
  2681. */
  2682. propertyWriteSideEffects?: false | "always";
  2683. };
  2684. //#endregion
  2685. //#region src/types/output-bundle.d.ts
  2686. /** @category Plugin APIs */
  2687. interface OutputBundle {
  2688. [fileName: string]: OutputAsset | OutputChunk;
  2689. }
  2690. //#endregion
  2691. //#region src/types/sourcemap.d.ts
  2692. /** @category Plugin APIs */
  2693. interface ExistingRawSourceMap {
  2694. file?: string | null | undefined;
  2695. mappings: string;
  2696. names?: string[] | undefined;
  2697. sources?: (string | null)[] | undefined;
  2698. sourcesContent?: (string | null | undefined)[] | undefined;
  2699. sourceRoot?: string | undefined;
  2700. version?: number | undefined;
  2701. ignoreList?: number[] | undefined;
  2702. x_google_ignoreList?: number[] | undefined;
  2703. }
  2704. /** @inline @category Plugin APIs */
  2705. type SourceMapInput = ExistingRawSourceMap | string | null;
  2706. //#endregion
  2707. //#region src/utils/error.d.ts
  2708. /**
  2709. * The error type that is thrown by Rolldown for the whole build.
  2710. */
  2711. type BundleError = Error & {
  2712. /**
  2713. * The individual errors that happened during the build.
  2714. *
  2715. * This property is a getter to avoid unnecessary expansion of error details when the error is logged.
  2716. */
  2717. errors?: RolldownError[];
  2718. };
  2719. //#endregion
  2720. //#region src/constants/version.d.ts
  2721. /**
  2722. * The version of Rolldown.
  2723. * @example `'1.0.0'`
  2724. *
  2725. * @category Plugin APIs
  2726. */
  2727. declare const VERSION: string;
  2728. //#endregion
  2729. //#region src/constants/index.d.ts
  2730. /**
  2731. * Runtime helper module ID
  2732. */
  2733. declare const RUNTIME_MODULE_ID = "\0rolldown/runtime.js";
  2734. //#endregion
  2735. //#region src/builtin-plugin/utils.d.ts
  2736. declare class BuiltinPlugin {
  2737. name: BindingBuiltinPluginName;
  2738. _options?: unknown | undefined;
  2739. /** Vite-specific option to control plugin ordering */
  2740. enforce?: "pre" | "post";
  2741. constructor(name: BindingBuiltinPluginName, _options?: unknown | undefined);
  2742. }
  2743. //#endregion
  2744. //#region src/constants/plugin.d.ts
  2745. declare const ENUMERATED_INPUT_PLUGIN_HOOK_NAMES: readonly ["options", "buildStart", "resolveId", "load", "transform", "moduleParsed", "buildEnd", "onLog", "resolveDynamicImport", "closeBundle", "closeWatcher", "watchChange"];
  2746. declare const ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES: readonly ["augmentChunkHash", "outputOptions", "renderChunk", "renderStart", "renderError", "writeBundle", "generateBundle", "resolveFileUrl"];
  2747. declare const ENUMERATED_PLUGIN_HOOK_NAMES: [...typeof ENUMERATED_INPUT_PLUGIN_HOOK_NAMES, ...typeof ENUMERATED_OUTPUT_PLUGIN_HOOK_NAMES, "footer", "banner", "intro", "outro"];
  2748. /**
  2749. * Names of all defined hooks. It's like
  2750. * ```ts
  2751. * type DefinedHookNames = {
  2752. * options: 'options',
  2753. * buildStart: 'buildStart',
  2754. * ...
  2755. * }
  2756. * ```
  2757. */
  2758. type DefinedHookNames = { readonly [K in (typeof ENUMERATED_PLUGIN_HOOK_NAMES)[number]]: K; };
  2759. /**
  2760. * Names of all defined hooks. It's like
  2761. * ```js
  2762. * const DEFINED_HOOK_NAMES ={
  2763. * options: 'options',
  2764. * buildStart: 'buildStart',
  2765. * ...
  2766. * }
  2767. * ```
  2768. */
  2769. declare const DEFINED_HOOK_NAMES: DefinedHookNames;
  2770. //#endregion
  2771. //#region src/plugin/with-filter.d.ts
  2772. type OverrideFilterObject = {
  2773. transform?: HookFilterExtension<"transform">["filter"];
  2774. resolveId?: HookFilterExtension<"resolveId">["filter"];
  2775. load?: HookFilterExtension<"load">["filter"];
  2776. pluginNamePattern?: StringOrRegExp[];
  2777. };
  2778. /**
  2779. * A helper function to add plugin hook filters to a plugin or an array of plugins.
  2780. *
  2781. * @example
  2782. * ```ts
  2783. * import yaml from '@rollup/plugin-yaml';
  2784. * import { defineConfig } from 'rolldown';
  2785. * import { withFilter } from 'rolldown/filter';
  2786. *
  2787. * export default defineConfig({
  2788. * plugins: [
  2789. * // Run the transform hook of the `yaml` plugin
  2790. * // only for modules which end in `.yaml`
  2791. * withFilter(
  2792. * yaml({}),
  2793. * { transform: { id: /\.yaml$/ } },
  2794. * ),
  2795. * ],
  2796. * });
  2797. * ```
  2798. *
  2799. * @category Config
  2800. */
  2801. declare function withFilter<A, T extends RolldownPluginOption<A>>(pluginOption: T, filterObject: OverrideFilterObject | OverrideFilterObject[]): T;
  2802. //#endregion
  2803. //#region src/plugin/index.d.ts
  2804. type ModuleSideEffects = boolean | "no-treeshake" | null;
  2805. /** @category Plugin APIs */
  2806. type ModuleType = "js" | "jsx" | "ts" | "tsx" | "json" | "text" | "base64" | "dataurl" | "binary" | "empty" | (string & {});
  2807. /** @category Plugin APIs */
  2808. type ImportKind = BindingHookResolveIdExtraArgs["kind"];
  2809. /**
  2810. * Descriptive metadata a plugin can expose about itself.
  2811. *
  2812. * Set it via the {@linkcode Plugin.meta | meta} property of the plugin object.
  2813. *
  2814. * @category Plugin APIs
  2815. */
  2816. interface PluginMeta {
  2817. /**
  2818. * The name of the npm package the plugin ships in, e.g. `@vitejs/plugin-vue`.
  2819. */
  2820. packageName?: string;
  2821. /**
  2822. * The version of the npm package the plugin ships in, e.g. `5.0.0`. The
  2823. * `version` field of that package's `package.json`.
  2824. */
  2825. version?: string;
  2826. /**
  2827. * A short, human-readable description of what the plugin does.
  2828. */
  2829. description?: string;
  2830. }
  2831. /** @category Plugin APIs */
  2832. interface CustomPluginOptions {
  2833. [plugin: string]: any;
  2834. }
  2835. /** @category Plugin APIs */
  2836. interface ModuleOptions {
  2837. moduleSideEffects: ModuleSideEffects;
  2838. /** See [Custom module meta-data section](https://rolldown.rs/apis/plugin-api/inter-plugin-communication#custom-module-meta-data) for more details. */
  2839. meta: CustomPluginOptions;
  2840. /**
  2841. * A short, human-readable description of the module.
  2842. *
  2843. * This is useful for virtual modules, whose ids (e.g.
  2844. * `\0vite/modulepreload-polyfill.js`) do not convey their purpose on their own.
  2845. *
  2846. * @example
  2847. * ```js
  2848. * function polyfillPlugin() {
  2849. * return {
  2850. * name: 'vite:modulepreload-polyfill',
  2851. * load: {
  2852. * filter: { id: /^\0vite\/modulepreload-polyfill\.js$/ },
  2853. * handler(id) {
  2854. * return {
  2855. * code: '',
  2856. * description: 'A polyfill for `link` tag with `rel="modulepreload"`',
  2857. * };
  2858. * }
  2859. * },
  2860. * };
  2861. * }
  2862. * ```
  2863. */
  2864. description?: string;
  2865. invalidate?: boolean;
  2866. packageJsonPath?: string;
  2867. }
  2868. /** @category Plugin APIs */
  2869. interface ResolvedId extends ModuleOptions {
  2870. external: boolean | "absolute";
  2871. id: string;
  2872. }
  2873. interface SpecifiedModuleOptions {
  2874. /**
  2875. * Indicates whether the module has side effects to Rolldown.
  2876. *
  2877. * - If `false` is set and no other module imports anything from this module, then this module will not be included in the bundle even if the module would have side effects.
  2878. * - If `true` is set, Rolldown will use its default algorithm to include all statements in the module that has side effects.
  2879. * - If `"no-treeshake"` is set, treeshaking will be disabled for this module, and this module will be included in one of the chunks even if it is empty.
  2880. *
  2881. * The precedence of this option is as follows (highest to lowest):
  2882. * 1. {@linkcode Plugin.transform | transform} hook's returned `moduleSideEffects` option
  2883. * 2. {@linkcode Plugin.load | load} hook's returned `moduleSideEffects` option
  2884. * 3. {@linkcode Plugin.resolveId | resolveId} hook's returned `moduleSideEffects` option
  2885. * 4. {@linkcode TreeshakingOptions.moduleSideEffects | treeshake.moduleSideEffects} option
  2886. * 5. `sideEffects` field in the `package.json` file
  2887. * 6. `true` (default)
  2888. */
  2889. moduleSideEffects?: ModuleSideEffects | null;
  2890. }
  2891. /** @category Plugin APIs */
  2892. interface PartialResolvedId extends SpecifiedModuleOptions, Partial<PartialNull<ModuleOptions>> {
  2893. /**
  2894. * Whether this id should be treated as external.
  2895. *
  2896. * Relative external ids, i.e. ids starting with `./` or `../`, will not be internally
  2897. * converted to an absolute id and converted back to a relative id in the output,
  2898. * but are instead included in the output unchanged.
  2899. * If you want relative ids to be re-normalized and deduplicated instead, return
  2900. * an absolute file system location as id and choose `external: "relative"`.
  2901. *
  2902. * - If `true`, absolute ids will be converted to relative ids based on the user's choice for the {@linkcode InputOptions.makeAbsoluteExternalsRelative | makeAbsoluteExternalsRelative} option.
  2903. * - If `'relative'`, absolute ids will always be converted to relative ids.
  2904. * - If `'absolute'`, absolute ids will always be kept as absolute ids.
  2905. */
  2906. external?: boolean | "absolute" | "relative";
  2907. id: string;
  2908. }
  2909. /** @category Plugin APIs */
  2910. interface SourceDescription extends SpecifiedModuleOptions, Partial<PartialNull<ModuleOptions>> {
  2911. code: string;
  2912. /**
  2913. * The source map for the transformation.
  2914. *
  2915. * If the transformation does not move code, you can preserve existing sourcemaps by setting this to `null`.
  2916. *
  2917. * See [Source Code Transformations section](https://rolldown.rs/apis/plugin-api/transformations#source-code-transformations) for more details.
  2918. */
  2919. map?: SourceMapInput;
  2920. moduleType?: ModuleType;
  2921. }
  2922. /**
  2923. * Argument passed to the {@linkcode FunctionPluginHooks.resolveFileUrl | resolveFileUrl} hook.
  2924. *
  2925. * @category Plugin APIs
  2926. */
  2927. interface ResolveFileUrlArgs {
  2928. /**
  2929. * The preliminary filename of the chunk containing the reference with hash placeholders.
  2930. * Similar to {@linkcode RenderedChunk.fileName | chunk.fileName}.
  2931. */
  2932. chunkId: string;
  2933. /** The filename of the emitted file, relative to the output directory. */
  2934. fileName: string;
  2935. /** The rendered output format. */
  2936. format: InternalModuleFormat;
  2937. /**
  2938. * The id of the original module this file was referenced by
  2939. * using the `import.meta.ROLLDOWN_FILE_URL_*` reference.
  2940. */
  2941. moduleId: string;
  2942. /** The reference id of this file. */
  2943. referenceId: string;
  2944. /**
  2945. * The path of the emitted file, relative to the chunk the file is referenced from.
  2946. *
  2947. * This path will contain no leading `./`, but may contain a leading `../`.
  2948. */
  2949. relativePath: string;
  2950. /**
  2951. * The `urlId` of an `import.meta.ROLLDOWN_FILE_URL_<referenceId>_<urlId>` reference,
  2952. * or `undefined` when the reference has no `urlId`.
  2953. *
  2954. * This is a rolldown-specific extension: the Rollup-compatible
  2955. * `import.meta.ROLLUP_FILE_URL_<referenceId>` form never carries a `urlId`.
  2956. *
  2957. * @experimental This API may change in minor versions.
  2958. */
  2959. urlId?: string | undefined;
  2960. }
  2961. /** @inline */
  2962. interface ResolveIdExtraOptions {
  2963. /**
  2964. * Plugin-specific options.
  2965. *
  2966. * See [Custom resolver options section](https://rolldown.rs/apis/plugin-api/inter-plugin-communication#custom-resolver-options) for more details.
  2967. */
  2968. custom?: CustomPluginOptions;
  2969. /**
  2970. * Whether this is resolution for an entry point.
  2971. *
  2972. *
  2973. */
  2974. isEntry: boolean;
  2975. /**
  2976. * The kind of import being resolved.
  2977. *
  2978. * - `import-statement`: `import { foo } from './lib.js';`
  2979. * - `dynamic-import`: `import('./lib.js')`
  2980. * - `require-call`: `require('./lib.js')`
  2981. * - `import-rule`: `@import 'bg-color.css'` (experimental)
  2982. * - `url-token`: `url('./icon.png')` (experimental)
  2983. * - `new-url`: `new URL('./worker.js', import.meta.url)` (experimental)
  2984. * - `hot-accept`: `import.meta.hot.accept('./lib.js', () => {})` (experimental)
  2985. */
  2986. kind: BindingHookResolveIdExtraArgs["kind"];
  2987. }
  2988. /** @inline @category Plugin APIs */
  2989. type ResolveIdResult = string | NullValue | false | PartialResolvedId;
  2990. /** @inline @category Plugin APIs */
  2991. type LoadResult = NullValue | string | SourceDescription;
  2992. /** @inline @category Plugin APIs */
  2993. type TransformResult = NullValue | string | (Omit<SourceDescription, "code"> & {
  2994. code?: string | RolldownMagicString;
  2995. });
  2996. type RenderedChunkMeta = {
  2997. /**
  2998. * Contains information about all chunks that are being rendered.
  2999. * This is useful to explore the entire chunk graph.
  3000. */
  3001. chunks: Record<string, RenderedChunk>;
  3002. /**
  3003. * A lazily-created MagicString instance for the chunk's code.
  3004. * Use this to perform string transformations with automatic source map support.
  3005. * This is only available when `experimental.nativeMagicString` is enabled.
  3006. */
  3007. magicString?: RolldownMagicString;
  3008. };
  3009. /** @category Plugin APIs */
  3010. interface FunctionPluginHooks {
  3011. /**
  3012. * A function that receives and filters logs and warnings generated by Rolldown and
  3013. * plugins before they are passed to the {@linkcode InputOptions.onLog | onLog} option
  3014. * or printed to the console.
  3015. *
  3016. * If `false` is returned, the log will be filtered out.
  3017. * Otherwise, the log will be handed to the `onLog` hook of the next plugin,
  3018. * the {@linkcode InputOptions.onLog | onLog} option, or printed to the console.
  3019. * Plugins can also change the log level of a log or turn a log into an error by passing
  3020. * the `log` object to {@linkcode MinimalPluginContext.error | this.error},
  3021. * {@linkcode MinimalPluginContext.warn | this.warn},
  3022. * {@linkcode MinimalPluginContext.info | this.info} or
  3023. * {@linkcode MinimalPluginContext.debug | this.debug} and returning `false`.
  3024. *
  3025. *
  3026. *
  3027. * @kind sync sequential
  3028. * @group Build Hooks
  3029. */
  3030. [DEFINED_HOOK_NAMES.onLog]: (this: MinimalPluginContext, level: LogLevel, log: RolldownLog) => NullValue | boolean;
  3031. /**
  3032. * Replaces or manipulates the options object passed to {@linkcode rolldown | rolldown()}.
  3033. *
  3034. * Returning `null` does not replace anything.
  3035. *
  3036. * If you just need to read the options, it is recommended to use
  3037. * the {@linkcode buildStart} hook as that hook has access to the options
  3038. * after the transformations from all `options` hooks have been taken into account.
  3039. *
  3040. * @kind async sequential
  3041. * @group Build Hooks
  3042. */
  3043. [DEFINED_HOOK_NAMES.options]: (this: MinimalPluginContext, options: InputOptions) => NullValue | InputOptions;
  3044. /**
  3045. * Replaces or manipulates the output options object passed to
  3046. * {@linkcode RolldownBuild.generate | bundle.generate()} or
  3047. * {@linkcode RolldownBuild.write | bundle.write()}.
  3048. *
  3049. * Returning null does not replace anything.
  3050. *
  3051. * If you just need to read the output options, it is recommended to use
  3052. * the {@linkcode renderStart} hook as this hook has access to the output options
  3053. * after the transformations from all `outputOptions` hooks have been taken into account.
  3054. *
  3055. * @kind sync sequential
  3056. * @group Build Hooks
  3057. */
  3058. [DEFINED_HOOK_NAMES.outputOptions]: (this: MinimalPluginContext, options: OutputOptions) => NullValue | OutputOptions;
  3059. /**
  3060. * Called on each {@linkcode rolldown | rolldown()} build.
  3061. *
  3062. * This is the recommended hook to use when you need access to the options passed to {@linkcode rolldown | rolldown()} as it takes the transformations by all options hooks into account and also contains the right default values for unset options.
  3063. *
  3064. * @kind async parallel
  3065. * @group Build Hooks
  3066. */
  3067. [DEFINED_HOOK_NAMES.buildStart]: (this: PluginContext, options: NormalizedInputOptions) => void;
  3068. /**
  3069. * Defines a custom resolver.
  3070. *
  3071. * A resolver can be useful for e.g. locating third-party dependencies.
  3072. *
  3073. * Returning `null` defers to other `resolveId` hooks and eventually the default resolution behavior.
  3074. * Returning `false` signals that `source` should be treated as an external module and not included in the bundle. If this happens for a relative import, the id will be renormalized the same way as when the {@linkcode InputOptions.external} option is used.
  3075. * If you return an object, then it is possible to resolve an import to a different id while excluding it from the bundle at the same time.
  3076. *
  3077. * Note that while `resolveId` will be called for each import of a module and can therefore
  3078. * resolve to the same `id` many times, values for `external`, `meta` or `moduleSideEffects`
  3079. * can only be set once before the module is loaded. The reason is that after this call,
  3080. * Rolldown will continue with the {@linkcode load} and {@linkcode transform} hooks for that
  3081. * module that may override these values and should take precedence if they do so.
  3082. *
  3083. * @kind async first
  3084. * @group Build Hooks
  3085. */
  3086. [DEFINED_HOOK_NAMES.resolveId]: (this: PluginContext, source: string, importer: string | undefined, extraOptions: ResolveIdExtraOptions) => ResolveIdResult;
  3087. /**
  3088. * Defines a custom resolver for dynamic imports.
  3089. *
  3090. * @deprecated
  3091. * This hook exists only for Rollup compatibility. Please use {@linkcode resolveId} instead.
  3092. *
  3093. * @kind async first
  3094. * @group Build Hooks
  3095. */
  3096. [DEFINED_HOOK_NAMES.resolveDynamicImport]: (this: PluginContext, source: string, importer: string | undefined) => ResolveIdResult;
  3097. /**
  3098. * Defines a custom loader.
  3099. *
  3100. * Returning `null` defers to other `load` hooks or the built-in loading mechanism.
  3101. *
  3102. * You can use {@linkcode PluginContext.getModuleInfo | this.getModuleInfo()} to find out the previous values of `meta`, `moduleSideEffects` inside this hook.
  3103. *
  3104. * @kind async first
  3105. * @group Build Hooks
  3106. */
  3107. [DEFINED_HOOK_NAMES.load]: (this: PluginContext, id: string) => MaybePromise<LoadResult>;
  3108. /**
  3109. * Can be used to transform individual modules.
  3110. *
  3111. * Note that it's possible to return only properties and no code transformations.
  3112. *
  3113. * You can use {@linkcode PluginContext.getModuleInfo | this.getModuleInfo()} to find out the previous values of `meta`, `moduleSideEffects` inside this hook.
  3114. *
  3115. *
  3116. *
  3117. * @kind async sequential
  3118. * @group Build Hooks
  3119. */
  3120. [DEFINED_HOOK_NAMES.transform]: (this: TransformPluginContext, code: string, id: string, meta: BindingTransformHookExtraArgs & {
  3121. moduleType: ModuleType;
  3122. magicString?: RolldownMagicString;
  3123. ast?: Program;
  3124. }) => TransformResult;
  3125. /**
  3126. * This hook is called each time a module has been fully parsed by Rolldown.
  3127. *
  3128. * This hook will wait until all imports are resolved so that the information in
  3129. * {@linkcode ModuleInfo.importedIds | moduleInfo.importedIds},
  3130. * {@linkcode ModuleInfo.dynamicallyImportedIds | moduleInfo.dynamicallyImportedIds}
  3131. * are complete and accurate. Note however that information about importing modules
  3132. * may be incomplete as additional importers could be discovered later.
  3133. * If you need this information, use the {@linkcode buildEnd} hook.
  3134. *
  3135. * @kind async parallel
  3136. * @group Build Hooks
  3137. */
  3138. [DEFINED_HOOK_NAMES.moduleParsed]: (this: PluginContext, moduleInfo: ModuleInfo) => void;
  3139. /**
  3140. * Called when Rolldown has finished bundling, but before Output Generation Hooks.
  3141. * If an error occurred during the build, it is passed on to this hook.
  3142. *
  3143. * @kind async parallel
  3144. * @group Build Hooks
  3145. */
  3146. [DEFINED_HOOK_NAMES.buildEnd]: (this: PluginContext, err?: Error) => void;
  3147. /**
  3148. * Called initially each time {@linkcode RolldownBuild.generate | bundle.generate()} or
  3149. * {@linkcode RolldownBuild.write | bundle.write()} is called.
  3150. *
  3151. * To get notified when generation has completed, use the {@linkcode generateBundle} and
  3152. * {@linkcode renderError} hooks.
  3153. *
  3154. * This is the recommended hook to use when you need access to the output options passed to
  3155. * {@linkcode RolldownBuild.generate | bundle.generate()} or
  3156. * {@linkcode RolldownBuild.write | bundle.write()} as it takes the transformations by all outputOptions hooks into account and also contains the right default values for unset options.
  3157. *
  3158. * It also receives the input options passed to {@linkcode rolldown | rolldown()} so that
  3159. * plugins that can be used as output plugins, i.e. plugins that only use generate phase hooks,
  3160. * can get access to them.
  3161. *
  3162. * @kind async parallel
  3163. * @group Output Generation Hooks
  3164. */
  3165. [DEFINED_HOOK_NAMES.renderStart]: (this: PluginContext, outputOptions: NormalizedOutputOptions, inputOptions: NormalizedInputOptions) => void;
  3166. /**
  3167. * Can be used to transform individual chunks. Called for each Rolldown output chunk file.
  3168. *
  3169. * Returning null will apply no transformations. If you change code in this hook and want to support source maps, you need to return a map describing your changes, see [Source Code Transformations section](https://rolldown.rs/apis/plugin-api/transformations#source-code-transformations).
  3170. *
  3171. * `chunk` is mutable and changes applied in this hook will propagate to other plugins and
  3172. * to the generated bundle.
  3173. * That means if you add or remove imports or exports in this hook, you should update
  3174. * {@linkcode RenderedChunk.imports | imports}, {@linkcode RenderedChunk.importedBindings | importedBindings} and/or {@linkcode RenderedChunk.exports | exports} accordingly.
  3175. *
  3176. * @kind async sequential
  3177. * @group Output Generation Hooks
  3178. */
  3179. [DEFINED_HOOK_NAMES.renderChunk]: (this: PluginContext, code: string, chunk: RenderedChunk, outputOptions: NormalizedOutputOptions, meta: RenderedChunkMeta) => NullValue | string | RolldownMagicString | {
  3180. code: string | RolldownMagicString;
  3181. map?: SourceMapInput;
  3182. };
  3183. /**
  3184. * Can be used to augment the hash of individual chunks. Called for each Rolldown output chunk.
  3185. *
  3186. * Returning a falsy value will not modify the hash.
  3187. * Truthy values will be used as an additional source for hash calculation.
  3188. *
  3189. *
  3190. *
  3191. * @kind sync sequential
  3192. * @group Output Generation Hooks
  3193. */
  3194. [DEFINED_HOOK_NAMES.augmentChunkHash]: (this: PluginContext, chunk: RenderedChunk) => string | void;
  3195. /**
  3196. *
  3197. *
  3198. * @group Output Generation Hooks
  3199. */
  3200. [DEFINED_HOOK_NAMES.resolveFileUrl]: (this: PluginContext, args: ResolveFileUrlArgs) => string | NullValue;
  3201. /**
  3202. * Called when Rolldown encounters an error during
  3203. * {@linkcode RolldownBuild.generate | bundle.generate()} or
  3204. * {@linkcode RolldownBuild.write | bundle.write()}.
  3205. *
  3206. * To get notified when generation completes successfully, use the
  3207. * {@linkcode generateBundle} hook.
  3208. *
  3209. * @kind async parallel
  3210. * @group Output Generation Hooks
  3211. */
  3212. [DEFINED_HOOK_NAMES.renderError]: (this: PluginContext, error: Error) => void;
  3213. /**
  3214. * Called at the end of {@linkcode RolldownBuild.generate | bundle.generate()} or
  3215. * immediately before the files are written in
  3216. * {@linkcode RolldownBuild.write | bundle.write()}.
  3217. *
  3218. * To modify the files after they have been written, use the {@linkcode writeBundle} hook.
  3219. *
  3220. *
  3221. *
  3222. * @kind async sequential
  3223. * @group Output Generation Hooks
  3224. */
  3225. [DEFINED_HOOK_NAMES.generateBundle]: (this: PluginContext, outputOptions: NormalizedOutputOptions, bundle: OutputBundle, isWrite: boolean) => void;
  3226. /**
  3227. * Called only at the end of {@linkcode RolldownBuild.write | bundle.write()} once
  3228. * all files have been written.
  3229. *
  3230. * @kind async parallel
  3231. * @group Output Generation Hooks
  3232. */
  3233. [DEFINED_HOOK_NAMES.writeBundle]: (this: PluginContext, outputOptions: NormalizedOutputOptions, bundle: OutputBundle) => void;
  3234. /**
  3235. * Can be used to clean up any external service that may be running.
  3236. *
  3237. * Rolldown's CLI will make sure this hook is called after each run, but it is the responsibility
  3238. * of users of the JavaScript API to manually call
  3239. * {@linkcode RolldownBuild.close | bundle.close()} once they are done generating bundles.
  3240. * For that reason, any plugin relying on this feature should carefully mention this in
  3241. * its documentation.
  3242. *
  3243. * If a plugin wants to retain resources across builds in watch mode, they can check for
  3244. * {@linkcode PluginContextMeta.watchMode | this.meta.watchMode} in this hook and perform
  3245. * the necessary cleanup for watch mode in closeWatcher.
  3246. *
  3247. * @kind async parallel
  3248. * @group Output Generation Hooks
  3249. */
  3250. [DEFINED_HOOK_NAMES.closeBundle]: (this: PluginContext, error?: Error) => void;
  3251. /**
  3252. * Notifies a plugin whenever Rolldown has detected a change to a monitored file in watch mode.
  3253. *
  3254. * If a build is currently running, this hook is called once the build finished.
  3255. * It will be called once for every file that changed.
  3256. *
  3257. * This hook cannot be used by output plugins.
  3258. *
  3259. * If you need to be notified immediately when a file changed, you can use the {@linkcode WatcherOptions.onInvalidate | watch.onInvalidate} option.
  3260. *
  3261. * @kind async parallel
  3262. * @group Build Hooks
  3263. */
  3264. [DEFINED_HOOK_NAMES.watchChange]: (this: PluginContext, id: string, event: {
  3265. event: ChangeEvent;
  3266. }) => void;
  3267. /**
  3268. * Notifies a plugin when the watcher process will close so that all open resources can be closed too.
  3269. *
  3270. * This hook cannot be used by output plugins.
  3271. *
  3272. * @kind async parallel
  3273. * @group Build Hooks
  3274. */
  3275. [DEFINED_HOOK_NAMES.closeWatcher]: (this: PluginContext) => void;
  3276. }
  3277. type ChangeEvent = "create" | "update" | "delete";
  3278. type PluginOrder = "pre" | "post" | null;
  3279. /** @inline */
  3280. type ObjectHookMeta = {
  3281. order?: PluginOrder;
  3282. };
  3283. /**
  3284. * A hook in a function or an object form with additional properties.
  3285. *
  3286. * @typeParam T - The type of the hook function.
  3287. * @typeParam O - Additional properties that are specific to some hooks.
  3288. *
  3289. *
  3290. *
  3291. * @category Plugin APIs
  3292. */
  3293. type ObjectHook<T, O = {}> = T | ({
  3294. handler: T;
  3295. } & ObjectHookMeta & O);
  3296. type SyncPluginHooks = DefinedHookNames["augmentChunkHash" | "onLog" | "outputOptions" | "resolveFileUrl"];
  3297. /** @category Plugin APIs */
  3298. type AsyncPluginHooks = Exclude<keyof FunctionPluginHooks, SyncPluginHooks>;
  3299. type FirstPluginHooks = DefinedHookNames["load" | "resolveDynamicImport" | "resolveFileUrl" | "resolveId"];
  3300. type SequentialPluginHooks = DefinedHookNames["augmentChunkHash" | "generateBundle" | "onLog" | "options" | "outputOptions" | "renderChunk" | "transform"];
  3301. interface AddonHooks {
  3302. /**
  3303. * A hook equivalent to {@linkcode OutputOptions.banner | output.banner} option.
  3304. *
  3305. * @kind async sequential
  3306. * @group Output Generation Hooks
  3307. */
  3308. [DEFINED_HOOK_NAMES.banner]: AddonHook;
  3309. /**
  3310. * A hook equivalent to {@linkcode OutputOptions.footer | output.footer} option.
  3311. *
  3312. * @kind async sequential
  3313. * @group Output Generation Hooks
  3314. */
  3315. [DEFINED_HOOK_NAMES.footer]: AddonHook;
  3316. /**
  3317. * A hook equivalent to {@linkcode OutputOptions.intro | output.intro} option.
  3318. *
  3319. * @kind async sequential
  3320. * @group Output Generation Hooks
  3321. */
  3322. [DEFINED_HOOK_NAMES.intro]: AddonHook;
  3323. /**
  3324. * A hook equivalent to {@linkcode OutputOptions.outro | output.outro} option.
  3325. *
  3326. * @kind async sequential
  3327. * @group Output Generation Hooks
  3328. */
  3329. [DEFINED_HOOK_NAMES.outro]: AddonHook;
  3330. }
  3331. type OutputPluginHooks = DefinedHookNames["augmentChunkHash" | "generateBundle" | "outputOptions" | "renderChunk" | "renderError" | "renderStart" | "resolveFileUrl" | "writeBundle"];
  3332. /** @internal */
  3333. type ParallelPluginHooks = Exclude<keyof FunctionPluginHooks | keyof AddonHooks, FirstPluginHooks | SequentialPluginHooks>;
  3334. /** @category Plugin APIs */
  3335. type HookFilterExtension<K extends keyof FunctionPluginHooks> = K extends "transform" ? {
  3336. filter?: HookFilter | TopLevelFilterExpression[];
  3337. } : K extends "load" ? {
  3338. filter?: Pick<HookFilter, "id"> | TopLevelFilterExpression[];
  3339. } : K extends "resolveId" ? {
  3340. filter?: {
  3341. id?: GeneralHookFilter<RegExp>;
  3342. } | TopLevelFilterExpression[];
  3343. } : K extends "renderChunk" ? {
  3344. filter?: Pick<HookFilter, "code"> | TopLevelFilterExpression[];
  3345. } : {};
  3346. type PluginHooks = { [K in keyof FunctionPluginHooks]: ObjectHook<K extends AsyncPluginHooks ? MakeAsync<FunctionPluginHooks[K]> : FunctionPluginHooks[K], HookFilterExtension<K> & (K extends ParallelPluginHooks ? {
  3347. /**
  3348. * @deprecated
  3349. * this is only for rollup Plugin type compatibility.
  3350. * hooks always work as `sequential: true`.
  3351. */
  3352. sequential?: boolean;
  3353. } : {})>; };
  3354. type AddonHookFunction = (this: PluginContext, chunk: RenderedChunk) => string | Promise<string>;
  3355. type AddonHook = string | AddonHookFunction;
  3356. interface OutputPlugin extends Partial<{ [K in keyof PluginHooks as K & OutputPluginHooks]: PluginHooks[K]; }>, Partial<{ [K in keyof AddonHooks]: ObjectHook<AddonHook>; }> {
  3357. /** The name of the plugin, for use in error messages and logs. */
  3358. name: string;
  3359. /** The version of the plugin, for use in inter-plugin communication scenarios. */
  3360. version?: string;
  3361. /**
  3362. * Descriptive metadata about the plugin, such as the npm package it ships in.
  3363. *
  3364. * This does not affect bundling; it is informational and intended to be
  3365. * surfaced by tooling that inspects a build. See {@linkcode PluginMeta}.
  3366. *
  3367. * @experimental
  3368. */
  3369. meta?: PluginMeta;
  3370. }
  3371. /**
  3372. * The Plugin interface.
  3373. *
  3374. * See [Plugin API document](https://rolldown.rs/apis/plugin-api) for details.
  3375. *
  3376. * @typeParam A - The type of the {@link Plugin.api | api} property.
  3377. *
  3378. * @category Plugin APIs
  3379. */
  3380. interface Plugin<A = any> extends OutputPlugin, Partial<PluginHooks> {
  3381. /**
  3382. * Used for inter-plugin communication.
  3383. */
  3384. api?: A;
  3385. }
  3386. type RolldownPlugin<A = any> = Plugin<A> | BuiltinPlugin | ParallelPlugin;
  3387. type RolldownPluginOption<A = any> = MaybePromise<NullValue<RolldownPlugin<A>> | {
  3388. name: string;
  3389. } | false | RolldownPluginOption[]>;
  3390. type RolldownOutputPlugin = OutputPlugin | BuiltinPlugin;
  3391. type RolldownOutputPluginOption = MaybePromise<NullValue<RolldownOutputPlugin> | {
  3392. name: string;
  3393. } | false | RolldownOutputPluginOption[]>;
  3394. //#endregion
  3395. //#region src/options/input-options.d.ts
  3396. /**
  3397. * @inline
  3398. */
  3399. type InputOption = string | string[] | Record<string, string>;
  3400. /**
  3401. * @param id The id of the module being checked.
  3402. * @param parentId The id of the module importing the id being checked.
  3403. * @param isResolved Whether the id has been resolved.
  3404. * @returns Whether the module should be treated as external.
  3405. */
  3406. type ExternalOptionFunction = (id: string, parentId: string | undefined, isResolved: boolean) => NullValue<boolean>;
  3407. /** @inline */
  3408. type ExternalOption = StringOrRegExp | StringOrRegExp[] | ExternalOptionFunction;
  3409. interface ChunkOptimizationOptions {
  3410. /**
  3411. * Merge common chunks into existing entry chunks when it is safe.
  3412. *
  3413. * This can reduce the number of emitted chunks by moving shared/common modules
  3414. * into an entry chunk that already depends on them. Rolldown only applies the
  3415. * merge when it does not create a circular chunk dependency or change strict
  3416. * entry export signatures. This pass also covers safe empty-facade cleanup.
  3417. *
  3418. * @default true
  3419. */
  3420. mergeCommonChunks?: boolean;
  3421. /**
  3422. * Avoid emitting redundant chunk loads for dynamic entries.
  3423. *
  3424. * This pass can reduce dynamic-entry dependent chunks when the shared modules
  3425. * are guaranteed to be loaded by every importer of that dynamic entry.
  3426. *
  3427. * @default true
  3428. */
  3429. avoidRedundantChunkLoads?: boolean;
  3430. }
  3431. type ModuleTypes = Record<string, "js" | "jsx" | "ts" | "tsx" | "json" | "text" | "base64" | "dataurl" | "binary" | "empty" | "css" | "asset" | "copy">;
  3432. interface WatcherFileWatcherOptions {
  3433. /**
  3434. * Whether to use polling-based file watching instead of native OS events.
  3435. *
  3436. * Polling is useful for environments where native FS events are unreliable,
  3437. * such as network mounts, Docker volumes, or WSL2.
  3438. *
  3439. * @default false
  3440. */
  3441. usePolling?: boolean;
  3442. /**
  3443. * Interval between each poll in milliseconds.
  3444. *
  3445. * This option is only used when {@linkcode usePolling} is `true`.
  3446. *
  3447. * @default 100
  3448. */
  3449. pollInterval?: number;
  3450. /**
  3451. * Whether to compare file contents for poll-based watchers.
  3452. * When enabled, poll watchers will check file contents to determine if they actually changed.
  3453. *
  3454. * This option is only used when {@linkcode usePolling} is `true`.
  3455. *
  3456. * @default false
  3457. */
  3458. compareContentsForPolling?: boolean;
  3459. /**
  3460. * Whether to use debounced event delivery at the filesystem level.
  3461. * This coalesces rapid filesystem events before they reach the build coordinator.
  3462. * @default false
  3463. */
  3464. useDebounce?: boolean;
  3465. /**
  3466. * Debounce delay in milliseconds for fs-level debounced watchers.
  3467. * Only used when {@linkcode useDebounce} is `true`.
  3468. * @default 10
  3469. */
  3470. debounceDelay?: number;
  3471. /**
  3472. * Tick rate in milliseconds for the debouncer's internal polling.
  3473. * Only used when {@linkcode useDebounce} is `true`.
  3474. * When undefined, auto-selects 1/4 of debounceDelay.
  3475. */
  3476. debounceTickRate?: number;
  3477. }
  3478. interface WatcherOptions {
  3479. /**
  3480. * Whether to skip the {@linkcode RolldownBuild.write | bundle.write()} step when a rebuild is triggered.
  3481. * @default false
  3482. */
  3483. skipWrite?: boolean;
  3484. /**
  3485. * Configures how long Rolldown will wait for further changes until it triggers
  3486. * a rebuild in milliseconds.
  3487. *
  3488. * Even if this value is set to 0, there's a small debounce timeout configured
  3489. * in the file system watcher. Setting this to a value greater than 0 will mean
  3490. * that Rolldown will only trigger a rebuild if there was no change for the
  3491. * configured number of milliseconds. If several configurations are watched,
  3492. * Rolldown will use the largest configured build delay.
  3493. *
  3494. * This option is useful if you use a tool that regenerates multiple source files
  3495. * very slowly. Rebuilding immediately after the first change could cause Rolldown
  3496. * to generate a broken intermediate build before generating a successful final
  3497. * build, which can be confusing and distracting.
  3498. *
  3499. * @default 0
  3500. */
  3501. buildDelay?: number;
  3502. /**
  3503. * File watcher options for configuring how file changes are detected.
  3504. */
  3505. watcher?: WatcherFileWatcherOptions;
  3506. /**
  3507. * Filter to limit the file-watching to certain files.
  3508. *
  3509. * Strings are treated as glob patterns.
  3510. * Note that this only filters the module graph but does not allow adding
  3511. * additional watch files.
  3512. *
  3513. * @example
  3514. * ```js
  3515. * export default defineConfig({
  3516. * watch: {
  3517. * include: 'src/**',
  3518. * },
  3519. * })
  3520. * ```
  3521. * @default []
  3522. */
  3523. include?: StringOrRegExp | StringOrRegExp[];
  3524. /**
  3525. * Filter to prevent files from being watched.
  3526. *
  3527. * Strings are treated as glob patterns.
  3528. *
  3529. * @example
  3530. * ```js
  3531. * export default defineConfig({
  3532. * watch: {
  3533. * exclude: 'node_modules/**',
  3534. * },
  3535. * })
  3536. * ```
  3537. * @default []
  3538. */
  3539. exclude?: StringOrRegExp | StringOrRegExp[];
  3540. /**
  3541. * An optional function that will be called immediately every time
  3542. * a module changes that is part of the build.
  3543. *
  3544. * This is different from the {@linkcode Plugin.watchChange | watchChange} plugin hook, which is
  3545. * only called once the running build has finished. This may for
  3546. * instance be used to prevent additional steps from being performed
  3547. * if we know another build will be started anyway once the current
  3548. * build finished. This callback may be called multiple times per
  3549. * build as it tracks every change.
  3550. *
  3551. * @param id The id of the changed module.
  3552. */
  3553. onInvalidate?: (id: string) => void;
  3554. /**
  3555. * Whether to clear the screen when a rebuild is triggered.
  3556. * @default true
  3557. */
  3558. clearScreen?: boolean;
  3559. }
  3560. /** @inline */
  3561. type MakeAbsoluteExternalsRelative = boolean | "ifRelativeSource";
  3562. type DevModeOptions = boolean | {
  3563. host?: string;
  3564. port?: number;
  3565. implement?: string;
  3566. /**
  3567. * Prevent Rolldown from prepending its common dev runtime to {@link implement}.
  3568. * @deprecated Common runtime injection will be disabled by default in the future.
  3569. * Include the common runtime in {@link implement} instead.
  3570. * @default false
  3571. */
  3572. skipCommonRuntimeInjection?: boolean;
  3573. lazy?: boolean;
  3574. };
  3575. type OptimizationOptions = {
  3576. /**
  3577. * Inline imported constant values during bundling instead of preserving variable references.
  3578. *
  3579. * When enabled, constant values from imported modules will be inlined at their usage sites,
  3580. * potentially reducing bundle size and improving runtime performance by eliminating variable lookups.
  3581. *
  3582. * **Options:**
  3583. * - `true`: equivalent to `{ mode: 'all', pass: 1 }`, enabling constant inlining for all eligible constants with a single pass.
  3584. * - `false`: Disable constant inlining
  3585. * - `{ mode: 'smart' | 'all', pass?: number }`:
  3586. * - `mode: 'smart'`: Only inline constants in specific scenarios where it is likely to reduce bundle size and improve performance.
  3587. * Smart mode inlines constants in these specific scenarios:
  3588. * 1. `if (test) {} else {}` - condition expressions in if statements
  3589. * 2. `test ? a : b` - condition expressions in ternary operators
  3590. * 3. `test1 || test2` - logical OR expressions
  3591. * 4. `test1 && test2` - logical AND expressions
  3592. * 5. `test1 ?? test2` - nullish coalescing expressions
  3593. * - `mode: 'all'`: Inline all imported constants wherever they are used.
  3594. * - `pass`: Number of passes to perform for inlining constants.
  3595. *
  3596. * @example
  3597. * ```js
  3598. * // Input files:
  3599. * // constants.js
  3600. * export const API_URL = 'https://api.example.com';
  3601. *
  3602. * // main.js
  3603. * import { API_URL } from './constants.js';
  3604. * console.log(API_URL);
  3605. *
  3606. * // With inlineConst: true, the bundled output becomes:
  3607. * console.log('https://api.example.com');
  3608. *
  3609. * // Instead of:
  3610. * const API_URL = 'https://api.example.com';
  3611. * console.log(API_URL);
  3612. * ```
  3613. *
  3614. * @default { mode: 'smart', pass: 1 }
  3615. */
  3616. inlineConst?: boolean | {
  3617. mode?: "all" | "smart";
  3618. pass?: number;
  3619. };
  3620. /**
  3621. * Use PIFE pattern for module wrappers.
  3622. *
  3623. * Enabling this option improves the start up performance of the generated bundle with the cost of a slight increase in bundle size.
  3624. *
  3625. *
  3626. *
  3627. * @default true
  3628. */
  3629. pifeForModuleWrappers?: boolean;
  3630. };
  3631. /** @inline */
  3632. type AttachDebugOptions = "none" | "simple" | "full";
  3633. /** @inline */
  3634. type ChunkModulesOrder = "exec-order" | "module-id";
  3635. /** @inline */
  3636. type OnLogFunction = (level: LogLevel, log: RolldownLog, defaultHandler: LogOrStringHandler) => void;
  3637. /** @inline */
  3638. type OnwarnFunction = (warning: RolldownLog, defaultHandler: (warning: RolldownLogWithString | (() => RolldownLogWithString)) => void) => void;
  3639. interface InputOptions {
  3640. /**
  3641. * Defines entries and location(s) of entry modules for the bundle. Relative paths are resolved based on the {@linkcode cwd} option.
  3642. *
  3643. */
  3644. input?: InputOption;
  3645. /**
  3646. * The list of plugins to use.
  3647. *
  3648. * Falsy plugins will be ignored, which can be used to easily activate or deactivate plugins. Nested plugins will be flattened. Async plugins will be awaited and resolved.
  3649. *
  3650. * See [Plugin API document](https://rolldown.rs/apis/plugin-api) for more details about creating plugins.
  3651. *
  3652. * @example
  3653. * ```js
  3654. * import { defineConfig } from 'rolldown'
  3655. *
  3656. * export default defineConfig({
  3657. * plugins: [
  3658. * examplePlugin1(),
  3659. * // Conditional plugins
  3660. * process.env.ENV1 && examplePlugin2(),
  3661. * // Nested plugins arrays are flattened
  3662. * [examplePlugin3(), examplePlugin4()],
  3663. * ]
  3664. * })
  3665. * ```
  3666. */
  3667. plugins?: RolldownPluginOption;
  3668. /**
  3669. * Specifies which modules should be treated as external and not bundled. External modules will be left as import statements in the output.
  3670. *
  3671. */
  3672. external?: ExternalOption;
  3673. /**
  3674. * Options for built-in module resolution feature.
  3675. */
  3676. resolve?: {
  3677. /**
  3678. * Substitute one package for another.
  3679. *
  3680. * One use case for this feature is replacing a node-only package with a browser-friendly package in third-party code that you don't control.
  3681. *
  3682. * @example
  3683. * ```js
  3684. * resolve: {
  3685. * alias: {
  3686. * '@': '/src',
  3687. * 'utils': './src/utils',
  3688. * }
  3689. * }
  3690. * ```
  3691. * > [!WARNING]
  3692. * > `resolve.alias` will not call [`resolveId`](/reference/Interface.Plugin#resolveid) hooks of other plugin.
  3693. * > If you want to call `resolveId` hooks of other plugin, use `viteAliasPlugin` from `rolldown/experimental` instead.
  3694. * > You could find more discussion in [this issue](https://github.com/rolldown/rolldown/issues/3615)
  3695. */
  3696. alias?: Record<string, string[] | string | false>;
  3697. /**
  3698. * Fields in package.json to check for aliased paths.
  3699. *
  3700. * This option is expected to be used for `browser` field support.
  3701. *
  3702. * @default
  3703. * - `[['browser']]` for `browser` platform
  3704. * - `[]` for other platforms
  3705. */
  3706. aliasFields?: string[][];
  3707. /**
  3708. * Condition names to use when resolving exports in package.json.
  3709. *
  3710. * @default
  3711. * Defaults based on platform and import kind:
  3712. * - `browser` platform
  3713. * - `["import", "browser", "default"]` for import statements
  3714. * - `["require", "browser", "default"]` for require() calls
  3715. * - `node` platform
  3716. * - `["import", "node", "default"]` for import statements
  3717. * - `["require", "node", "default"]` for require() calls
  3718. * - `neutral` platform
  3719. * - `["import", "default"]` for import statements
  3720. * - `["require", "default"]` for require() calls
  3721. */
  3722. conditionNames?: string[];
  3723. /**
  3724. * Map of extensions to alternative extensions.
  3725. *
  3726. * With writing `import './foo.js'` in a file, you want to resolve it to `foo.ts` instead of `foo.js`.
  3727. * You can achieve this by setting: `extensionAlias: { '.js': ['.ts', '.js'] }`.
  3728. */
  3729. extensionAlias?: Record<string, string[]>;
  3730. /**
  3731. * Fields in package.json to check for exports.
  3732. *
  3733. * @default `[['exports']]`
  3734. */
  3735. exportsFields?: string[][];
  3736. /**
  3737. * Extensions to try when resolving files. These are tried in order from first to last.
  3738. *
  3739. * @default `['.tsx', '.ts', '.jsx', '.js', '.json']`
  3740. */
  3741. extensions?: string[];
  3742. /**
  3743. * Fields in package.json to check for entry points.
  3744. *
  3745. * @default
  3746. * Defaults based on platform:
  3747. * - `node` platform: `['main', 'module']`
  3748. * - `browser` platform: `['browser', 'module', 'main']`
  3749. * - `neutral` platform: `[]`
  3750. */
  3751. mainFields?: string[];
  3752. /**
  3753. * Filenames to try when resolving directories.
  3754. * @default ['index']
  3755. */
  3756. mainFiles?: string[];
  3757. /**
  3758. * Directories to search for modules.
  3759. * @default ['node_modules']
  3760. */
  3761. modules?: string[];
  3762. /**
  3763. * Whether to follow symlinks when resolving modules.
  3764. * @default true
  3765. */
  3766. symlinks?: boolean;
  3767. /**
  3768. * @deprecated Use the top-level {@linkcode tsconfig} option instead.
  3769. */
  3770. tsconfigFilename?: string;
  3771. };
  3772. /**
  3773. * The working directory to use when resolving relative paths in the configuration.
  3774. * @default process.cwd()
  3775. */
  3776. cwd?: string;
  3777. /**
  3778. * Expected platform where the code run.
  3779. *
  3780. * When the platform is set to neutral:
  3781. * - When bundling is enabled the default output format is set to esm, which uses the export syntax introduced with ECMAScript 2015 (i.e. ES6). You can change the output format if this default is not appropriate.
  3782. * - The main fields setting is empty by default. If you want to use npm-style packages, you will likely have to configure this to be something else such as main for the standard main field used by node.
  3783. * - The conditions setting does not automatically include any platform-specific values.
  3784. *
  3785. * @default
  3786. * - `'node'` if the format is `'cjs'`
  3787. * - `'browser'` for other formats
  3788. *
  3789. */
  3790. platform?: "node" | "browser" | "neutral";
  3791. /**
  3792. * When `true`, creates shim variables for missing exports instead of throwing an error.
  3793. * @default false
  3794. *
  3795. */
  3796. shimMissingExports?: boolean;
  3797. /**
  3798. * Controls tree-shaking (dead code elimination).
  3799. *
  3800. * See the [In-depth Dead Code Elimination Guide](https://rolldown.rs/in-depth/dead-code-elimination) for more details.
  3801. *
  3802. * When `false`, tree-shaking will be disabled.
  3803. * When `true`, it is equivalent to setting each options to the default value.
  3804. *
  3805. * @default true
  3806. */
  3807. treeshake?: boolean | TreeshakingOptions;
  3808. /**
  3809. * Controls the verbosity of console logging during the build.
  3810. *
  3811. *
  3812. *
  3813. * @default 'info'
  3814. */
  3815. logLevel?: LogLevelOption;
  3816. /**
  3817. * A function that intercepts log messages. If not supplied, logs are printed to the console.
  3818. *
  3819. *
  3820. *
  3821. * @example
  3822. * ```js
  3823. * export default defineConfig({
  3824. * onLog(level, log, defaultHandler) {
  3825. * if (log.code === 'CIRCULAR_DEPENDENCY') {
  3826. * return; // Ignore circular dependency warnings
  3827. * }
  3828. * if (level === 'warn') {
  3829. * defaultHandler('error', log); // turn other warnings into errors
  3830. * } else {
  3831. * defaultHandler(level, log); // otherwise, just print the log
  3832. * }
  3833. * }
  3834. * })
  3835. * ```
  3836. */
  3837. onLog?: OnLogFunction;
  3838. /**
  3839. * A function that will intercept warning messages.
  3840. *
  3841. *
  3842. *
  3843. * @deprecated
  3844. * This is a legacy API. Consider using {@linkcode onLog} instead for better control over all log types.
  3845. *
  3846. *
  3847. */
  3848. onwarn?: OnwarnFunction;
  3849. /**
  3850. * Maps file patterns to module types, controlling how files are processed.
  3851. *
  3852. * This is conceptually similar to [esbuild's `loader`](https://esbuild.github.io/api/#loader) option, allowing you to specify how each file extensions should be handled.
  3853. *
  3854. * See [the In-Depth Guide](https://rolldown.rs/in-depth/module-types) for more details.
  3855. *
  3856. * @example
  3857. * ```js
  3858. * import { defineConfig } from 'rolldown'
  3859. *
  3860. * export default defineConfig({
  3861. * moduleTypes: {
  3862. * '.frag': 'text',
  3863. * }
  3864. * })
  3865. * ```
  3866. */
  3867. moduleTypes?: ModuleTypes;
  3868. /**
  3869. * Experimental features that may change in future releases and can introduce behavior change without a major version bump.
  3870. * @experimental
  3871. */
  3872. experimental?: {
  3873. /**
  3874. * Enable Vite compatible mode.
  3875. * @default false
  3876. * @hidden This option is only meant to be used by Vite. It is not recommended to use this option directly.
  3877. */
  3878. viteMode?: boolean;
  3879. /**
  3880. * When enabled, `new URL()` calls will be transformed to a stable asset URL which includes the updated name and content hash.
  3881. * It is necessary to pass `import.meta.url` as the second argument to the
  3882. * `new URL` constructor, otherwise no transform will be applied.
  3883. * :::warning
  3884. * JavaScript and TypeScript files referenced via `new URL('./file.js', import.meta.url)` or `new URL('./file.ts', import.meta.url)` will **not** be transformed or bundled. The file will be copied as-is, meaning TypeScript files remain untransformed and dependencies are not resolved.
  3885. *
  3886. * The expected behavior for JS/TS files is still being discussed and may
  3887. * change in future releases. See [#7258](https://github.com/rolldown/rolldown/issues/7258) for more context.
  3888. * :::
  3889. * @example
  3890. * ```js
  3891. * // main.js
  3892. * const url = new URL('./styles.css', import.meta.url);
  3893. * console.log(url);
  3894. *
  3895. * // Example output after bundling WITHOUT the option (default)
  3896. * const url = new URL('./styles.css', import.meta.url);
  3897. * console.log(url);
  3898. *
  3899. * // Example output after bundling WITH `experimental.resolveNewUrlToAsset` set to `true`
  3900. * const url = new URL('assets/styles-CjdrdY7X.css', import.meta.url);
  3901. * console.log(url);
  3902. * ```
  3903. * @default false
  3904. */
  3905. resolveNewUrlToAsset?: boolean;
  3906. /**
  3907. * Dev mode related options.
  3908. * @hidden not ready for public usage yet
  3909. */
  3910. devMode?: DevModeOptions;
  3911. /**
  3912. * Control which order should be used when rendering modules in a chunk.
  3913. *
  3914. * Available options:
  3915. * - `exec-order`: Almost equivalent to the topological order of the module graph, but specially handling when module graph has cycle.
  3916. * - `module-id`: This is more friendly for gzip compression, especially for some javascript static asset lib (e.g. icon library)
  3917. *
  3918. * > [!NOTE]
  3919. * > Try to sort the modules by their module id if possible (Since rolldown scope hoist all modules in the chunk, we only try to sort those modules by module id if we could ensure runtime behavior is correct after sorting).
  3920. *
  3921. * @default 'exec-order'
  3922. */
  3923. chunkModulesOrder?: ChunkModulesOrder;
  3924. /**
  3925. * Attach debug information to the output bundle.
  3926. *
  3927. * Available modes:
  3928. * - `none`: No debug information is attached.
  3929. * - `simple`: Attach comments indicating which files the bundled code comes from. These comments could be removed by the minifier.
  3930. * - `full`: Attach detailed debug information to the output bundle. These comments are using legal comment syntax, so they won't be removed by the minifier.
  3931. *
  3932. * @default 'simple'
  3933. *
  3934. *
  3935. */
  3936. attachDebugInfo?: AttachDebugOptions;
  3937. /**
  3938. * Enables automatic generation of a chunk import map asset during build.
  3939. *
  3940. * This map only includes chunks with hashed filenames, where keys are derived from the facade module
  3941. * name or primary chunk name. It produces stable and unique hash-based filenames, effectively preventing
  3942. * cascading cache invalidation caused by content hashes and maximizing browser cache reuse.
  3943. *
  3944. * The output defaults to `importmap.json` unless overridden via `fileName`. A base URL prefix
  3945. * (default `"/"`) can be applied to all paths. The resulting JSON is a valid import map and can be
  3946. * directly injected into HTML via `<script type="importmap">`.
  3947. *
  3948. * @example
  3949. * ```js
  3950. * {
  3951. * experimental: {
  3952. * chunkImportMap: {
  3953. * baseUrl: '/',
  3954. * fileName: 'importmap.json'
  3955. * }
  3956. * },
  3957. * plugins: [
  3958. * {
  3959. * name: 'inject-import-map',
  3960. * generateBundle(_, bundle) {
  3961. * const chunkImportMap = bundle['importmap.json'];
  3962. * if (chunkImportMap?.type === 'asset') {
  3963. * const htmlPath = path.resolve('index.html');
  3964. * let html = fs.readFileSync(htmlPath, 'utf-8');
  3965. *
  3966. * html = html.replace(
  3967. * /<script\s+type="importmap"[^>]*>[\s\S]*?<\/script>/i,
  3968. * `<script type="importmap">${chunkImportMap.source}<\/script>`
  3969. * );
  3970. *
  3971. * fs.writeFileSync(htmlPath, html);
  3972. * delete bundle['importmap.json'];
  3973. * }
  3974. * }
  3975. * }
  3976. * ]
  3977. * }
  3978. * ```
  3979. *
  3980. * > [!TIP]
  3981. * > If you want to learn more, you can check out the example here: [examples/chunk-import-map](https://github.com/rolldown/rolldown/tree/main/examples/chunk-import-map)
  3982. *
  3983. * @default false
  3984. */
  3985. chunkImportMap?: boolean | {
  3986. baseUrl?: string;
  3987. fileName?: string;
  3988. };
  3989. /**
  3990. * Under `output.strictExecutionOrder`, derive a conservative wrapping plan from predicted
  3991. * chunk execution hazards instead of wrapping every eligible module.
  3992. * @default false
  3993. * @hidden not ready for public usage yet
  3994. */
  3995. onDemandWrapping?: boolean;
  3996. /**
  3997. * Enable incremental build support. Required to be used with `watch` mode.
  3998. * @default false
  3999. */
  4000. incrementalBuild?: boolean;
  4001. /**
  4002. * Use native Rust implementation of MagicString for source map generation.
  4003. *
  4004. * [MagicString](https://github.com/rich-harris/magic-string) is a JavaScript library commonly used by bundlers
  4005. * for string manipulation and source map generation. When enabled, rolldown will use a native Rust
  4006. * implementation of MagicString instead of the JavaScript version, providing significantly better performance
  4007. * during source map generation and code transformation.
  4008. *
  4009. * **Benefits**
  4010. *
  4011. * - **Improved Performance**: The native Rust implementation is typically faster than the JavaScript version,
  4012. * especially for large codebases with extensive source maps.
  4013. * - **Background Processing**: Source map generation is performed asynchronously in a background thread,
  4014. * allowing the main bundling process to continue without blocking. This parallel processing can significantly
  4015. * reduce overall build times when working with JavaScript transform hooks.
  4016. * - **Better Integration**: Seamless integration with rolldown's native Rust architecture.
  4017. *
  4018. * @example
  4019. * ```js
  4020. * export default {
  4021. * experimental: {
  4022. * nativeMagicString: true
  4023. * },
  4024. * output: {
  4025. * sourcemap: true
  4026. * }
  4027. * }
  4028. * ```
  4029. *
  4030. * > [!NOTE]
  4031. * > This is an experimental feature. While it aims to provide identical behavior to the JavaScript
  4032. * > implementation, there may be edge cases. Please report any discrepancies you encounter.
  4033. * > For a complete working example, see [examples/native-magic-string](https://github.com/rolldown/rolldown/tree/main/examples/native-magic-string)
  4034. * @default false
  4035. */
  4036. nativeMagicString?: boolean;
  4037. /**
  4038. * Control chunk optimizations.
  4039. *
  4040. * `true` enables both common-chunk merging and redundant dynamic chunk-load avoidance.
  4041. * `false` disables all chunk optimizations. Use the object form to control
  4042. * `mergeCommonChunks` and `avoidRedundantChunkLoads` separately.
  4043. *
  4044. * These optimizations are automatically disabled when any module uses top-level await (TLA) or contains TLA dependencies,
  4045. * as they could affect execution order guarantees.
  4046. *
  4047. * @default true
  4048. */
  4049. chunkOptimization?: boolean | ChunkOptimizationOptions;
  4050. /**
  4051. * Control whether to enable lazy barrel optimization.
  4052. *
  4053. * Lazy barrel optimization avoids compiling unused re-export modules in side-effect-free barrel modules,
  4054. * significantly improving build performance for large codebases with many barrel modules.
  4055. *
  4056. * This option is planned to be removed in the future. If you need to opt out, please open an issue
  4057. * describing your use case so we can address it before the option is gone.
  4058. *
  4059. * @see {@link https://rolldown.rs/in-depth/lazy-barrel-optimization | Lazy Barrel Documentation}
  4060. * @default false
  4061. */
  4062. lazyBarrel?: boolean;
  4063. };
  4064. /**
  4065. * Configure how the code is transformed. This process happens after the `transform` hook.
  4066. *
  4067. * @example
  4068. * **Enable legacy decorators**
  4069. * ```js
  4070. * export default defineConfig({
  4071. * transform: {
  4072. * decorator: {
  4073. * legacy: true,
  4074. * },
  4075. * },
  4076. * })
  4077. * ```
  4078. * Note that if you have correct `tsconfig.json` file, Rolldown will automatically detect and enable legacy decorators support.
  4079. *
  4080. *
  4081. */
  4082. transform?: TransformOptions;
  4083. /**
  4084. * Watch mode related options.
  4085. *
  4086. * These options only take effect when running with the [`--watch`](/apis/cli#w-watch) flag, or using {@linkcode watch | watch()} API.
  4087. *
  4088. *
  4089. *
  4090. * @experimental
  4091. */
  4092. watch?: WatcherOptions | false;
  4093. /**
  4094. * Controls which warnings are emitted during the build process. Each option can be set to `true` (emit warning) or `false` (suppress warning).
  4095. */
  4096. checks?: ChecksOptions;
  4097. /**
  4098. * Determines if absolute external paths should be converted to relative paths in the output.
  4099. *
  4100. * This does not only apply to paths that are absolute in the source but also to paths that are resolved to an absolute path by either a plugin or Rolldown core.
  4101. *
  4102. *
  4103. */
  4104. makeAbsoluteExternalsRelative?: MakeAbsoluteExternalsRelative;
  4105. /**
  4106. * Devtools integration options.
  4107. *
  4108. * When enabled, Rolldown writes JSON-lines devtools output under
  4109. * `node_modules/.rolldown/{session_id}/`, resolved against {@linkcode cwd}.
  4110. * Consumers can parse the output with `@rolldown/debug` after
  4111. * `await bundle.close()` resolves.
  4112. *
  4113. * @experimental
  4114. */
  4115. devtools?: {
  4116. sessionId?: string;
  4117. };
  4118. /**
  4119. * Controls how entry chunk exports are preserved.
  4120. *
  4121. * This determines whether Rolldown needs to create facade chunks (additional wrapper chunks) to maintain the exact export signatures of entry modules, or whether it can combine entry modules with other chunks for optimization.
  4122. *
  4123. * @default `'exports-only'`
  4124. *
  4125. */
  4126. preserveEntrySignatures?: false | "strict" | "allow-extension" | "exports-only";
  4127. /**
  4128. * Configure optimization features for the bundler.
  4129. */
  4130. optimization?: OptimizationOptions;
  4131. /**
  4132. * The value of `this` at the top level of each module. **Normally, you don't need to set this option.**
  4133. * @default undefined
  4134. * @example
  4135. * **Set custom context**
  4136. * ```js
  4137. * export default {
  4138. * context: 'globalThis',
  4139. * output: {
  4140. * format: 'iife',
  4141. * },
  4142. * };
  4143. * ```
  4144. *
  4145. */
  4146. context?: string;
  4147. /**
  4148. * Configures TypeScript configuration file resolution and usage.
  4149. *
  4150. * @default true
  4151. */
  4152. tsconfig?: boolean | string;
  4153. }
  4154. //#endregion
  4155. //#region src/types/rolldown-options.d.ts
  4156. interface RolldownOptions extends InputOptions {
  4157. output?: OutputOptions | OutputOptions[];
  4158. }
  4159. //#endregion
  4160. //#region src/utils/define-config.d.ts
  4161. /**
  4162. * Type for `default export` of `rolldown.config.js` file.
  4163. * @category Config
  4164. */
  4165. type ConfigExport = RolldownOptions | RolldownOptions[] | RolldownOptionsFunction;
  4166. /** @category Config */
  4167. type RolldownOptionsFunction = (commandLineArguments: Record<string, any>) => MaybePromise<RolldownOptions | RolldownOptions[]>;
  4168. /**
  4169. * A helper to define a rolldown configuration with type hints.
  4170. *
  4171. * @example
  4172. * ```js [rolldown.config.js]
  4173. * import { defineConfig } from 'rolldown';
  4174. *
  4175. * export default defineConfig({
  4176. * input: 'src/main.js',
  4177. * output: {
  4178. * file: 'bundle.js',
  4179. * },
  4180. * });
  4181. * ```
  4182. *
  4183. * @category Config
  4184. */
  4185. declare function defineConfig(config: RolldownOptions): RolldownOptions;
  4186. declare function defineConfig(config: RolldownOptions[]): RolldownOptions[];
  4187. declare function defineConfig(config: RolldownOptionsFunction): RolldownOptionsFunction;
  4188. declare function defineConfig(config: ConfigExport): ConfigExport;
  4189. //#endregion
  4190. export { defineParallelPlugin as $, SourceMap as $t, ResolvedId as A, ChunkFileNamesFunction as At, ExistingRawSourceMap as B, ManglePropertiesOptions as Bt, ParallelPluginHooks as C, RolldownBuild as Ct, ResolveFileUrlArgs as D, AdvancedChunksGroup as Dt, PluginMeta as E, AddonFunction as Et, withFilter as F, CommentsOptions as Ft, EmittedAsset as G, MaybePromise as Gt, OutputBundle as H, ModuleFormat as Ht, BuiltinPlugin as I, ExperimentalInlineCommonChunksOptions as It, EmittedPrebuiltChunk as J, OutputAsset as Jt, EmittedChunk as K, PartialNull as Kt, RUNTIME_MODULE_ID as L, GeneratedCodeOptions as Lt, RolldownPluginOption as M, CodeSplittingGroup as Mt, SourceDescription as N, CodeSplittingNameFunction as Nt, ResolveIdExtraOptions as O, AdvancedChunksOptions as Ot, TransformResult as P, CodeSplittingOptions as Pt, DefineParallelPluginResult as Q, RolldownOutput as Qt, VERSION as R, GeneratedCodePreset as Rt, ObjectHook as S, rolldown as St, Plugin as T, build as Tt, TreeshakingOptions as U, OutputOptions as Ut, SourceMapInput as V, MinifyOptions as Vt, TransformPluginContext as W, PreRenderedAsset as Wt, PluginContext as X, RenderedChunk as Xt, GetModuleInfo as Y, OutputChunk as Yt, PluginContextResolveOptions as Z, RenderedModule as Zt, HookFilterExtension as _, watch as _t, ChunkOptimizationOptions as a, BufferEncoding as at, ModuleOptions as b, RolldownWatcherWatcherEventMap as bt, InputOption as c, RolldownFsModule as ct, OptimizationOptions as d, NormalizedInputOptions as dt, freeExternalMemory as en, MinimalPluginContext as et, WatcherFileWatcherOptions as f, TransformOptions as ft, FunctionPluginHooks as g, RolldownMagicString as gt, CustomPluginOptions as h, WarningHandlerWithDefault as ht, RolldownOptions as i, ModuleTypeFilter as it, RolldownPlugin as j, ChunkingContext as jt, ResolveIdResult as k, BuiltinModuleTag as kt, InputOptions as l, InternalModuleFormat as lt, AsyncPluginHooks as m, LoggingFunction as mt, RolldownOptionsFunction as n, SourcemapIgnoreListOption as nn, GeneralHookFilter as nt, ExternalOption as o, RolldownDirectoryEntry as ot, WatcherOptions as p, ChecksOptions as pt, EmittedFile as q, StringOrRegExp as qt, defineConfig as r, HookFilter as rt, ExternalOptionFunction as s, RolldownFileStats as st, ConfigExport as t, ModuleInfo as tn, PluginContextMeta as tt, ModuleTypes as u, NormalizedOutputOptions as ut, ImportKind as v, RolldownWatcher as vt, PartialResolvedId as w, BuildOptions as wt, ModuleType as x, WatchOptions as xt, LoadResult as y, RolldownWatcherEvent as yt, BundleError as z, GlobalsFunction as zt };