index.d.ts 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627
  1. /// <reference types="node" />
  2. import { PluginHooks, RollupError, SourceMap, ModuleInfo, PartialResolvedId, MinimalPluginContext, InputOptions, CustomPluginOptions, LoadResult, SourceDescription, RollupOptions, WatcherOptions, InputOption, ModuleFormat, RollupOutput, RollupWatcher, SourceMapInput, ExistingRawSourceMap, OutputBundle, OutputChunk, ObjectHook, PluginContext, ResolveIdResult, TransformPluginContext, GetManualChunk } from 'rollup';
  3. import * as rollup from 'rollup';
  4. export { rollup as Rollup };
  5. export { parseAst, parseAstAsync } from 'rollup/parseAst';
  6. import * as http from 'node:http';
  7. import { OutgoingHttpHeaders, ClientRequestArgs, IncomingMessage, ClientRequest, Agent, Server, ServerResponse } from 'node:http';
  8. import { Http2SecureServer } from 'node:http2';
  9. import * as fs from 'node:fs';
  10. import * as events from 'node:events';
  11. import { EventEmitter } from 'node:events';
  12. import { ServerOptions as HttpsServerOptions, Server as HttpsServer } from 'node:https';
  13. import * as net from 'node:net';
  14. import * as url from 'node:url';
  15. import { URL } from 'node:url';
  16. import * as stream from 'node:stream';
  17. import { Duplex, DuplexOptions } from 'node:stream';
  18. import { F as FetchResult, H as HMRLogger } from './types.d-aGj9QkWt.js';
  19. export { a as FetchFunction } from './types.d-aGj9QkWt.js';
  20. import { SecureContextOptions } from 'node:tls';
  21. import { ZlibOptions } from 'node:zlib';
  22. import { HMRPayload, CustomPayload } from '../../types/hmrPayload.js';
  23. export { ConnectedPayload, CustomPayload, ErrorPayload, FullReloadPayload, HMRPayload, PrunePayload, Update, UpdatePayload } from '../../types/hmrPayload.js';
  24. import { InferCustomEventPayload } from '../../types/customEvent.js';
  25. export { CustomEventMap, InferCustomEventPayload, InvalidatePayload } from '../../types/customEvent.js';
  26. import { TransformOptions as esbuild_TransformOptions, TransformResult as esbuild_TransformResult, BuildOptions as esbuild_BuildOptions } from 'esbuild';
  27. export { TransformOptions as EsbuildTransformOptions, version as esbuildVersion } from 'esbuild';
  28. import * as PostCSS from 'postcss';
  29. import { ViteRuntimeOptions, ViteModuleRunner, ViteRuntime, HMRRuntimeConnection } from 'vite/runtime';
  30. export { GeneralImportGlobOptions, ImportGlobFunction, ImportGlobOptions, KnownAsTypeMap } from '../../types/importGlob.js';
  31. export { ChunkMetadata } from '../../types/metadata.js';
  32. import '../../types/hot.js';
  33. interface Alias {
  34. find: string | RegExp
  35. replacement: string
  36. /**
  37. * Instructs the plugin to use an alternative resolving algorithm,
  38. * rather than the Rollup's resolver.
  39. * @default null
  40. */
  41. customResolver?: ResolverFunction | ResolverObject | null
  42. }
  43. type MapToFunction<T> = T extends Function ? T : never
  44. type ResolverFunction = MapToFunction<PluginHooks['resolveId']>
  45. interface ResolverObject {
  46. buildStart?: PluginHooks['buildStart']
  47. resolveId: ResolverFunction
  48. }
  49. /**
  50. * Specifies an `Object`, or an `Array` of `Object`,
  51. * which defines aliases used to replace values in `import` or `require` statements.
  52. * With either format, the order of the entries is important,
  53. * in that the first defined rules are applied first.
  54. *
  55. * This is passed to \@rollup/plugin-alias as the "entries" field
  56. * https://github.com/rollup/plugins/tree/master/packages/alias#entries
  57. */
  58. type AliasOptions = readonly Alias[] | { [find: string]: string }
  59. type AnymatchFn = (testString: string) => boolean
  60. type AnymatchPattern = string | RegExp | AnymatchFn
  61. type AnymatchMatcher = AnymatchPattern | AnymatchPattern[]
  62. // Inlined to avoid extra dependency (chokidar is bundled in the published build)
  63. declare class FSWatcher extends EventEmitter implements fs.FSWatcher {
  64. options: WatchOptions
  65. /**
  66. * Constructs a new FSWatcher instance with optional WatchOptions parameter.
  67. */
  68. constructor(options?: WatchOptions)
  69. /**
  70. * When called, requests that the Node.js event loop not exit so long as the fs.FSWatcher is active.
  71. * Calling watcher.ref() multiple times will have no effect.
  72. */
  73. ref(): this
  74. /**
  75. * When called, the active fs.FSWatcher object will not require the Node.js event loop to remain active.
  76. * If there is no other activity keeping the event loop running, the process may exit before the fs.FSWatcher object's callback is invoked.
  77. * Calling watcher.unref() multiple times will have no effect.
  78. */
  79. unref(): this
  80. /**
  81. * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one
  82. * string.
  83. */
  84. add(paths: string | ReadonlyArray<string>): this
  85. /**
  86. * Stop watching files, directories, or glob patterns. Takes an array of strings or just one
  87. * string.
  88. */
  89. unwatch(paths: string | ReadonlyArray<string>): this
  90. /**
  91. * Returns an object representing all the paths on the file system being watched by this
  92. * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless
  93. * the `cwd` option was used), and the values are arrays of the names of the items contained in
  94. * each directory.
  95. */
  96. getWatched(): {
  97. [directory: string]: string[]
  98. }
  99. /**
  100. * Removes all listeners from watched files.
  101. */
  102. close(): Promise<void>
  103. on(
  104. event: 'add' | 'addDir' | 'change',
  105. listener: (path: string, stats?: fs.Stats) => void,
  106. ): this
  107. on(
  108. event: 'all',
  109. listener: (
  110. eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir',
  111. path: string,
  112. stats?: fs.Stats,
  113. ) => void,
  114. ): this
  115. /**
  116. * Error occurred
  117. */
  118. on(event: 'error', listener: (error: Error) => void): this
  119. /**
  120. * Exposes the native Node `fs.FSWatcher events`
  121. */
  122. on(
  123. event: 'raw',
  124. listener: (eventName: string, path: string, details: any) => void,
  125. ): this
  126. /**
  127. * Fires when the initial scan is complete
  128. */
  129. on(event: 'ready', listener: () => void): this
  130. on(event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this
  131. on(event: string, listener: (...args: any[]) => void): this
  132. }
  133. interface WatchOptions {
  134. /**
  135. * Indicates whether the process should continue to run as long as files are being watched. If
  136. * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`,
  137. * even if the process continues to run.
  138. */
  139. persistent?: boolean
  140. /**
  141. * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to
  142. * be ignored. The whole relative or absolute path is tested, not just filename. If a function
  143. * with two arguments is provided, it gets called twice per path - once with a single argument
  144. * (the path), second time with two arguments (the path and the
  145. * [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path).
  146. */
  147. ignored?: AnymatchMatcher
  148. /**
  149. * If set to `false` then `add`/`addDir` events are also emitted for matching paths while
  150. * instantiating the watching as chokidar discovers these file paths (before the `ready` event).
  151. */
  152. ignoreInitial?: boolean
  153. /**
  154. * When `false`, only the symlinks themselves will be watched for changes instead of following
  155. * the link references and bubbling events through the link's path.
  156. */
  157. followSymlinks?: boolean
  158. /**
  159. * The base directory from which watch `paths` are to be derived. Paths emitted with events will
  160. * be relative to this.
  161. */
  162. cwd?: string
  163. /**
  164. * If set to true then the strings passed to .watch() and .add() are treated as literal path
  165. * names, even if they look like globs.
  166. *
  167. * @default false
  168. */
  169. disableGlobbing?: boolean
  170. /**
  171. * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU
  172. * utilization, consider setting this to `false`. It is typically necessary to **set this to
  173. * `true` to successfully watch files over a network**, and it may be necessary to successfully
  174. * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides
  175. * the `useFsEvents` default.
  176. */
  177. usePolling?: boolean
  178. /**
  179. * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly
  180. * and `fsevents` is available this supersedes the `usePolling` setting. When set to `false` on
  181. * OS X, `usePolling: true` becomes the default.
  182. */
  183. useFsEvents?: boolean
  184. /**
  185. * If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that
  186. * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is
  187. * provided even in cases where it wasn't already available from the underlying watch events.
  188. */
  189. alwaysStat?: boolean
  190. /**
  191. * If set, limits how many levels of subdirectories will be traversed.
  192. */
  193. depth?: number
  194. /**
  195. * Interval of file system polling.
  196. */
  197. interval?: number
  198. /**
  199. * Interval of file system polling for binary files. ([see list of binary extensions](https://gi
  200. * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
  201. */
  202. binaryInterval?: number
  203. /**
  204. * Indicates whether to watch files that don't have read permissions if possible. If watching
  205. * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed
  206. * silently.
  207. */
  208. ignorePermissionErrors?: boolean
  209. /**
  210. * `true` if `useFsEvents` and `usePolling` are `false`. Automatically filters out artifacts
  211. * that occur when using editors that use "atomic writes" instead of writing directly to the
  212. * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change`
  213. * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you,
  214. * you can override it by setting `atomic` to a custom value, in milliseconds.
  215. */
  216. atomic?: boolean | number
  217. /**
  218. * can be set to an object in order to adjust timing params:
  219. */
  220. awaitWriteFinish?: AwaitWriteFinishOptions | boolean
  221. }
  222. interface AwaitWriteFinishOptions {
  223. /**
  224. * Amount of time in milliseconds for a file size to remain constant before emitting its event.
  225. */
  226. stabilityThreshold?: number
  227. /**
  228. * File size polling interval.
  229. */
  230. pollInterval?: number
  231. }
  232. // Inlined to avoid extra dependency
  233. // MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE
  234. declare namespace Connect {
  235. export type ServerHandle = HandleFunction | http.Server
  236. export class IncomingMessage extends http.IncomingMessage {
  237. originalUrl?: http.IncomingMessage['url'] | undefined
  238. }
  239. export type NextFunction = (err?: any) => void
  240. export type SimpleHandleFunction = (
  241. req: IncomingMessage,
  242. res: http.ServerResponse,
  243. ) => void
  244. export type NextHandleFunction = (
  245. req: IncomingMessage,
  246. res: http.ServerResponse,
  247. next: NextFunction,
  248. ) => void
  249. export type ErrorHandleFunction = (
  250. err: any,
  251. req: IncomingMessage,
  252. res: http.ServerResponse,
  253. next: NextFunction,
  254. ) => void
  255. export type HandleFunction =
  256. | SimpleHandleFunction
  257. | NextHandleFunction
  258. | ErrorHandleFunction
  259. export interface ServerStackItem {
  260. route: string
  261. handle: ServerHandle
  262. }
  263. export interface Server extends NodeJS.EventEmitter {
  264. (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void
  265. route: string
  266. stack: ServerStackItem[]
  267. /**
  268. * Utilize the given middleware `handle` to the given `route`,
  269. * defaulting to _/_. This "route" is the mount-point for the
  270. * middleware, when given a value other than _/_ the middleware
  271. * is only effective when that segment is present in the request's
  272. * pathname.
  273. *
  274. * For example if we were to mount a function at _/admin_, it would
  275. * be invoked on _/admin_, and _/admin/settings_, however it would
  276. * not be invoked for _/_, or _/posts_.
  277. */
  278. use(fn: NextHandleFunction): Server
  279. use(fn: HandleFunction): Server
  280. use(route: string, fn: NextHandleFunction): Server
  281. use(route: string, fn: HandleFunction): Server
  282. /**
  283. * Handle server requests, punting them down
  284. * the middleware stack.
  285. */
  286. handle(
  287. req: http.IncomingMessage,
  288. res: http.ServerResponse,
  289. next: Function,
  290. ): void
  291. /**
  292. * Listen for connections.
  293. *
  294. * This method takes the same arguments
  295. * as node's `http.Server#listen()`.
  296. *
  297. * HTTP and HTTPS:
  298. *
  299. * If you run your application both as HTTP
  300. * and HTTPS you may wrap them individually,
  301. * since your Connect "server" is really just
  302. * a JavaScript `Function`.
  303. *
  304. * var connect = require('connect')
  305. * , http = require('http')
  306. * , https = require('https');
  307. *
  308. * var app = connect();
  309. *
  310. * http.createServer(app).listen(80);
  311. * https.createServer(options, app).listen(443);
  312. */
  313. listen(
  314. port: number,
  315. hostname?: string,
  316. backlog?: number,
  317. callback?: Function,
  318. ): http.Server
  319. listen(port: number, hostname?: string, callback?: Function): http.Server
  320. listen(path: string, callback?: Function): http.Server
  321. listen(handle: any, listeningListener?: Function): http.Server
  322. }
  323. }
  324. // Inlined to avoid extra dependency
  325. // MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE
  326. declare namespace HttpProxy {
  327. export type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed
  328. export type ProxyTargetUrl = string | Partial<url.Url>
  329. export interface ProxyTargetDetailed {
  330. host: string
  331. port: number
  332. protocol?: string | undefined
  333. hostname?: string | undefined
  334. socketPath?: string | undefined
  335. key?: string | undefined
  336. passphrase?: string | undefined
  337. pfx?: Buffer | string | undefined
  338. cert?: string | undefined
  339. ca?: string | undefined
  340. ciphers?: string | undefined
  341. secureProtocol?: string | undefined
  342. }
  343. export type ErrorCallback = (
  344. err: Error,
  345. req: http.IncomingMessage,
  346. res: http.ServerResponse,
  347. target?: ProxyTargetUrl,
  348. ) => void
  349. export class Server extends events.EventEmitter {
  350. /**
  351. * Creates the proxy server with specified options.
  352. * @param options - Config object passed to the proxy
  353. */
  354. constructor(options?: ServerOptions)
  355. /**
  356. * Used for proxying regular HTTP(S) requests
  357. * @param req - Client request.
  358. * @param res - Client response.
  359. * @param options - Additional options.
  360. * @param callback - Error callback.
  361. */
  362. web(
  363. req: http.IncomingMessage,
  364. res: http.ServerResponse,
  365. options?: ServerOptions,
  366. callback?: ErrorCallback,
  367. ): void
  368. /**
  369. * Used for proxying regular HTTP(S) requests
  370. * @param req - Client request.
  371. * @param socket - Client socket.
  372. * @param head - Client head.
  373. * @param options - Additional options.
  374. * @param callback - Error callback.
  375. */
  376. ws(
  377. req: http.IncomingMessage,
  378. socket: unknown,
  379. head: unknown,
  380. options?: ServerOptions,
  381. callback?: ErrorCallback,
  382. ): void
  383. /**
  384. * A function that wraps the object in a webserver, for your convenience
  385. * @param port - Port to listen on
  386. */
  387. listen(port: number): Server
  388. /**
  389. * A function that closes the inner webserver and stops listening on given port
  390. */
  391. close(callback?: () => void): void
  392. /**
  393. * Creates the proxy server with specified options.
  394. * @param options - Config object passed to the proxy
  395. * @returns Proxy object with handlers for `ws` and `web` requests
  396. */
  397. static createProxyServer(options?: ServerOptions): Server
  398. /**
  399. * Creates the proxy server with specified options.
  400. * @param options - Config object passed to the proxy
  401. * @returns Proxy object with handlers for `ws` and `web` requests
  402. */
  403. static createServer(options?: ServerOptions): Server
  404. /**
  405. * Creates the proxy server with specified options.
  406. * @param options - Config object passed to the proxy
  407. * @returns Proxy object with handlers for `ws` and `web` requests
  408. */
  409. static createProxy(options?: ServerOptions): Server
  410. addListener(event: string, listener: () => void): this
  411. on(event: string, listener: () => void): this
  412. on(event: 'error', listener: ErrorCallback): this
  413. on(
  414. event: 'start',
  415. listener: (
  416. req: http.IncomingMessage,
  417. res: http.ServerResponse,
  418. target: ProxyTargetUrl,
  419. ) => void,
  420. ): this
  421. on(
  422. event: 'proxyReq',
  423. listener: (
  424. proxyReq: http.ClientRequest,
  425. req: http.IncomingMessage,
  426. res: http.ServerResponse,
  427. options: ServerOptions,
  428. ) => void,
  429. ): this
  430. on(
  431. event: 'proxyRes',
  432. listener: (
  433. proxyRes: http.IncomingMessage,
  434. req: http.IncomingMessage,
  435. res: http.ServerResponse,
  436. ) => void,
  437. ): this
  438. on(
  439. event: 'proxyReqWs',
  440. listener: (
  441. proxyReq: http.ClientRequest,
  442. req: http.IncomingMessage,
  443. socket: net.Socket,
  444. options: ServerOptions,
  445. head: any,
  446. ) => void,
  447. ): this
  448. on(
  449. event: 'econnreset',
  450. listener: (
  451. err: Error,
  452. req: http.IncomingMessage,
  453. res: http.ServerResponse,
  454. target: ProxyTargetUrl,
  455. ) => void,
  456. ): this
  457. on(
  458. event: 'end',
  459. listener: (
  460. req: http.IncomingMessage,
  461. res: http.ServerResponse,
  462. proxyRes: http.IncomingMessage,
  463. ) => void,
  464. ): this
  465. on(
  466. event: 'close',
  467. listener: (
  468. proxyRes: http.IncomingMessage,
  469. proxySocket: net.Socket,
  470. proxyHead: any,
  471. ) => void,
  472. ): this
  473. once(event: string, listener: () => void): this
  474. removeListener(event: string, listener: () => void): this
  475. removeAllListeners(event?: string): this
  476. getMaxListeners(): number
  477. setMaxListeners(n: number): this
  478. listeners(event: string): Array<() => void>
  479. emit(event: string, ...args: any[]): boolean
  480. listenerCount(type: string): number
  481. }
  482. export interface ServerOptions {
  483. /** URL string to be parsed with the url module. */
  484. target?: ProxyTarget | undefined
  485. /** URL string to be parsed with the url module. */
  486. forward?: ProxyTargetUrl | undefined
  487. /** Object to be passed to http(s).request. */
  488. agent?: any
  489. /** Object to be passed to https.createServer(). */
  490. ssl?: any
  491. /** If you want to proxy websockets. */
  492. ws?: boolean | undefined
  493. /** Adds x- forward headers. */
  494. xfwd?: boolean | undefined
  495. /** Verify SSL certificate. */
  496. secure?: boolean | undefined
  497. /** Explicitly specify if we are proxying to another proxy. */
  498. toProxy?: boolean | undefined
  499. /** Specify whether you want to prepend the target's path to the proxy path. */
  500. prependPath?: boolean | undefined
  501. /** Specify whether you want to ignore the proxy path of the incoming request. */
  502. ignorePath?: boolean | undefined
  503. /** Local interface string to bind for outgoing connections. */
  504. localAddress?: string | undefined
  505. /** Changes the origin of the host header to the target URL. */
  506. changeOrigin?: boolean | undefined
  507. /** specify whether you want to keep letter case of response header key */
  508. preserveHeaderKeyCase?: boolean | undefined
  509. /** Basic authentication i.e. 'user:password' to compute an Authorization header. */
  510. auth?: string | undefined
  511. /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */
  512. hostRewrite?: string | undefined
  513. /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */
  514. autoRewrite?: boolean | undefined
  515. /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */
  516. protocolRewrite?: string | undefined
  517. /** rewrites domain of set-cookie headers. */
  518. cookieDomainRewrite?:
  519. | false
  520. | string
  521. | { [oldDomain: string]: string }
  522. | undefined
  523. /** rewrites path of set-cookie headers. Default: false */
  524. cookiePathRewrite?:
  525. | false
  526. | string
  527. | { [oldPath: string]: string }
  528. | undefined
  529. /** object with extra headers to be added to target requests. */
  530. headers?: { [header: string]: string } | undefined
  531. /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */
  532. proxyTimeout?: number | undefined
  533. /** Timeout (in milliseconds) for incoming requests */
  534. timeout?: number | undefined
  535. /** Specify whether you want to follow redirects. Default: false */
  536. followRedirects?: boolean | undefined
  537. /** If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event */
  538. selfHandleResponse?: boolean | undefined
  539. /** Buffer */
  540. buffer?: stream.Stream | undefined
  541. }
  542. }
  543. interface ProxyOptions extends HttpProxy.ServerOptions {
  544. /**
  545. * rewrite path
  546. */
  547. rewrite?: (path: string) => string;
  548. /**
  549. * configure the proxy server (e.g. listen to events)
  550. */
  551. configure?: (proxy: HttpProxy.Server, options: ProxyOptions) => void;
  552. /**
  553. * webpack-dev-server style bypass function
  554. */
  555. bypass?: (req: http.IncomingMessage, res: http.ServerResponse, options: ProxyOptions) => void | null | undefined | false | string;
  556. /**
  557. * rewrite the Origin header of a WebSocket request to match the the target
  558. *
  559. * **Exercise caution as rewriting the Origin can leave the proxying open to [CSRF attacks](https://owasp.org/www-community/attacks/csrf).**
  560. */
  561. rewriteWsOrigin?: boolean | undefined;
  562. }
  563. type LogType = 'error' | 'warn' | 'info';
  564. type LogLevel = LogType | 'silent';
  565. interface Logger {
  566. info(msg: string, options?: LogOptions): void;
  567. warn(msg: string, options?: LogOptions): void;
  568. warnOnce(msg: string, options?: LogOptions): void;
  569. error(msg: string, options?: LogErrorOptions): void;
  570. clearScreen(type: LogType): void;
  571. hasErrorLogged(error: Error | RollupError): boolean;
  572. hasWarned: boolean;
  573. }
  574. interface LogOptions {
  575. clear?: boolean;
  576. timestamp?: boolean;
  577. }
  578. interface LogErrorOptions extends LogOptions {
  579. error?: Error | RollupError | null;
  580. }
  581. interface LoggerOptions {
  582. prefix?: string;
  583. allowClearScreen?: boolean;
  584. customLogger?: Logger;
  585. }
  586. declare function createLogger(level?: LogLevel, options?: LoggerOptions): Logger;
  587. interface CommonServerOptions {
  588. /**
  589. * Specify server port. Note if the port is already being used, Vite will
  590. * automatically try the next available port so this may not be the actual
  591. * port the server ends up listening on.
  592. */
  593. port?: number;
  594. /**
  595. * If enabled, vite will exit if specified port is already in use
  596. */
  597. strictPort?: boolean;
  598. /**
  599. * Specify which IP addresses the server should listen on.
  600. * Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.
  601. */
  602. host?: string | boolean;
  603. /**
  604. * The hostnames that Vite is allowed to respond to.
  605. * `localhost` and subdomains under `.localhost` and all IP addresses are allowed by default.
  606. * When using HTTPS, this check is skipped.
  607. *
  608. * If a string starts with `.`, it will allow that hostname without the `.` and all subdomains under the hostname.
  609. * For example, `.example.com` will allow `example.com`, `foo.example.com`, and `foo.bar.example.com`.
  610. *
  611. * If set to `true`, the server is allowed to respond to requests for any hosts.
  612. * This is not recommended as it will be vulnerable to DNS rebinding attacks.
  613. */
  614. allowedHosts?: string[] | true;
  615. /**
  616. * Enable TLS + HTTP/2.
  617. * Note: this downgrades to TLS only when the proxy option is also used.
  618. */
  619. https?: HttpsServerOptions;
  620. /**
  621. * Open browser window on startup
  622. */
  623. open?: boolean | string;
  624. /**
  625. * Configure custom proxy rules for the dev server. Expects an object
  626. * of `{ key: options }` pairs.
  627. * Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).
  628. * Full options [here](https://github.com/http-party/node-http-proxy#options).
  629. *
  630. * Example `vite.config.js`:
  631. * ``` js
  632. * module.exports = {
  633. * proxy: {
  634. * // string shorthand: /foo -> http://localhost:4567/foo
  635. * '/foo': 'http://localhost:4567',
  636. * // with options
  637. * '/api': {
  638. * target: 'http://jsonplaceholder.typicode.com',
  639. * changeOrigin: true,
  640. * rewrite: path => path.replace(/^\/api/, '')
  641. * }
  642. * }
  643. * }
  644. * ```
  645. */
  646. proxy?: Record<string, string | ProxyOptions>;
  647. /**
  648. * Configure CORS for the dev server.
  649. * Uses https://github.com/expressjs/cors.
  650. *
  651. * When enabling this option, **we recommend setting a specific value
  652. * rather than `true`** to avoid exposing the source code to untrusted origins.
  653. *
  654. * Set to `true` to allow all methods from any origin, or configure separately
  655. * using an object.
  656. *
  657. * @default false
  658. */
  659. cors?: CorsOptions | boolean;
  660. /**
  661. * Specify server response headers.
  662. */
  663. headers?: OutgoingHttpHeaders;
  664. }
  665. /**
  666. * https://github.com/expressjs/cors#configuration-options
  667. */
  668. interface CorsOptions {
  669. /**
  670. * Configures the Access-Control-Allow-Origin CORS header.
  671. *
  672. * **We recommend setting a specific value rather than
  673. * `true`** to avoid exposing the source code to untrusted origins.
  674. */
  675. origin?: CorsOrigin | ((origin: string | undefined, cb: (err: Error, origins: CorsOrigin) => void) => void);
  676. methods?: string | string[];
  677. allowedHeaders?: string | string[];
  678. exposedHeaders?: string | string[];
  679. credentials?: boolean;
  680. maxAge?: number;
  681. preflightContinue?: boolean;
  682. optionsSuccessStatus?: number;
  683. }
  684. type CorsOrigin = boolean | string | RegExp | (string | RegExp)[];
  685. interface PreviewOptions extends CommonServerOptions {
  686. }
  687. interface ResolvedPreviewOptions extends PreviewOptions {
  688. }
  689. interface PreviewServer {
  690. /**
  691. * The resolved vite config object
  692. */
  693. config: ResolvedConfig;
  694. /**
  695. * Stop the server.
  696. */
  697. close(): Promise<void>;
  698. /**
  699. * A connect app instance.
  700. * - Can be used to attach custom middlewares to the preview server.
  701. * - Can also be used as the handler function of a custom http server
  702. * or as a middleware in any connect-style Node.js frameworks
  703. *
  704. * https://github.com/senchalabs/connect#use-middleware
  705. */
  706. middlewares: Connect.Server;
  707. /**
  708. * native Node http server instance
  709. */
  710. httpServer: HttpServer;
  711. /**
  712. * The resolved urls Vite prints on the CLI.
  713. * null before server is listening.
  714. */
  715. resolvedUrls: ResolvedServerUrls | null;
  716. /**
  717. * Print server urls
  718. */
  719. printUrls(): void;
  720. /**
  721. * Bind CLI shortcuts
  722. */
  723. bindCLIShortcuts(options?: BindCLIShortcutsOptions<PreviewServer>): void;
  724. }
  725. type PreviewServerHook = (this: void, server: PreviewServer) => (() => void) | void | Promise<(() => void) | void>;
  726. /**
  727. * Starts the Vite server in preview mode, to simulate a production deployment
  728. */
  729. declare function preview(inlineConfig?: InlineConfig): Promise<PreviewServer>;
  730. type BindCLIShortcutsOptions<Server = ViteDevServer | PreviewServer> = {
  731. /**
  732. * Print a one-line shortcuts "help" hint to the terminal
  733. */
  734. print?: boolean;
  735. /**
  736. * Custom shortcuts to run when a key is pressed. These shortcuts take priority
  737. * over the default shortcuts if they have the same keys (except the `h` key).
  738. * To disable a default shortcut, define the same key but with `action: undefined`.
  739. */
  740. customShortcuts?: CLIShortcut<Server>[];
  741. };
  742. type CLIShortcut<Server = ViteDevServer | PreviewServer> = {
  743. key: string;
  744. description: string;
  745. action?(server: Server): void | Promise<void>;
  746. };
  747. interface TransformResult {
  748. code: string;
  749. map: SourceMap | {
  750. mappings: '';
  751. } | null;
  752. etag?: string;
  753. deps?: string[];
  754. dynamicDeps?: string[];
  755. }
  756. interface TransformOptions {
  757. ssr?: boolean;
  758. html?: boolean;
  759. }
  760. declare class ModuleNode {
  761. /**
  762. * Public served url path, starts with /
  763. */
  764. url: string;
  765. /**
  766. * Resolved file system path + query
  767. */
  768. id: string | null;
  769. file: string | null;
  770. type: 'js' | 'css';
  771. info?: ModuleInfo;
  772. meta?: Record<string, any>;
  773. importers: Set<ModuleNode>;
  774. clientImportedModules: Set<ModuleNode>;
  775. ssrImportedModules: Set<ModuleNode>;
  776. acceptedHmrDeps: Set<ModuleNode>;
  777. acceptedHmrExports: Set<string> | null;
  778. importedBindings: Map<string, Set<string>> | null;
  779. isSelfAccepting?: boolean;
  780. transformResult: TransformResult | null;
  781. ssrTransformResult: TransformResult | null;
  782. ssrModule: Record<string, any> | null;
  783. ssrError: Error | null;
  784. lastHMRTimestamp: number;
  785. lastInvalidationTimestamp: number;
  786. /**
  787. * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
  788. */
  789. constructor(url: string, setIsSelfAccepting?: boolean);
  790. get importedModules(): Set<ModuleNode>;
  791. }
  792. type ResolvedUrl = [
  793. url: string,
  794. resolvedId: string,
  795. meta: object | null | undefined
  796. ];
  797. declare class ModuleGraph {
  798. private resolveId;
  799. urlToModuleMap: Map<string, ModuleNode>;
  800. idToModuleMap: Map<string, ModuleNode>;
  801. etagToModuleMap: Map<string, ModuleNode>;
  802. fileToModulesMap: Map<string, Set<ModuleNode>>;
  803. safeModulesPath: Set<string>;
  804. constructor(resolveId: (url: string, ssr: boolean) => Promise<PartialResolvedId | null>);
  805. getModuleByUrl(rawUrl: string, ssr?: boolean): Promise<ModuleNode | undefined>;
  806. getModuleById(id: string): ModuleNode | undefined;
  807. getModulesByFile(file: string): Set<ModuleNode> | undefined;
  808. onFileChange(file: string): void;
  809. onFileDelete(file: string): void;
  810. invalidateModule(mod: ModuleNode, seen?: Set<ModuleNode>, timestamp?: number, isHmr?: boolean,
  811. ): void;
  812. invalidateAll(): void;
  813. /**
  814. * Update the module graph based on a module's updated imports information
  815. * If there are dependencies that no longer have any importers, they are
  816. * returned as a Set.
  817. *
  818. * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
  819. * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
  820. */
  821. updateModuleInfo(mod: ModuleNode, importedModules: Set<string | ModuleNode>, importedBindings: Map<string, Set<string>> | null, acceptedModules: Set<string | ModuleNode>, acceptedExports: Set<string> | null, isSelfAccepting: boolean, ssr?: boolean,
  822. ): Promise<Set<ModuleNode> | undefined>;
  823. ensureEntryFromUrl(rawUrl: string, ssr?: boolean, setIsSelfAccepting?: boolean): Promise<ModuleNode>;
  824. createFileOnlyEntry(file: string): ModuleNode;
  825. resolveUrl(url: string, ssr?: boolean): Promise<ResolvedUrl>;
  826. updateModuleTransformResult(mod: ModuleNode, result: TransformResult | null, ssr: boolean): void;
  827. getModuleByEtag(etag: string): ModuleNode | undefined;
  828. }
  829. /**
  830. * This file is refactored into TypeScript based on
  831. * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
  832. */
  833. declare class PluginContainer {
  834. config: ResolvedConfig;
  835. moduleGraph?: ModuleGraph | undefined;
  836. watcher?: FSWatcher | undefined;
  837. plugins: readonly Plugin<any>[];
  838. private _pluginContextMap;
  839. private _pluginContextMapSsr;
  840. private _resolvedRollupOptions?;
  841. private _processesing;
  842. private _seenResolves;
  843. private _closed;
  844. private _moduleNodeToLoadAddedImports;
  845. getSortedPluginHooks: PluginHookUtils['getSortedPluginHooks'];
  846. getSortedPlugins: PluginHookUtils['getSortedPlugins'];
  847. watchFiles: Set<string>;
  848. minimalContext: MinimalPluginContext;
  849. private _updateModuleLoadAddedImports;
  850. private _getAddedImports;
  851. getModuleInfo(id: string): ModuleInfo | null;
  852. private handleHookPromise;
  853. get options(): InputOptions;
  854. resolveRollupOptions(): Promise<InputOptions>;
  855. private _getPluginContext;
  856. private hookParallel;
  857. buildStart(_options?: InputOptions): Promise<void>;
  858. resolveId(rawId: string, importer?: string | undefined, options?: {
  859. attributes?: Record<string, string>;
  860. custom?: CustomPluginOptions;
  861. skip?: Set<Plugin>;
  862. ssr?: boolean;
  863. isEntry?: boolean;
  864. }): Promise<PartialResolvedId | null>;
  865. load(id: string, options?: {
  866. ssr?: boolean;
  867. }): Promise<LoadResult | null>;
  868. transform(code: string, id: string, options?: {
  869. ssr?: boolean;
  870. inMap?: SourceDescription['map'];
  871. }): Promise<{
  872. code: string;
  873. map: SourceMap | {
  874. mappings: '';
  875. } | null;
  876. }>;
  877. watchChange(id: string, change: {
  878. event: 'create' | 'update' | 'delete';
  879. }): Promise<void>;
  880. close(): Promise<void>;
  881. }
  882. // Modified and inlined to avoid extra dependency
  883. // Source: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts
  884. declare const WebSocketAlias: typeof WebSocket
  885. interface WebSocketAlias extends WebSocket {}
  886. // WebSocket socket.
  887. declare class WebSocket extends EventEmitter {
  888. /** The connection is not yet open. */
  889. static readonly CONNECTING: 0
  890. /** The connection is open and ready to communicate. */
  891. static readonly OPEN: 1
  892. /** The connection is in the process of closing. */
  893. static readonly CLOSING: 2
  894. /** The connection is closed. */
  895. static readonly CLOSED: 3
  896. binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments'
  897. readonly bufferedAmount: number
  898. readonly extensions: string
  899. /** Indicates whether the websocket is paused */
  900. readonly isPaused: boolean
  901. readonly protocol: string
  902. /** The current state of the connection */
  903. readonly readyState:
  904. | typeof WebSocket.CONNECTING
  905. | typeof WebSocket.OPEN
  906. | typeof WebSocket.CLOSING
  907. | typeof WebSocket.CLOSED
  908. readonly url: string
  909. /** The connection is not yet open. */
  910. readonly CONNECTING: 0
  911. /** The connection is open and ready to communicate. */
  912. readonly OPEN: 1
  913. /** The connection is in the process of closing. */
  914. readonly CLOSING: 2
  915. /** The connection is closed. */
  916. readonly CLOSED: 3
  917. onopen: ((event: WebSocket.Event) => void) | null
  918. onerror: ((event: WebSocket.ErrorEvent) => void) | null
  919. onclose: ((event: WebSocket.CloseEvent) => void) | null
  920. onmessage: ((event: WebSocket.MessageEvent) => void) | null
  921. constructor(address: null)
  922. constructor(
  923. address: string | URL,
  924. options?: WebSocket.ClientOptions | ClientRequestArgs,
  925. )
  926. constructor(
  927. address: string | URL,
  928. protocols?: string | string[],
  929. options?: WebSocket.ClientOptions | ClientRequestArgs,
  930. )
  931. close(code?: number, data?: string | Buffer): void
  932. ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void
  933. pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void
  934. send(data: any, cb?: (err?: Error) => void): void
  935. send(
  936. data: any,
  937. options: {
  938. mask?: boolean | undefined
  939. binary?: boolean | undefined
  940. compress?: boolean | undefined
  941. fin?: boolean | undefined
  942. },
  943. cb?: (err?: Error) => void,
  944. ): void
  945. terminate(): void
  946. /**
  947. * Pause the websocket causing it to stop emitting events. Some events can still be
  948. * emitted after this is called, until all buffered data is consumed. This method
  949. * is a noop if the ready state is `CONNECTING` or `CLOSED`.
  950. */
  951. pause(): void
  952. /**
  953. * Make a paused socket resume emitting events. This method is a noop if the ready
  954. * state is `CONNECTING` or `CLOSED`.
  955. */
  956. resume(): void
  957. // HTML5 WebSocket events
  958. addEventListener(
  959. method: 'message',
  960. cb: (event: WebSocket.MessageEvent) => void,
  961. options?: WebSocket.EventListenerOptions,
  962. ): void
  963. addEventListener(
  964. method: 'close',
  965. cb: (event: WebSocket.CloseEvent) => void,
  966. options?: WebSocket.EventListenerOptions,
  967. ): void
  968. addEventListener(
  969. method: 'error',
  970. cb: (event: WebSocket.ErrorEvent) => void,
  971. options?: WebSocket.EventListenerOptions,
  972. ): void
  973. addEventListener(
  974. method: 'open',
  975. cb: (event: WebSocket.Event) => void,
  976. options?: WebSocket.EventListenerOptions,
  977. ): void
  978. removeEventListener(
  979. method: 'message',
  980. cb: (event: WebSocket.MessageEvent) => void,
  981. ): void
  982. removeEventListener(
  983. method: 'close',
  984. cb: (event: WebSocket.CloseEvent) => void,
  985. ): void
  986. removeEventListener(
  987. method: 'error',
  988. cb: (event: WebSocket.ErrorEvent) => void,
  989. ): void
  990. removeEventListener(
  991. method: 'open',
  992. cb: (event: WebSocket.Event) => void,
  993. ): void
  994. // Events
  995. on(
  996. event: 'close',
  997. listener: (this: WebSocket, code: number, reason: Buffer) => void,
  998. ): this
  999. on(event: 'error', listener: (this: WebSocket, err: Error) => void): this
  1000. on(
  1001. event: 'upgrade',
  1002. listener: (this: WebSocket, request: IncomingMessage) => void,
  1003. ): this
  1004. on(
  1005. event: 'message',
  1006. listener: (
  1007. this: WebSocket,
  1008. data: WebSocket.RawData,
  1009. isBinary: boolean,
  1010. ) => void,
  1011. ): this
  1012. on(event: 'open', listener: (this: WebSocket) => void): this
  1013. on(
  1014. event: 'ping' | 'pong',
  1015. listener: (this: WebSocket, data: Buffer) => void,
  1016. ): this
  1017. on(
  1018. event: 'unexpected-response',
  1019. listener: (
  1020. this: WebSocket,
  1021. request: ClientRequest,
  1022. response: IncomingMessage,
  1023. ) => void,
  1024. ): this
  1025. on(
  1026. event: string | symbol,
  1027. listener: (this: WebSocket, ...args: any[]) => void,
  1028. ): this
  1029. once(
  1030. event: 'close',
  1031. listener: (this: WebSocket, code: number, reason: Buffer) => void,
  1032. ): this
  1033. once(event: 'error', listener: (this: WebSocket, err: Error) => void): this
  1034. once(
  1035. event: 'upgrade',
  1036. listener: (this: WebSocket, request: IncomingMessage) => void,
  1037. ): this
  1038. once(
  1039. event: 'message',
  1040. listener: (
  1041. this: WebSocket,
  1042. data: WebSocket.RawData,
  1043. isBinary: boolean,
  1044. ) => void,
  1045. ): this
  1046. once(event: 'open', listener: (this: WebSocket) => void): this
  1047. once(
  1048. event: 'ping' | 'pong',
  1049. listener: (this: WebSocket, data: Buffer) => void,
  1050. ): this
  1051. once(
  1052. event: 'unexpected-response',
  1053. listener: (
  1054. this: WebSocket,
  1055. request: ClientRequest,
  1056. response: IncomingMessage,
  1057. ) => void,
  1058. ): this
  1059. once(
  1060. event: string | symbol,
  1061. listener: (this: WebSocket, ...args: any[]) => void,
  1062. ): this
  1063. off(
  1064. event: 'close',
  1065. listener: (this: WebSocket, code: number, reason: Buffer) => void,
  1066. ): this
  1067. off(event: 'error', listener: (this: WebSocket, err: Error) => void): this
  1068. off(
  1069. event: 'upgrade',
  1070. listener: (this: WebSocket, request: IncomingMessage) => void,
  1071. ): this
  1072. off(
  1073. event: 'message',
  1074. listener: (
  1075. this: WebSocket,
  1076. data: WebSocket.RawData,
  1077. isBinary: boolean,
  1078. ) => void,
  1079. ): this
  1080. off(event: 'open', listener: (this: WebSocket) => void): this
  1081. off(
  1082. event: 'ping' | 'pong',
  1083. listener: (this: WebSocket, data: Buffer) => void,
  1084. ): this
  1085. off(
  1086. event: 'unexpected-response',
  1087. listener: (
  1088. this: WebSocket,
  1089. request: ClientRequest,
  1090. response: IncomingMessage,
  1091. ) => void,
  1092. ): this
  1093. off(
  1094. event: string | symbol,
  1095. listener: (this: WebSocket, ...args: any[]) => void,
  1096. ): this
  1097. addListener(
  1098. event: 'close',
  1099. listener: (code: number, reason: Buffer) => void,
  1100. ): this
  1101. addListener(event: 'error', listener: (err: Error) => void): this
  1102. addListener(
  1103. event: 'upgrade',
  1104. listener: (request: IncomingMessage) => void,
  1105. ): this
  1106. addListener(
  1107. event: 'message',
  1108. listener: (data: WebSocket.RawData, isBinary: boolean) => void,
  1109. ): this
  1110. addListener(event: 'open', listener: () => void): this
  1111. addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
  1112. addListener(
  1113. event: 'unexpected-response',
  1114. listener: (request: ClientRequest, response: IncomingMessage) => void,
  1115. ): this
  1116. addListener(event: string | symbol, listener: (...args: any[]) => void): this
  1117. removeListener(
  1118. event: 'close',
  1119. listener: (code: number, reason: Buffer) => void,
  1120. ): this
  1121. removeListener(event: 'error', listener: (err: Error) => void): this
  1122. removeListener(
  1123. event: 'upgrade',
  1124. listener: (request: IncomingMessage) => void,
  1125. ): this
  1126. removeListener(
  1127. event: 'message',
  1128. listener: (data: WebSocket.RawData, isBinary: boolean) => void,
  1129. ): this
  1130. removeListener(event: 'open', listener: () => void): this
  1131. removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
  1132. removeListener(
  1133. event: 'unexpected-response',
  1134. listener: (request: ClientRequest, response: IncomingMessage) => void,
  1135. ): this
  1136. removeListener(
  1137. event: string | symbol,
  1138. listener: (...args: any[]) => void,
  1139. ): this
  1140. }
  1141. declare namespace WebSocket {
  1142. /**
  1143. * Data represents the raw message payload received over the WebSocket.
  1144. */
  1145. type RawData = Buffer | ArrayBuffer | Buffer[]
  1146. /**
  1147. * Data represents the message payload received over the WebSocket.
  1148. */
  1149. type Data = string | Buffer | ArrayBuffer | Buffer[]
  1150. /**
  1151. * CertMeta represents the accepted types for certificate & key data.
  1152. */
  1153. type CertMeta = string | string[] | Buffer | Buffer[]
  1154. /**
  1155. * VerifyClientCallbackSync is a synchronous callback used to inspect the
  1156. * incoming message. The return value (boolean) of the function determines
  1157. * whether or not to accept the handshake.
  1158. */
  1159. type VerifyClientCallbackSync = (info: {
  1160. origin: string
  1161. secure: boolean
  1162. req: IncomingMessage
  1163. }) => boolean
  1164. /**
  1165. * VerifyClientCallbackAsync is an asynchronous callback used to inspect the
  1166. * incoming message. The return value (boolean) of the function determines
  1167. * whether or not to accept the handshake.
  1168. */
  1169. type VerifyClientCallbackAsync = (
  1170. info: { origin: string; secure: boolean; req: IncomingMessage },
  1171. callback: (
  1172. res: boolean,
  1173. code?: number,
  1174. message?: string,
  1175. headers?: OutgoingHttpHeaders,
  1176. ) => void,
  1177. ) => void
  1178. interface ClientOptions extends SecureContextOptions {
  1179. protocol?: string | undefined
  1180. followRedirects?: boolean | undefined
  1181. generateMask?(mask: Buffer): void
  1182. handshakeTimeout?: number | undefined
  1183. maxRedirects?: number | undefined
  1184. perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
  1185. localAddress?: string | undefined
  1186. protocolVersion?: number | undefined
  1187. headers?: { [key: string]: string } | undefined
  1188. origin?: string | undefined
  1189. agent?: Agent | undefined
  1190. host?: string | undefined
  1191. family?: number | undefined
  1192. checkServerIdentity?(servername: string, cert: CertMeta): boolean
  1193. rejectUnauthorized?: boolean | undefined
  1194. maxPayload?: number | undefined
  1195. skipUTF8Validation?: boolean | undefined
  1196. }
  1197. interface PerMessageDeflateOptions {
  1198. serverNoContextTakeover?: boolean | undefined
  1199. clientNoContextTakeover?: boolean | undefined
  1200. serverMaxWindowBits?: number | undefined
  1201. clientMaxWindowBits?: number | undefined
  1202. zlibDeflateOptions?:
  1203. | {
  1204. flush?: number | undefined
  1205. finishFlush?: number | undefined
  1206. chunkSize?: number | undefined
  1207. windowBits?: number | undefined
  1208. level?: number | undefined
  1209. memLevel?: number | undefined
  1210. strategy?: number | undefined
  1211. dictionary?: Buffer | Buffer[] | DataView | undefined
  1212. info?: boolean | undefined
  1213. }
  1214. | undefined
  1215. zlibInflateOptions?: ZlibOptions | undefined
  1216. threshold?: number | undefined
  1217. concurrencyLimit?: number | undefined
  1218. }
  1219. interface Event {
  1220. type: string
  1221. target: WebSocket
  1222. }
  1223. interface ErrorEvent {
  1224. error: any
  1225. message: string
  1226. type: string
  1227. target: WebSocket
  1228. }
  1229. interface CloseEvent {
  1230. wasClean: boolean
  1231. code: number
  1232. reason: string
  1233. type: string
  1234. target: WebSocket
  1235. }
  1236. interface MessageEvent {
  1237. data: Data
  1238. type: string
  1239. target: WebSocket
  1240. }
  1241. interface EventListenerOptions {
  1242. once?: boolean | undefined
  1243. }
  1244. interface ServerOptions {
  1245. host?: string | undefined
  1246. port?: number | undefined
  1247. backlog?: number | undefined
  1248. server?: Server | HttpsServer | undefined
  1249. verifyClient?:
  1250. | VerifyClientCallbackAsync
  1251. | VerifyClientCallbackSync
  1252. | undefined
  1253. handleProtocols?: (
  1254. protocols: Set<string>,
  1255. request: IncomingMessage,
  1256. ) => string | false
  1257. path?: string | undefined
  1258. noServer?: boolean | undefined
  1259. clientTracking?: boolean | undefined
  1260. perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
  1261. maxPayload?: number | undefined
  1262. skipUTF8Validation?: boolean | undefined
  1263. WebSocket?: typeof WebSocket.WebSocket | undefined
  1264. }
  1265. interface AddressInfo {
  1266. address: string
  1267. family: string
  1268. port: number
  1269. }
  1270. // WebSocket Server
  1271. class Server<T extends WebSocket = WebSocket> extends EventEmitter {
  1272. options: ServerOptions
  1273. path: string
  1274. clients: Set<T>
  1275. constructor(options?: ServerOptions, callback?: () => void)
  1276. address(): AddressInfo | string
  1277. close(cb?: (err?: Error) => void): void
  1278. handleUpgrade(
  1279. request: IncomingMessage,
  1280. socket: Duplex,
  1281. upgradeHead: Buffer,
  1282. callback: (client: T, request: IncomingMessage) => void,
  1283. ): void
  1284. shouldHandle(request: IncomingMessage): boolean | Promise<boolean>
  1285. // Events
  1286. on(
  1287. event: 'connection',
  1288. cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
  1289. ): this
  1290. on(event: 'error', cb: (this: Server<T>, error: Error) => void): this
  1291. on(
  1292. event: 'headers',
  1293. cb: (
  1294. this: Server<T>,
  1295. headers: string[],
  1296. request: IncomingMessage,
  1297. ) => void,
  1298. ): this
  1299. on(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
  1300. on(
  1301. event: string | symbol,
  1302. listener: (this: Server<T>, ...args: any[]) => void,
  1303. ): this
  1304. once(
  1305. event: 'connection',
  1306. cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
  1307. ): this
  1308. once(event: 'error', cb: (this: Server<T>, error: Error) => void): this
  1309. once(
  1310. event: 'headers',
  1311. cb: (
  1312. this: Server<T>,
  1313. headers: string[],
  1314. request: IncomingMessage,
  1315. ) => void,
  1316. ): this
  1317. once(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
  1318. once(
  1319. event: string | symbol,
  1320. listener: (this: Server<T>, ...args: any[]) => void,
  1321. ): this
  1322. off(
  1323. event: 'connection',
  1324. cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
  1325. ): this
  1326. off(event: 'error', cb: (this: Server<T>, error: Error) => void): this
  1327. off(
  1328. event: 'headers',
  1329. cb: (
  1330. this: Server<T>,
  1331. headers: string[],
  1332. request: IncomingMessage,
  1333. ) => void,
  1334. ): this
  1335. off(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
  1336. off(
  1337. event: string | symbol,
  1338. listener: (this: Server<T>, ...args: any[]) => void,
  1339. ): this
  1340. addListener(
  1341. event: 'connection',
  1342. cb: (client: T, request: IncomingMessage) => void,
  1343. ): this
  1344. addListener(event: 'error', cb: (err: Error) => void): this
  1345. addListener(
  1346. event: 'headers',
  1347. cb: (headers: string[], request: IncomingMessage) => void,
  1348. ): this
  1349. addListener(event: 'close' | 'listening', cb: () => void): this
  1350. addListener(
  1351. event: string | symbol,
  1352. listener: (...args: any[]) => void,
  1353. ): this
  1354. removeListener(event: 'connection', cb: (client: T) => void): this
  1355. removeListener(event: 'error', cb: (err: Error) => void): this
  1356. removeListener(
  1357. event: 'headers',
  1358. cb: (headers: string[], request: IncomingMessage) => void,
  1359. ): this
  1360. removeListener(event: 'close' | 'listening', cb: () => void): this
  1361. removeListener(
  1362. event: string | symbol,
  1363. listener: (...args: any[]) => void,
  1364. ): this
  1365. }
  1366. const WebSocketServer: typeof Server
  1367. interface WebSocketServer extends Server {}
  1368. const WebSocket: typeof WebSocketAlias
  1369. interface WebSocket extends WebSocketAlias {}
  1370. // WebSocket stream
  1371. function createWebSocketStream(
  1372. websocket: WebSocket,
  1373. options?: DuplexOptions,
  1374. ): Duplex
  1375. }
  1376. interface HmrOptions {
  1377. protocol?: string;
  1378. host?: string;
  1379. port?: number;
  1380. clientPort?: number;
  1381. path?: string;
  1382. timeout?: number;
  1383. overlay?: boolean;
  1384. server?: HttpServer;
  1385. }
  1386. interface HmrContext {
  1387. file: string;
  1388. timestamp: number;
  1389. modules: Array<ModuleNode>;
  1390. read: () => string | Promise<string>;
  1391. server: ViteDevServer;
  1392. }
  1393. interface HMRBroadcasterClient {
  1394. /**
  1395. * Send event to the client
  1396. */
  1397. send(payload: HMRPayload): void;
  1398. /**
  1399. * Send custom event
  1400. */
  1401. send(event: string, payload?: CustomPayload['data']): void;
  1402. }
  1403. interface HMRChannel {
  1404. /**
  1405. * Unique channel name
  1406. */
  1407. name: string;
  1408. /**
  1409. * Broadcast events to all clients
  1410. */
  1411. send(payload: HMRPayload): void;
  1412. /**
  1413. * Send custom event
  1414. */
  1415. send<T extends string>(event: T, payload?: InferCustomEventPayload<T>): void;
  1416. /**
  1417. * Handle custom event emitted by `import.meta.hot.send`
  1418. */
  1419. on<T extends string>(event: T, listener: (data: InferCustomEventPayload<T>, client: HMRBroadcasterClient, ...args: any[]) => void): void;
  1420. on(event: 'connection', listener: () => void): void;
  1421. /**
  1422. * Unregister event listener
  1423. */
  1424. off(event: string, listener: Function): void;
  1425. /**
  1426. * Start listening for messages
  1427. */
  1428. listen(): void;
  1429. /**
  1430. * Disconnect all clients, called when server is closed or restarted.
  1431. */
  1432. close(): void;
  1433. }
  1434. interface HMRBroadcaster extends Omit<HMRChannel, 'close' | 'name'> {
  1435. /**
  1436. * All registered channels. Always has websocket channel.
  1437. */
  1438. readonly channels: HMRChannel[];
  1439. /**
  1440. * Add a new third-party channel.
  1441. */
  1442. addChannel(connection: HMRChannel): HMRBroadcaster;
  1443. close(): Promise<unknown[]>;
  1444. }
  1445. interface ServerHMRChannel extends HMRChannel {
  1446. api: {
  1447. innerEmitter: EventEmitter;
  1448. outsideEmitter: EventEmitter;
  1449. };
  1450. }
  1451. type WebSocketCustomListener<T> = (data: T, client: WebSocketClient) => void;
  1452. interface WebSocketServer extends HMRChannel {
  1453. /**
  1454. * Listen on port and host
  1455. */
  1456. listen(): void;
  1457. /**
  1458. * Get all connected clients.
  1459. */
  1460. clients: Set<WebSocketClient>;
  1461. /**
  1462. * Disconnect all clients and terminate the server.
  1463. */
  1464. close(): Promise<void>;
  1465. /**
  1466. * Handle custom event emitted by `import.meta.hot.send`
  1467. */
  1468. on: WebSocket.Server['on'] & {
  1469. <T extends string>(event: T, listener: WebSocketCustomListener<InferCustomEventPayload<T>>): void;
  1470. };
  1471. /**
  1472. * Unregister event listener.
  1473. */
  1474. off: WebSocket.Server['off'] & {
  1475. (event: string, listener: Function): void;
  1476. };
  1477. }
  1478. interface WebSocketClient {
  1479. /**
  1480. * Send event to the client
  1481. */
  1482. send(payload: HMRPayload): void;
  1483. /**
  1484. * Send custom event
  1485. */
  1486. send(event: string, payload?: CustomPayload['data']): void;
  1487. /**
  1488. * The raw WebSocket instance
  1489. * @advanced
  1490. */
  1491. socket: WebSocket;
  1492. }
  1493. interface ServerOptions extends CommonServerOptions {
  1494. /**
  1495. * Configure HMR-specific options (port, host, path & protocol)
  1496. */
  1497. hmr?: HmrOptions | boolean;
  1498. /**
  1499. * Do not start the websocket connection.
  1500. * @experimental
  1501. */
  1502. ws?: false;
  1503. /**
  1504. * Warm-up files to transform and cache the results in advance. This improves the
  1505. * initial page load during server starts and prevents transform waterfalls.
  1506. */
  1507. warmup?: {
  1508. /**
  1509. * The files to be transformed and used on the client-side. Supports glob patterns.
  1510. */
  1511. clientFiles?: string[];
  1512. /**
  1513. * The files to be transformed and used in SSR. Supports glob patterns.
  1514. */
  1515. ssrFiles?: string[];
  1516. };
  1517. /**
  1518. * chokidar watch options or null to disable FS watching
  1519. * https://github.com/paulmillr/chokidar#api
  1520. */
  1521. watch?: WatchOptions | null;
  1522. /**
  1523. * Create Vite dev server to be used as a middleware in an existing server
  1524. * @default false
  1525. */
  1526. middlewareMode?: boolean | {
  1527. /**
  1528. * Parent server instance to attach to
  1529. *
  1530. * This is needed to proxy WebSocket connections to the parent server.
  1531. */
  1532. server: HttpServer;
  1533. };
  1534. /**
  1535. * Options for files served via '/\@fs/'.
  1536. */
  1537. fs?: FileSystemServeOptions;
  1538. /**
  1539. * Origin for the generated asset URLs.
  1540. *
  1541. * @example `http://127.0.0.1:8080`
  1542. */
  1543. origin?: string;
  1544. /**
  1545. * Pre-transform known direct imports
  1546. * @default true
  1547. */
  1548. preTransformRequests?: boolean;
  1549. /**
  1550. * Whether or not to ignore-list source files in the dev server sourcemap, used to populate
  1551. * the [`x_google_ignoreList` source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension).
  1552. *
  1553. * By default, it excludes all paths containing `node_modules`. You can pass `false` to
  1554. * disable this behavior, or, for full control, a function that takes the source path and
  1555. * sourcemap path and returns whether to ignore the source path.
  1556. */
  1557. sourcemapIgnoreList?: false | ((sourcePath: string, sourcemapPath: string) => boolean);
  1558. }
  1559. interface ResolvedServerOptions extends Omit<ServerOptions, 'fs' | 'middlewareMode' | 'sourcemapIgnoreList'> {
  1560. fs: Required<FileSystemServeOptions>;
  1561. middlewareMode: NonNullable<ServerOptions['middlewareMode']>;
  1562. sourcemapIgnoreList: Exclude<ServerOptions['sourcemapIgnoreList'], false | undefined>;
  1563. }
  1564. interface FileSystemServeOptions {
  1565. /**
  1566. * Strictly restrict file accessing outside of allowing paths.
  1567. *
  1568. * Set to `false` to disable the warning
  1569. *
  1570. * @default true
  1571. */
  1572. strict?: boolean;
  1573. /**
  1574. * Restrict accessing files outside the allowed directories.
  1575. *
  1576. * Accepts absolute path or a path relative to project root.
  1577. * Will try to search up for workspace root by default.
  1578. */
  1579. allow?: string[];
  1580. /**
  1581. * Restrict accessing files that matches the patterns.
  1582. *
  1583. * This will have higher priority than `allow`.
  1584. * picomatch patterns are supported.
  1585. *
  1586. * @default ['.env', '.env.*', '*.crt', '*.pem']
  1587. */
  1588. deny?: string[];
  1589. /**
  1590. * Enable caching of fs calls. It is enabled by default if no custom watch ignored patterns are provided.
  1591. *
  1592. * @experimental
  1593. * @default undefined
  1594. */
  1595. cachedChecks?: boolean;
  1596. }
  1597. type ServerHook = (this: void, server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>;
  1598. type HttpServer = http.Server | Http2SecureServer;
  1599. interface ViteDevServer {
  1600. /**
  1601. * The resolved vite config object
  1602. */
  1603. config: ResolvedConfig;
  1604. /**
  1605. * A connect app instance.
  1606. * - Can be used to attach custom middlewares to the dev server.
  1607. * - Can also be used as the handler function of a custom http server
  1608. * or as a middleware in any connect-style Node.js frameworks
  1609. *
  1610. * https://github.com/senchalabs/connect#use-middleware
  1611. */
  1612. middlewares: Connect.Server;
  1613. /**
  1614. * native Node http server instance
  1615. * will be null in middleware mode
  1616. */
  1617. httpServer: HttpServer | null;
  1618. /**
  1619. * chokidar watcher instance
  1620. * https://github.com/paulmillr/chokidar#api
  1621. */
  1622. watcher: FSWatcher;
  1623. /**
  1624. * web socket server with `send(payload)` method
  1625. */
  1626. ws: WebSocketServer;
  1627. /**
  1628. * HMR broadcaster that can be used to send custom HMR messages to the client
  1629. *
  1630. * Always sends a message to at least a WebSocket client. Any third party can
  1631. * add a channel to the broadcaster to process messages
  1632. * @deprecated will be replaced with the environment api in v6.
  1633. */
  1634. hot: HMRBroadcaster;
  1635. /**
  1636. * Rollup plugin container that can run plugin hooks on a given file
  1637. */
  1638. pluginContainer: PluginContainer;
  1639. /**
  1640. * Module graph that tracks the import relationships, url to file mapping
  1641. * and hmr state.
  1642. */
  1643. moduleGraph: ModuleGraph;
  1644. /**
  1645. * The resolved urls Vite prints on the CLI. null in middleware mode or
  1646. * before `server.listen` is called.
  1647. */
  1648. resolvedUrls: ResolvedServerUrls | null;
  1649. /**
  1650. * Programmatically resolve, load and transform a URL and get the result
  1651. * without going through the http request pipeline.
  1652. */
  1653. transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null>;
  1654. /**
  1655. * Same as `transformRequest` but only warm up the URLs so the next request
  1656. * will already be cached. The function will never throw as it handles and
  1657. * reports errors internally.
  1658. */
  1659. warmupRequest(url: string, options?: TransformOptions): Promise<void>;
  1660. /**
  1661. * Apply vite built-in HTML transforms and any plugin HTML transforms.
  1662. */
  1663. transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string>;
  1664. /**
  1665. * Transform module code into SSR format.
  1666. */
  1667. ssrTransform(code: string, inMap: SourceMap | {
  1668. mappings: '';
  1669. } | null, url: string, originalCode?: string): Promise<TransformResult | null>;
  1670. /**
  1671. * Load a given URL as an instantiated module for SSR.
  1672. */
  1673. ssrLoadModule(url: string, opts?: {
  1674. fixStacktrace?: boolean;
  1675. }): Promise<Record<string, any>>;
  1676. /**
  1677. * Fetch information about the module for Vite SSR runtime.
  1678. * @experimental
  1679. */
  1680. ssrFetchModule(id: string, importer?: string): Promise<FetchResult>;
  1681. /**
  1682. * Returns a fixed version of the given stack
  1683. */
  1684. ssrRewriteStacktrace(stack: string): string;
  1685. /**
  1686. * Mutates the given SSR error by rewriting the stacktrace
  1687. */
  1688. ssrFixStacktrace(e: Error): void;
  1689. /**
  1690. * Triggers HMR for a module in the module graph. You can use the `server.moduleGraph`
  1691. * API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op.
  1692. */
  1693. reloadModule(module: ModuleNode): Promise<void>;
  1694. /**
  1695. * Start the server.
  1696. */
  1697. listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>;
  1698. /**
  1699. * Stop the server.
  1700. */
  1701. close(): Promise<void>;
  1702. /**
  1703. * Print server urls
  1704. */
  1705. printUrls(): void;
  1706. /**
  1707. * Bind CLI shortcuts
  1708. */
  1709. bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void;
  1710. /**
  1711. * Restart the server.
  1712. *
  1713. * @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
  1714. */
  1715. restart(forceOptimize?: boolean): Promise<void>;
  1716. /**
  1717. * Open browser
  1718. */
  1719. openBrowser(): void;
  1720. /**
  1721. * Calling `await server.waitForRequestsIdle(id)` will wait until all static imports
  1722. * are processed. If called from a load or transform plugin hook, the id needs to be
  1723. * passed as a parameter to avoid deadlocks. Calling this function after the first
  1724. * static imports section of the module graph has been processed will resolve immediately.
  1725. * @experimental
  1726. */
  1727. waitForRequestsIdle: (ignoredId?: string) => Promise<void>;
  1728. }
  1729. interface ResolvedServerUrls {
  1730. local: string[];
  1731. network: string[];
  1732. }
  1733. declare function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>;
  1734. /** Cache for package.json resolution and package.json contents */
  1735. type PackageCache = Map<string, PackageData>;
  1736. interface PackageData {
  1737. dir: string;
  1738. hasSideEffects: (id: string) => boolean | 'no-treeshake' | null;
  1739. webResolvedImports: Record<string, string | undefined>;
  1740. nodeResolvedImports: Record<string, string | undefined>;
  1741. setResolvedCache: (key: string, entry: string, targetWeb: boolean) => void;
  1742. getResolvedCache: (key: string, targetWeb: boolean) => string | undefined;
  1743. data: {
  1744. [field: string]: any;
  1745. name: string;
  1746. type: string;
  1747. version: string;
  1748. main: string;
  1749. module: string;
  1750. browser: string | Record<string, string | false>;
  1751. exports: string | Record<string, any> | string[];
  1752. imports: Record<string, any>;
  1753. dependencies: Record<string, string>;
  1754. };
  1755. }
  1756. interface RollupCommonJSOptions {
  1757. /**
  1758. * A minimatch pattern, or array of patterns, which specifies the files in
  1759. * the build the plugin should operate on. By default, all files with
  1760. * extension `".cjs"` or those in `extensions` are included, but you can
  1761. * narrow this list by only including specific files. These files will be
  1762. * analyzed and transpiled if either the analysis does not find ES module
  1763. * specific statements or `transformMixedEsModules` is `true`.
  1764. * @default undefined
  1765. */
  1766. include?: string | RegExp | readonly (string | RegExp)[]
  1767. /**
  1768. * A minimatch pattern, or array of patterns, which specifies the files in
  1769. * the build the plugin should _ignore_. By default, all files with
  1770. * extensions other than those in `extensions` or `".cjs"` are ignored, but you
  1771. * can exclude additional files. See also the `include` option.
  1772. * @default undefined
  1773. */
  1774. exclude?: string | RegExp | readonly (string | RegExp)[]
  1775. /**
  1776. * For extensionless imports, search for extensions other than .js in the
  1777. * order specified. Note that you need to make sure that non-JavaScript files
  1778. * are transpiled by another plugin first.
  1779. * @default [ '.js' ]
  1780. */
  1781. extensions?: ReadonlyArray<string>
  1782. /**
  1783. * If true then uses of `global` won't be dealt with by this plugin
  1784. * @default false
  1785. */
  1786. ignoreGlobal?: boolean
  1787. /**
  1788. * If false, skips source map generation for CommonJS modules. This will
  1789. * improve performance.
  1790. * @default true
  1791. */
  1792. sourceMap?: boolean
  1793. /**
  1794. * Some `require` calls cannot be resolved statically to be translated to
  1795. * imports.
  1796. * When this option is set to `false`, the generated code will either
  1797. * directly throw an error when such a call is encountered or, when
  1798. * `dynamicRequireTargets` is used, when such a call cannot be resolved with a
  1799. * configured dynamic require target.
  1800. * Setting this option to `true` will instead leave the `require` call in the
  1801. * code or use it as a fallback for `dynamicRequireTargets`.
  1802. * @default false
  1803. */
  1804. ignoreDynamicRequires?: boolean
  1805. /**
  1806. * Instructs the plugin whether to enable mixed module transformations. This
  1807. * is useful in scenarios with modules that contain a mix of ES `import`
  1808. * statements and CommonJS `require` expressions. Set to `true` if `require`
  1809. * calls should be transformed to imports in mixed modules, or `false` if the
  1810. * `require` expressions should survive the transformation. The latter can be
  1811. * important if the code contains environment detection, or you are coding
  1812. * for an environment with special treatment for `require` calls such as
  1813. * ElectronJS. See also the `ignore` option.
  1814. * @default false
  1815. */
  1816. transformMixedEsModules?: boolean
  1817. /**
  1818. * By default, this plugin will try to hoist `require` statements as imports
  1819. * to the top of each file. While this works well for many code bases and
  1820. * allows for very efficient ESM output, it does not perfectly capture
  1821. * CommonJS semantics as the order of side effects like log statements may
  1822. * change. But it is especially problematic when there are circular `require`
  1823. * calls between CommonJS modules as those often rely on the lazy execution of
  1824. * nested `require` calls.
  1825. *
  1826. * Setting this option to `true` will wrap all CommonJS files in functions
  1827. * which are executed when they are required for the first time, preserving
  1828. * NodeJS semantics. Note that this can have an impact on the size and
  1829. * performance of the generated code.
  1830. *
  1831. * The default value of `"auto"` will only wrap CommonJS files when they are
  1832. * part of a CommonJS dependency cycle, e.g. an index file that is required by
  1833. * many of its dependencies. All other CommonJS files are hoisted. This is the
  1834. * recommended setting for most code bases.
  1835. *
  1836. * `false` will entirely prevent wrapping and hoist all files. This may still
  1837. * work depending on the nature of cyclic dependencies but will often cause
  1838. * problems.
  1839. *
  1840. * You can also provide a minimatch pattern, or array of patterns, to only
  1841. * specify a subset of files which should be wrapped in functions for proper
  1842. * `require` semantics.
  1843. *
  1844. * `"debug"` works like `"auto"` but after bundling, it will display a warning
  1845. * containing a list of ids that have been wrapped which can be used as
  1846. * minimatch pattern for fine-tuning.
  1847. * @default "auto"
  1848. */
  1849. strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[]
  1850. /**
  1851. * Sometimes you have to leave require statements unconverted. Pass an array
  1852. * containing the IDs or a `id => boolean` function.
  1853. * @default []
  1854. */
  1855. ignore?: ReadonlyArray<string> | ((id: string) => boolean)
  1856. /**
  1857. * In most cases, where `require` calls are inside a `try-catch` clause,
  1858. * they should be left unconverted as it requires an optional dependency
  1859. * that may or may not be installed beside the rolled up package.
  1860. * Due to the conversion of `require` to a static `import` - the call is
  1861. * hoisted to the top of the file, outside the `try-catch` clause.
  1862. *
  1863. * - `true`: Default. All `require` calls inside a `try` will be left unconverted.
  1864. * - `false`: All `require` calls inside a `try` will be converted as if the
  1865. * `try-catch` clause is not there.
  1866. * - `remove`: Remove all `require` calls from inside any `try` block.
  1867. * - `string[]`: Pass an array containing the IDs to left unconverted.
  1868. * - `((id: string) => boolean|'remove')`: Pass a function that controls
  1869. * individual IDs.
  1870. *
  1871. * @default true
  1872. */
  1873. ignoreTryCatch?:
  1874. | boolean
  1875. | 'remove'
  1876. | ReadonlyArray<string>
  1877. | ((id: string) => boolean | 'remove')
  1878. /**
  1879. * Controls how to render imports from external dependencies. By default,
  1880. * this plugin assumes that all external dependencies are CommonJS. This
  1881. * means they are rendered as default imports to be compatible with e.g.
  1882. * NodeJS where ES modules can only import a default export from a CommonJS
  1883. * dependency.
  1884. *
  1885. * If you set `esmExternals` to `true`, this plugin assumes that all
  1886. * external dependencies are ES modules and respect the
  1887. * `requireReturnsDefault` option. If that option is not set, they will be
  1888. * rendered as namespace imports.
  1889. *
  1890. * You can also supply an array of ids to be treated as ES modules, or a
  1891. * function that will be passed each external id to determine whether it is
  1892. * an ES module.
  1893. * @default false
  1894. */
  1895. esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean)
  1896. /**
  1897. * Controls what is returned when requiring an ES module from a CommonJS file.
  1898. * When using the `esmExternals` option, this will also apply to external
  1899. * modules. By default, this plugin will render those imports as namespace
  1900. * imports i.e.
  1901. *
  1902. * ```js
  1903. * // input
  1904. * const foo = require('foo');
  1905. *
  1906. * // output
  1907. * import * as foo from 'foo';
  1908. * ```
  1909. *
  1910. * However, there are some situations where this may not be desired.
  1911. * For these situations, you can change Rollup's behaviour either globally or
  1912. * per module. To change it globally, set the `requireReturnsDefault` option
  1913. * to one of the following values:
  1914. *
  1915. * - `false`: This is the default, requiring an ES module returns its
  1916. * namespace. This is the only option that will also add a marker
  1917. * `__esModule: true` to the namespace to support interop patterns in
  1918. * CommonJS modules that are transpiled ES modules.
  1919. * - `"namespace"`: Like `false`, requiring an ES module returns its
  1920. * namespace, but the plugin does not add the `__esModule` marker and thus
  1921. * creates more efficient code. For external dependencies when using
  1922. * `esmExternals: true`, no additional interop code is generated.
  1923. * - `"auto"`: This is complementary to how `output.exports: "auto"` works in
  1924. * Rollup: If a module has a default export and no named exports, requiring
  1925. * that module returns the default export. In all other cases, the namespace
  1926. * is returned. For external dependencies when using `esmExternals: true`, a
  1927. * corresponding interop helper is added.
  1928. * - `"preferred"`: If a module has a default export, requiring that module
  1929. * always returns the default export, no matter whether additional named
  1930. * exports exist. This is similar to how previous versions of this plugin
  1931. * worked. Again for external dependencies when using `esmExternals: true`,
  1932. * an interop helper is added.
  1933. * - `true`: This will always try to return the default export on require
  1934. * without checking if it actually exists. This can throw at build time if
  1935. * there is no default export. This is how external dependencies are handled
  1936. * when `esmExternals` is not used. The advantage over the other options is
  1937. * that, like `false`, this does not add an interop helper for external
  1938. * dependencies, keeping the code lean.
  1939. *
  1940. * To change this for individual modules, you can supply a function for
  1941. * `requireReturnsDefault` instead. This function will then be called once for
  1942. * each required ES module or external dependency with the corresponding id
  1943. * and allows you to return different values for different modules.
  1944. * @default false
  1945. */
  1946. requireReturnsDefault?:
  1947. | boolean
  1948. | 'auto'
  1949. | 'preferred'
  1950. | 'namespace'
  1951. | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace')
  1952. /**
  1953. * @default "auto"
  1954. */
  1955. defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto')
  1956. /**
  1957. * Some modules contain dynamic `require` calls, or require modules that
  1958. * contain circular dependencies, which are not handled well by static
  1959. * imports. Including those modules as `dynamicRequireTargets` will simulate a
  1960. * CommonJS (NodeJS-like) environment for them with support for dynamic
  1961. * dependencies. It also enables `strictRequires` for those modules.
  1962. *
  1963. * Note: In extreme cases, this feature may result in some paths being
  1964. * rendered as absolute in the final bundle. The plugin tries to avoid
  1965. * exposing paths from the local machine, but if you are `dynamicRequirePaths`
  1966. * with paths that are far away from your project's folder, that may require
  1967. * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`.
  1968. */
  1969. dynamicRequireTargets?: string | ReadonlyArray<string>
  1970. /**
  1971. * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory
  1972. * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/`
  1973. * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your
  1974. * home directory name. By default, it uses the current working directory.
  1975. */
  1976. dynamicRequireRoot?: string
  1977. }
  1978. interface RollupDynamicImportVarsOptions {
  1979. /**
  1980. * Files to include in this plugin (default all).
  1981. * @default []
  1982. */
  1983. include?: string | RegExp | (string | RegExp)[]
  1984. /**
  1985. * Files to exclude in this plugin (default none).
  1986. * @default []
  1987. */
  1988. exclude?: string | RegExp | (string | RegExp)[]
  1989. /**
  1990. * By default, the plugin quits the build process when it encounters an error. If you set this option to true, it will throw a warning instead and leave the code untouched.
  1991. * @default false
  1992. */
  1993. warnOnError?: boolean
  1994. }
  1995. // Modified and inlined to avoid extra dependency
  1996. // Source: https://github.com/terser/terser/blob/master/tools/terser.d.ts
  1997. // BSD Licensed https://github.com/terser/terser/blob/master/LICENSE
  1998. declare namespace Terser {
  1999. export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020
  2000. export type ConsoleProperty = keyof typeof console
  2001. type DropConsoleOption = boolean | ConsoleProperty[]
  2002. export interface ParseOptions {
  2003. bare_returns?: boolean
  2004. /** @deprecated legacy option. Currently, all supported EcmaScript is valid to parse. */
  2005. ecma?: ECMA
  2006. html5_comments?: boolean
  2007. shebang?: boolean
  2008. }
  2009. export interface CompressOptions {
  2010. arguments?: boolean
  2011. arrows?: boolean
  2012. booleans_as_integers?: boolean
  2013. booleans?: boolean
  2014. collapse_vars?: boolean
  2015. comparisons?: boolean
  2016. computed_props?: boolean
  2017. conditionals?: boolean
  2018. dead_code?: boolean
  2019. defaults?: boolean
  2020. directives?: boolean
  2021. drop_console?: DropConsoleOption
  2022. drop_debugger?: boolean
  2023. ecma?: ECMA
  2024. evaluate?: boolean
  2025. expression?: boolean
  2026. global_defs?: object
  2027. hoist_funs?: boolean
  2028. hoist_props?: boolean
  2029. hoist_vars?: boolean
  2030. ie8?: boolean
  2031. if_return?: boolean
  2032. inline?: boolean | InlineFunctions
  2033. join_vars?: boolean
  2034. keep_classnames?: boolean | RegExp
  2035. keep_fargs?: boolean
  2036. keep_fnames?: boolean | RegExp
  2037. keep_infinity?: boolean
  2038. loops?: boolean
  2039. module?: boolean
  2040. negate_iife?: boolean
  2041. passes?: number
  2042. properties?: boolean
  2043. pure_funcs?: string[]
  2044. pure_new?: boolean
  2045. pure_getters?: boolean | 'strict'
  2046. reduce_funcs?: boolean
  2047. reduce_vars?: boolean
  2048. sequences?: boolean | number
  2049. side_effects?: boolean
  2050. switches?: boolean
  2051. toplevel?: boolean
  2052. top_retain?: null | string | string[] | RegExp
  2053. typeofs?: boolean
  2054. unsafe_arrows?: boolean
  2055. unsafe?: boolean
  2056. unsafe_comps?: boolean
  2057. unsafe_Function?: boolean
  2058. unsafe_math?: boolean
  2059. unsafe_symbols?: boolean
  2060. unsafe_methods?: boolean
  2061. unsafe_proto?: boolean
  2062. unsafe_regexp?: boolean
  2063. unsafe_undefined?: boolean
  2064. unused?: boolean
  2065. }
  2066. export enum InlineFunctions {
  2067. Disabled = 0,
  2068. SimpleFunctions = 1,
  2069. WithArguments = 2,
  2070. WithArgumentsAndVariables = 3,
  2071. }
  2072. export interface MangleOptions {
  2073. eval?: boolean
  2074. keep_classnames?: boolean | RegExp
  2075. keep_fnames?: boolean | RegExp
  2076. module?: boolean
  2077. nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
  2078. properties?: boolean | ManglePropertiesOptions
  2079. reserved?: string[]
  2080. safari10?: boolean
  2081. toplevel?: boolean
  2082. }
  2083. /**
  2084. * An identifier mangler for which the output is invariant with respect to the source code.
  2085. */
  2086. export interface SimpleIdentifierMangler {
  2087. /**
  2088. * Obtains the nth most favored (usually shortest) identifier to rename a variable to.
  2089. * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word.
  2090. * This function is expected to be stable; Evaluating get(n) === get(n) should always return true.
  2091. * @param n The ordinal of the identifier.
  2092. */
  2093. get(n: number): string
  2094. }
  2095. /**
  2096. * An identifier mangler that leverages character frequency analysis to determine identifier precedence.
  2097. */
  2098. export interface WeightedIdentifierMangler extends SimpleIdentifierMangler {
  2099. /**
  2100. * Modifies the internal weighting of the input characters by the specified delta.
  2101. * Will be invoked on the entire printed AST, and then deduct mangleable identifiers.
  2102. * @param chars The characters to modify the weighting of.
  2103. * @param delta The numeric weight to add to the characters.
  2104. */
  2105. consider(chars: string, delta: number): number
  2106. /**
  2107. * Resets character weights.
  2108. */
  2109. reset(): void
  2110. /**
  2111. * Sorts identifiers by character frequency, in preparation for calls to get(n).
  2112. */
  2113. sort(): void
  2114. }
  2115. export interface ManglePropertiesOptions {
  2116. builtins?: boolean
  2117. debug?: boolean
  2118. keep_quoted?: boolean | 'strict'
  2119. nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
  2120. regex?: RegExp | string
  2121. reserved?: string[]
  2122. }
  2123. export interface FormatOptions {
  2124. ascii_only?: boolean
  2125. /** @deprecated Not implemented anymore */
  2126. beautify?: boolean
  2127. braces?: boolean
  2128. comments?:
  2129. | boolean
  2130. | 'all'
  2131. | 'some'
  2132. | RegExp
  2133. | ((
  2134. node: any,
  2135. comment: {
  2136. value: string
  2137. type: 'comment1' | 'comment2' | 'comment3' | 'comment4'
  2138. pos: number
  2139. line: number
  2140. col: number
  2141. },
  2142. ) => boolean)
  2143. ecma?: ECMA
  2144. ie8?: boolean
  2145. keep_numbers?: boolean
  2146. indent_level?: number
  2147. indent_start?: number
  2148. inline_script?: boolean
  2149. keep_quoted_props?: boolean
  2150. max_line_len?: number | false
  2151. preamble?: string
  2152. preserve_annotations?: boolean
  2153. quote_keys?: boolean
  2154. quote_style?: OutputQuoteStyle
  2155. safari10?: boolean
  2156. semicolons?: boolean
  2157. shebang?: boolean
  2158. shorthand?: boolean
  2159. source_map?: SourceMapOptions
  2160. webkit?: boolean
  2161. width?: number
  2162. wrap_iife?: boolean
  2163. wrap_func_args?: boolean
  2164. }
  2165. export enum OutputQuoteStyle {
  2166. PreferDouble = 0,
  2167. AlwaysSingle = 1,
  2168. AlwaysDouble = 2,
  2169. AlwaysOriginal = 3,
  2170. }
  2171. export interface MinifyOptions {
  2172. compress?: boolean | CompressOptions
  2173. ecma?: ECMA
  2174. enclose?: boolean | string
  2175. ie8?: boolean
  2176. keep_classnames?: boolean | RegExp
  2177. keep_fnames?: boolean | RegExp
  2178. mangle?: boolean | MangleOptions
  2179. module?: boolean
  2180. nameCache?: object
  2181. format?: FormatOptions
  2182. /** @deprecated */
  2183. output?: FormatOptions
  2184. parse?: ParseOptions
  2185. safari10?: boolean
  2186. sourceMap?: boolean | SourceMapOptions
  2187. toplevel?: boolean
  2188. }
  2189. export interface MinifyOutput {
  2190. code?: string
  2191. map?: object | string
  2192. decoded_map?: object | null
  2193. }
  2194. export interface SourceMapOptions {
  2195. /** Source map object, 'inline' or source map file content */
  2196. content?: object | string
  2197. includeSources?: boolean
  2198. filename?: string
  2199. root?: string
  2200. asObject?: boolean
  2201. url?: string | 'inline'
  2202. }
  2203. }
  2204. interface TerserOptions extends Terser.MinifyOptions {
  2205. /**
  2206. * Vite-specific option to specify the max number of workers to spawn
  2207. * when minifying files with terser.
  2208. *
  2209. * @default number of CPUs minus 1
  2210. */
  2211. maxWorkers?: number;
  2212. }
  2213. interface BuildOptions {
  2214. /**
  2215. * Compatibility transform target. The transform is performed with esbuild
  2216. * and the lowest supported target is es2015/es6. Note this only handles
  2217. * syntax transformation and does not cover polyfills (except for dynamic
  2218. * import)
  2219. *
  2220. * Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules,
  2221. * transpile targeting browsers that natively support dynamic es module imports.
  2222. * https://caniuse.com/es6-module-dynamic-import
  2223. *
  2224. * Another special value is 'esnext' - which only performs minimal transpiling
  2225. * (for minification compat) and assumes native dynamic imports support.
  2226. *
  2227. * For custom targets, see https://esbuild.github.io/api/#target and
  2228. * https://esbuild.github.io/content-types/#javascript for more details.
  2229. * @default 'modules'
  2230. */
  2231. target?: 'modules' | esbuild_TransformOptions['target'] | false;
  2232. /**
  2233. * whether to inject module preload polyfill.
  2234. * Note: does not apply to library mode.
  2235. * @default true
  2236. * @deprecated use `modulePreload.polyfill` instead
  2237. */
  2238. polyfillModulePreload?: boolean;
  2239. /**
  2240. * Configure module preload
  2241. * Note: does not apply to library mode.
  2242. * @default true
  2243. */
  2244. modulePreload?: boolean | ModulePreloadOptions;
  2245. /**
  2246. * Directory relative from `root` where build output will be placed. If the
  2247. * directory exists, it will be removed before the build.
  2248. * @default 'dist'
  2249. */
  2250. outDir?: string;
  2251. /**
  2252. * Directory relative from `outDir` where the built js/css/image assets will
  2253. * be placed.
  2254. * @default 'assets'
  2255. */
  2256. assetsDir?: string;
  2257. /**
  2258. * Static asset files smaller than this number (in bytes) will be inlined as
  2259. * base64 strings. Default limit is `4096` (4 KiB). Set to `0` to disable.
  2260. * @default 4096
  2261. */
  2262. assetsInlineLimit?: number | ((filePath: string, content: Buffer) => boolean | undefined);
  2263. /**
  2264. * Whether to code-split CSS. When enabled, CSS in async chunks will be
  2265. * inlined as strings in the chunk and inserted via dynamically created
  2266. * style tags when the chunk is loaded.
  2267. * @default true
  2268. */
  2269. cssCodeSplit?: boolean;
  2270. /**
  2271. * An optional separate target for CSS minification.
  2272. * As esbuild only supports configuring targets to mainstream
  2273. * browsers, users may need this option when they are targeting
  2274. * a niche browser that comes with most modern JavaScript features
  2275. * but has poor CSS support, e.g. Android WeChat WebView, which
  2276. * doesn't support the #RGBA syntax.
  2277. * @default target
  2278. */
  2279. cssTarget?: esbuild_TransformOptions['target'] | false;
  2280. /**
  2281. * Override CSS minification specifically instead of defaulting to `build.minify`,
  2282. * so you can configure minification for JS and CSS separately.
  2283. * @default 'esbuild'
  2284. */
  2285. cssMinify?: boolean | 'esbuild' | 'lightningcss';
  2286. /**
  2287. * If `true`, a separate sourcemap file will be created. If 'inline', the
  2288. * sourcemap will be appended to the resulting output file as data URI.
  2289. * 'hidden' works like `true` except that the corresponding sourcemap
  2290. * comments in the bundled files are suppressed.
  2291. * @default false
  2292. */
  2293. sourcemap?: boolean | 'inline' | 'hidden';
  2294. /**
  2295. * Set to `false` to disable minification, or specify the minifier to use.
  2296. * Available options are 'terser' or 'esbuild'.
  2297. * @default 'esbuild'
  2298. */
  2299. minify?: boolean | 'terser' | 'esbuild';
  2300. /**
  2301. * Options for terser
  2302. * https://terser.org/docs/api-reference#minify-options
  2303. *
  2304. * In addition, you can also pass a `maxWorkers: number` option to specify the
  2305. * max number of workers to spawn. Defaults to the number of CPUs minus 1.
  2306. */
  2307. terserOptions?: TerserOptions;
  2308. /**
  2309. * Will be merged with internal rollup options.
  2310. * https://rollupjs.org/configuration-options/
  2311. */
  2312. rollupOptions?: RollupOptions;
  2313. /**
  2314. * Options to pass on to `@rollup/plugin-commonjs`
  2315. */
  2316. commonjsOptions?: RollupCommonJSOptions;
  2317. /**
  2318. * Options to pass on to `@rollup/plugin-dynamic-import-vars`
  2319. */
  2320. dynamicImportVarsOptions?: RollupDynamicImportVarsOptions;
  2321. /**
  2322. * Whether to write bundle to disk
  2323. * @default true
  2324. */
  2325. write?: boolean;
  2326. /**
  2327. * Empty outDir on write.
  2328. * @default true when outDir is a sub directory of project root
  2329. */
  2330. emptyOutDir?: boolean | null;
  2331. /**
  2332. * Copy the public directory to outDir on write.
  2333. * @default true
  2334. */
  2335. copyPublicDir?: boolean;
  2336. /**
  2337. * Whether to emit a .vite/manifest.json under assets dir to map hash-less filenames
  2338. * to their hashed versions. Useful when you want to generate your own HTML
  2339. * instead of using the one generated by Vite.
  2340. *
  2341. * Example:
  2342. *
  2343. * ```json
  2344. * {
  2345. * "main.js": {
  2346. * "file": "main.68fe3fad.js",
  2347. * "css": "main.e6b63442.css",
  2348. * "imports": [...],
  2349. * "dynamicImports": [...]
  2350. * }
  2351. * }
  2352. * ```
  2353. * @default false
  2354. */
  2355. manifest?: boolean | string;
  2356. /**
  2357. * Build in library mode. The value should be the global name of the lib in
  2358. * UMD mode. This will produce esm + cjs + umd bundle formats with default
  2359. * configurations that are suitable for distributing libraries.
  2360. * @default false
  2361. */
  2362. lib?: LibraryOptions | false;
  2363. /**
  2364. * Produce SSR oriented build. Note this requires specifying SSR entry via
  2365. * `rollupOptions.input`.
  2366. * @default false
  2367. */
  2368. ssr?: boolean | string;
  2369. /**
  2370. * Generate SSR manifest for determining style links and asset preload
  2371. * directives in production.
  2372. * @default false
  2373. */
  2374. ssrManifest?: boolean | string;
  2375. /**
  2376. * Emit assets during SSR.
  2377. * @default false
  2378. */
  2379. ssrEmitAssets?: boolean;
  2380. /**
  2381. * Set to false to disable reporting compressed chunk sizes.
  2382. * Can slightly improve build speed.
  2383. * @default true
  2384. */
  2385. reportCompressedSize?: boolean;
  2386. /**
  2387. * Adjust chunk size warning limit (in kB).
  2388. * @default 500
  2389. */
  2390. chunkSizeWarningLimit?: number;
  2391. /**
  2392. * Rollup watch options
  2393. * https://rollupjs.org/configuration-options/#watch
  2394. * @default null
  2395. */
  2396. watch?: WatcherOptions | null;
  2397. }
  2398. interface LibraryOptions {
  2399. /**
  2400. * Path of library entry
  2401. */
  2402. entry: InputOption;
  2403. /**
  2404. * The name of the exposed global variable. Required when the `formats` option includes
  2405. * `umd` or `iife`
  2406. */
  2407. name?: string;
  2408. /**
  2409. * Output bundle formats
  2410. * @default ['es', 'umd']
  2411. */
  2412. formats?: LibraryFormats[];
  2413. /**
  2414. * The name of the package file output. The default file name is the name option
  2415. * of the project package.json. It can also be defined as a function taking the
  2416. * format as an argument.
  2417. */
  2418. fileName?: string | ((format: ModuleFormat, entryName: string) => string);
  2419. }
  2420. type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife' | 'system';
  2421. interface ModulePreloadOptions {
  2422. /**
  2423. * Whether to inject a module preload polyfill.
  2424. * Note: does not apply to library mode.
  2425. * @default true
  2426. */
  2427. polyfill?: boolean;
  2428. /**
  2429. * Resolve the list of dependencies to preload for a given dynamic import
  2430. * @experimental
  2431. */
  2432. resolveDependencies?: ResolveModulePreloadDependenciesFn;
  2433. }
  2434. interface ResolvedModulePreloadOptions {
  2435. polyfill: boolean;
  2436. resolveDependencies?: ResolveModulePreloadDependenciesFn;
  2437. }
  2438. type ResolveModulePreloadDependenciesFn = (filename: string, deps: string[], context: {
  2439. hostId: string;
  2440. hostType: 'html' | 'js';
  2441. }) => string[];
  2442. interface ResolvedBuildOptions extends Required<Omit<BuildOptions, 'polyfillModulePreload'>> {
  2443. modulePreload: false | ResolvedModulePreloadOptions;
  2444. }
  2445. /**
  2446. * Bundles the app for production.
  2447. * Returns a Promise containing the build result.
  2448. */
  2449. declare function build(inlineConfig?: InlineConfig): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
  2450. type RenderBuiltAssetUrl = (filename: string, type: {
  2451. type: 'asset' | 'public';
  2452. hostId: string;
  2453. hostType: 'js' | 'css' | 'html';
  2454. ssr: boolean;
  2455. }) => string | {
  2456. relative?: boolean;
  2457. runtime?: string;
  2458. } | undefined;
  2459. interface ESBuildOptions extends esbuild_TransformOptions {
  2460. include?: string | RegExp | string[] | RegExp[];
  2461. exclude?: string | RegExp | string[] | RegExp[];
  2462. jsxInject?: string;
  2463. /**
  2464. * This option is not respected. Use `build.minify` instead.
  2465. */
  2466. minify?: never;
  2467. }
  2468. type ESBuildTransformResult = Omit<esbuild_TransformResult, 'map'> & {
  2469. map: SourceMap;
  2470. };
  2471. declare function transformWithEsbuild(code: string, filename: string, options?: esbuild_TransformOptions, inMap?: object): Promise<ESBuildTransformResult>;
  2472. type ExportsData = {
  2473. hasModuleSyntax: boolean;
  2474. exports: readonly string[];
  2475. jsxLoader?: boolean;
  2476. };
  2477. interface DepsOptimizer {
  2478. metadata: DepOptimizationMetadata;
  2479. scanProcessing?: Promise<void>;
  2480. registerMissingImport: (id: string, resolved: string) => OptimizedDepInfo;
  2481. run: () => void;
  2482. isOptimizedDepFile: (id: string) => boolean;
  2483. isOptimizedDepUrl: (url: string) => boolean;
  2484. getOptimizedDepId: (depInfo: OptimizedDepInfo) => string;
  2485. close: () => Promise<void>;
  2486. options: DepOptimizationOptions;
  2487. }
  2488. interface DepOptimizationConfig {
  2489. /**
  2490. * Force optimize listed dependencies (must be resolvable import paths,
  2491. * cannot be globs).
  2492. */
  2493. include?: string[];
  2494. /**
  2495. * Do not optimize these dependencies (must be resolvable import paths,
  2496. * cannot be globs).
  2497. */
  2498. exclude?: string[];
  2499. /**
  2500. * Forces ESM interop when importing these dependencies. Some legacy
  2501. * packages advertise themselves as ESM but use `require` internally
  2502. * @experimental
  2503. */
  2504. needsInterop?: string[];
  2505. /**
  2506. * Options to pass to esbuild during the dep scanning and optimization
  2507. *
  2508. * Certain options are omitted since changing them would not be compatible
  2509. * with Vite's dep optimization.
  2510. *
  2511. * - `external` is also omitted, use Vite's `optimizeDeps.exclude` option
  2512. * - `plugins` are merged with Vite's dep plugin
  2513. *
  2514. * https://esbuild.github.io/api
  2515. */
  2516. esbuildOptions?: Omit<esbuild_BuildOptions, 'bundle' | 'entryPoints' | 'external' | 'write' | 'watch' | 'outdir' | 'outfile' | 'outbase' | 'outExtension' | 'metafile'>;
  2517. /**
  2518. * List of file extensions that can be optimized. A corresponding esbuild
  2519. * plugin must exist to handle the specific extension.
  2520. *
  2521. * By default, Vite can optimize `.mjs`, `.js`, `.ts`, and `.mts` files. This option
  2522. * allows specifying additional extensions.
  2523. *
  2524. * @experimental
  2525. */
  2526. extensions?: string[];
  2527. /**
  2528. * Deps optimization during build was removed in Vite 5.1. This option is
  2529. * now redundant and will be removed in a future version. Switch to using
  2530. * `optimizeDeps.noDiscovery` and an empty or undefined `optimizeDeps.include`.
  2531. * true or 'dev' disables the optimizer, false or 'build' leaves it enabled.
  2532. * @default 'build'
  2533. * @deprecated
  2534. * @experimental
  2535. */
  2536. disabled?: boolean | 'build' | 'dev';
  2537. /**
  2538. * Automatic dependency discovery. When `noDiscovery` is true, only dependencies
  2539. * listed in `include` will be optimized. The scanner isn't run for cold start
  2540. * in this case. CJS-only dependencies must be present in `include` during dev.
  2541. * @default false
  2542. * @experimental
  2543. */
  2544. noDiscovery?: boolean;
  2545. /**
  2546. * When enabled, it will hold the first optimized deps results until all static
  2547. * imports are crawled on cold start. This avoids the need for full-page reloads
  2548. * when new dependencies are discovered and they trigger the generation of new
  2549. * common chunks. If all dependencies are found by the scanner plus the explicitly
  2550. * defined ones in `include`, it is better to disable this option to let the
  2551. * browser process more requests in parallel.
  2552. * @default true
  2553. * @experimental
  2554. */
  2555. holdUntilCrawlEnd?: boolean;
  2556. }
  2557. type DepOptimizationOptions = DepOptimizationConfig & {
  2558. /**
  2559. * By default, Vite will crawl your `index.html` to detect dependencies that
  2560. * need to be pre-bundled. If `build.rollupOptions.input` is specified, Vite
  2561. * will crawl those entry points instead.
  2562. *
  2563. * If neither of these fit your needs, you can specify custom entries using
  2564. * this option - the value should be a fast-glob pattern or array of patterns
  2565. * (https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from
  2566. * vite project root. This will overwrite default entries inference.
  2567. */
  2568. entries?: string | string[];
  2569. /**
  2570. * Force dep pre-optimization regardless of whether deps have changed.
  2571. * @experimental
  2572. */
  2573. force?: boolean;
  2574. };
  2575. interface OptimizedDepInfo {
  2576. id: string;
  2577. file: string;
  2578. src?: string;
  2579. needsInterop?: boolean;
  2580. browserHash?: string;
  2581. fileHash?: string;
  2582. /**
  2583. * During optimization, ids can still be resolved to their final location
  2584. * but the bundles may not yet be saved to disk
  2585. */
  2586. processing?: Promise<void>;
  2587. /**
  2588. * ExportData cache, discovered deps will parse the src entry to get exports
  2589. * data used both to define if interop is needed and when pre-bundling
  2590. */
  2591. exportsData?: Promise<ExportsData>;
  2592. }
  2593. interface DepOptimizationMetadata {
  2594. /**
  2595. * The main hash is determined by user config and dependency lockfiles.
  2596. * This is checked on server startup to avoid unnecessary re-bundles.
  2597. */
  2598. hash: string;
  2599. /**
  2600. * This hash is determined by dependency lockfiles.
  2601. * This is checked on server startup to avoid unnecessary re-bundles.
  2602. */
  2603. lockfileHash: string;
  2604. /**
  2605. * This hash is determined by user config.
  2606. * This is checked on server startup to avoid unnecessary re-bundles.
  2607. */
  2608. configHash: string;
  2609. /**
  2610. * The browser hash is determined by the main hash plus additional dependencies
  2611. * discovered at runtime. This is used to invalidate browser requests to
  2612. * optimized deps.
  2613. */
  2614. browserHash: string;
  2615. /**
  2616. * Metadata for each already optimized dependency
  2617. */
  2618. optimized: Record<string, OptimizedDepInfo>;
  2619. /**
  2620. * Metadata for non-entry optimized chunks and dynamic imports
  2621. */
  2622. chunks: Record<string, OptimizedDepInfo>;
  2623. /**
  2624. * Metadata for each newly discovered dependency after processing
  2625. */
  2626. discovered: Record<string, OptimizedDepInfo>;
  2627. /**
  2628. * OptimizedDepInfo list
  2629. */
  2630. depInfoList: OptimizedDepInfo[];
  2631. }
  2632. /**
  2633. * Scan and optimize dependencies within a project.
  2634. * Used by Vite CLI when running `vite optimize`.
  2635. */
  2636. declare function optimizeDeps(config: ResolvedConfig, force?: boolean | undefined, asCommand?: boolean): Promise<DepOptimizationMetadata>;
  2637. type SSRTarget = 'node' | 'webworker';
  2638. type SsrDepOptimizationOptions = DepOptimizationConfig;
  2639. interface SSROptions {
  2640. noExternal?: string | RegExp | (string | RegExp)[] | true;
  2641. external?: string[] | true;
  2642. /**
  2643. * Define the target for the ssr build. The browser field in package.json
  2644. * is ignored for node but used if webworker is the target
  2645. * @default 'node'
  2646. */
  2647. target?: SSRTarget;
  2648. /**
  2649. * Control over which dependencies are optimized during SSR and esbuild options
  2650. * During build:
  2651. * no external CJS dependencies are optimized by default
  2652. * During dev:
  2653. * explicit no external CJS dependencies are optimized by default
  2654. * @experimental
  2655. */
  2656. optimizeDeps?: SsrDepOptimizationOptions;
  2657. resolve?: {
  2658. /**
  2659. * Conditions that are used in the plugin pipeline. The default value is the root config's `resolve.conditions`.
  2660. *
  2661. * Use this to override the default ssr conditions for the ssr build.
  2662. *
  2663. * @default rootConfig.resolve.conditions
  2664. */
  2665. conditions?: string[];
  2666. /**
  2667. * Conditions that are used during ssr import (including `ssrLoadModule`) of externalized dependencies.
  2668. *
  2669. * @default []
  2670. */
  2671. externalConditions?: string[];
  2672. };
  2673. }
  2674. interface ResolvedSSROptions extends SSROptions {
  2675. target: SSRTarget;
  2676. optimizeDeps: SsrDepOptimizationOptions;
  2677. }
  2678. interface FsUtils {
  2679. existsSync: (path: string) => boolean;
  2680. isDirectory: (path: string) => boolean;
  2681. tryResolveRealFile: (path: string, preserveSymlinks?: boolean) => string | undefined;
  2682. tryResolveRealFileWithExtensions: (path: string, extensions: string[], preserveSymlinks?: boolean) => string | undefined;
  2683. tryResolveRealFileOrType: (path: string, preserveSymlinks?: boolean) => {
  2684. path?: string;
  2685. type: 'directory' | 'file';
  2686. } | undefined;
  2687. initWatcher?: (watcher: FSWatcher) => void;
  2688. }
  2689. interface ResolveOptions {
  2690. /**
  2691. * @default ['browser', 'module', 'jsnext:main', 'jsnext']
  2692. */
  2693. mainFields?: string[];
  2694. conditions?: string[];
  2695. /**
  2696. * @default ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']
  2697. */
  2698. extensions?: string[];
  2699. dedupe?: string[];
  2700. /**
  2701. * @default false
  2702. */
  2703. preserveSymlinks?: boolean;
  2704. }
  2705. interface InternalResolveOptions extends Required<ResolveOptions> {
  2706. root: string;
  2707. isBuild: boolean;
  2708. isProduction: boolean;
  2709. ssrConfig?: SSROptions;
  2710. packageCache?: PackageCache;
  2711. fsUtils?: FsUtils;
  2712. /**
  2713. * src code mode also attempts the following:
  2714. * - resolving /xxx as URLs
  2715. * - resolving bare imports from optimized deps
  2716. */
  2717. asSrc?: boolean;
  2718. tryIndex?: boolean;
  2719. tryPrefix?: string;
  2720. preferRelative?: boolean;
  2721. isRequire?: boolean;
  2722. isFromTsImporter?: boolean;
  2723. tryEsmOnly?: boolean;
  2724. scan?: boolean;
  2725. ssrOptimizeCheck?: boolean;
  2726. getDepsOptimizer?: (ssr: boolean) => DepsOptimizer | undefined;
  2727. shouldExternalize?: (id: string, importer?: string) => boolean | undefined;
  2728. }
  2729. // This file is autogenerated by build-prefixes.js. DO NOT EDIT!
  2730. interface Targets {
  2731. android?: number,
  2732. chrome?: number,
  2733. edge?: number,
  2734. firefox?: number,
  2735. ie?: number,
  2736. ios_saf?: number,
  2737. opera?: number,
  2738. safari?: number,
  2739. samsung?: number
  2740. }
  2741. interface Drafts {
  2742. /** Whether to enable @custom-media rules. */
  2743. customMedia?: boolean
  2744. }
  2745. interface NonStandard {
  2746. /** Whether to enable the non-standard >>> and /deep/ selector combinators used by Angular and Vue. */
  2747. deepSelectorCombinator?: boolean
  2748. }
  2749. interface PseudoClasses {
  2750. hover?: string,
  2751. active?: string,
  2752. focus?: string,
  2753. focusVisible?: string,
  2754. focusWithin?: string
  2755. }
  2756. interface CSSModulesConfig {
  2757. /** The pattern to use when renaming class names and other identifiers. Default is `[hash]_[local]`. */
  2758. pattern?: string,
  2759. /** Whether to rename dashed identifiers, e.g. custom properties. */
  2760. dashedIdents?: boolean
  2761. }
  2762. /**
  2763. * Options are spread, so you can also use options that are not typed here like
  2764. * visitor (not exposed because it would impact too much the bundle size)
  2765. */
  2766. type LightningCSSOptions = {
  2767. targets?: Targets
  2768. include?: number
  2769. exclude?: number
  2770. drafts?: Drafts
  2771. nonStandard?: NonStandard
  2772. pseudoClasses?: PseudoClasses
  2773. unusedSymbols?: string[]
  2774. cssModules?: CSSModulesConfig
  2775. errorRecovery?: boolean
  2776. }
  2777. interface CSSOptions {
  2778. /**
  2779. * Using lightningcss is an experimental option to handle CSS modules,
  2780. * assets and imports via Lightning CSS. It requires to install it as a
  2781. * peer dependency. This is incompatible with the use of preprocessors.
  2782. *
  2783. * @default 'postcss'
  2784. * @experimental
  2785. */
  2786. transformer?: 'postcss' | 'lightningcss';
  2787. /**
  2788. * https://github.com/css-modules/postcss-modules
  2789. */
  2790. modules?: CSSModulesOptions | false;
  2791. /**
  2792. * Options for preprocessors.
  2793. *
  2794. * In addition to options specific to each processors, Vite supports `additionalData` option.
  2795. * The `additionalData` option can be used to inject extra code for each style content.
  2796. */
  2797. preprocessorOptions?: Record<string, any>;
  2798. /**
  2799. * If this option is set, preprocessors will run in workers when possible.
  2800. * `true` means the number of CPUs minus 1.
  2801. *
  2802. * @default 0
  2803. * @experimental
  2804. */
  2805. preprocessorMaxWorkers?: number | true;
  2806. postcss?: string | (PostCSS.ProcessOptions & {
  2807. plugins?: PostCSS.AcceptedPlugin[];
  2808. });
  2809. /**
  2810. * Enables css sourcemaps during dev
  2811. * @default false
  2812. * @experimental
  2813. */
  2814. devSourcemap?: boolean;
  2815. /**
  2816. * @experimental
  2817. */
  2818. lightningcss?: LightningCSSOptions;
  2819. }
  2820. interface CSSModulesOptions {
  2821. getJSON?: (cssFileName: string, json: Record<string, string>, outputFileName: string) => void;
  2822. scopeBehaviour?: 'global' | 'local';
  2823. globalModulePaths?: RegExp[];
  2824. exportGlobals?: boolean;
  2825. generateScopedName?: string | ((name: string, filename: string, css: string) => string);
  2826. hashPrefix?: string;
  2827. /**
  2828. * default: undefined
  2829. */
  2830. localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | ((originalClassName: string, generatedClassName: string, inputFile: string) => string);
  2831. }
  2832. type ResolvedCSSOptions = Omit<CSSOptions, 'lightningcss'> & {
  2833. lightningcss?: LightningCSSOptions & {
  2834. targets: LightningCSSOptions['targets'];
  2835. };
  2836. };
  2837. interface PreprocessCSSResult {
  2838. code: string;
  2839. map?: SourceMapInput;
  2840. modules?: Record<string, string>;
  2841. deps?: Set<string>;
  2842. }
  2843. /**
  2844. * @experimental
  2845. */
  2846. declare function preprocessCSS(code: string, filename: string, config: ResolvedConfig): Promise<PreprocessCSSResult>;
  2847. declare function formatPostcssSourceMap(rawMap: ExistingRawSourceMap, file: string): Promise<ExistingRawSourceMap>;
  2848. interface HtmlTagDescriptor {
  2849. tag: string;
  2850. attrs?: Record<string, string | boolean | undefined>;
  2851. children?: string | HtmlTagDescriptor[];
  2852. /**
  2853. * default: 'head-prepend'
  2854. */
  2855. injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend';
  2856. }
  2857. type IndexHtmlTransformResult = string | HtmlTagDescriptor[] | {
  2858. html: string;
  2859. tags: HtmlTagDescriptor[];
  2860. };
  2861. interface IndexHtmlTransformContext {
  2862. /**
  2863. * public path when served
  2864. */
  2865. path: string;
  2866. /**
  2867. * filename on disk
  2868. */
  2869. filename: string;
  2870. server?: ViteDevServer;
  2871. bundle?: OutputBundle;
  2872. chunk?: OutputChunk;
  2873. originalUrl?: string;
  2874. }
  2875. type IndexHtmlTransformHook = (this: void, html: string, ctx: IndexHtmlTransformContext) => IndexHtmlTransformResult | void | Promise<IndexHtmlTransformResult | void>;
  2876. type IndexHtmlTransform = IndexHtmlTransformHook | {
  2877. order?: 'pre' | 'post' | null;
  2878. /**
  2879. * @deprecated renamed to `order`
  2880. */
  2881. enforce?: 'pre' | 'post';
  2882. /**
  2883. * @deprecated renamed to `handler`
  2884. */
  2885. transform: IndexHtmlTransformHook;
  2886. } | {
  2887. order?: 'pre' | 'post' | null;
  2888. /**
  2889. * @deprecated renamed to `order`
  2890. */
  2891. enforce?: 'pre' | 'post';
  2892. handler: IndexHtmlTransformHook;
  2893. };
  2894. /**
  2895. * Vite plugins extends the Rollup plugin interface with a few extra
  2896. * vite-specific options. A valid vite plugin is also a valid Rollup plugin.
  2897. * On the contrary, a Rollup plugin may or may NOT be a valid vite universal
  2898. * plugin, since some Rollup features do not make sense in an unbundled
  2899. * dev server context. That said, as long as a rollup plugin doesn't have strong
  2900. * coupling between its bundle phase and output phase hooks then it should
  2901. * just work (that means, most of them).
  2902. *
  2903. * By default, the plugins are run during both serve and build. When a plugin
  2904. * is applied during serve, it will only run **non output plugin hooks** (see
  2905. * rollup type definition of {@link rollup#PluginHooks}). You can think of the
  2906. * dev server as only running `const bundle = rollup.rollup()` but never calling
  2907. * `bundle.generate()`.
  2908. *
  2909. * A plugin that expects to have different behavior depending on serve/build can
  2910. * export a factory function that receives the command being run via options.
  2911. *
  2912. * If a plugin should be applied only for server or build, a function format
  2913. * config file can be used to conditional determine the plugins to use.
  2914. */
  2915. interface Plugin<A = any> extends rollup.Plugin<A> {
  2916. /**
  2917. * Enforce plugin invocation tier similar to webpack loaders. Hooks ordering
  2918. * is still subject to the `order` property in the hook object.
  2919. *
  2920. * Plugin invocation order:
  2921. * - alias resolution
  2922. * - `enforce: 'pre'` plugins
  2923. * - vite core plugins
  2924. * - normal plugins
  2925. * - vite build plugins
  2926. * - `enforce: 'post'` plugins
  2927. * - vite build post plugins
  2928. */
  2929. enforce?: 'pre' | 'post';
  2930. /**
  2931. * Apply the plugin only for serve or build, or on certain conditions.
  2932. */
  2933. apply?: 'serve' | 'build' | ((this: void, config: UserConfig, env: ConfigEnv) => boolean);
  2934. /**
  2935. * Modify vite config before it's resolved. The hook can either mutate the
  2936. * passed-in config directly, or return a partial config object that will be
  2937. * deeply merged into existing config.
  2938. *
  2939. * Note: User plugins are resolved before running this hook so injecting other
  2940. * plugins inside the `config` hook will have no effect.
  2941. */
  2942. config?: ObjectHook<(this: void, config: UserConfig, env: ConfigEnv) => Omit<UserConfig, 'plugins'> | null | void | Promise<Omit<UserConfig, 'plugins'> | null | void>>;
  2943. /**
  2944. * Use this hook to read and store the final resolved vite config.
  2945. */
  2946. configResolved?: ObjectHook<(this: void, config: ResolvedConfig) => void | Promise<void>>;
  2947. /**
  2948. * Configure the vite server. The hook receives the {@link ViteDevServer}
  2949. * instance. This can also be used to store a reference to the server
  2950. * for use in other hooks.
  2951. *
  2952. * The hooks will be called before internal middlewares are applied. A hook
  2953. * can return a post hook that will be called after internal middlewares
  2954. * are applied. Hook can be async functions and will be called in series.
  2955. */
  2956. configureServer?: ObjectHook<ServerHook>;
  2957. /**
  2958. * Configure the preview server. The hook receives the {@link PreviewServer}
  2959. * instance. This can also be used to store a reference to the server
  2960. * for use in other hooks.
  2961. *
  2962. * The hooks are called before other middlewares are applied. A hook can
  2963. * return a post hook that will be called after other middlewares are
  2964. * applied. Hooks can be async functions and will be called in series.
  2965. */
  2966. configurePreviewServer?: ObjectHook<PreviewServerHook>;
  2967. /**
  2968. * Transform index.html.
  2969. * The hook receives the following arguments:
  2970. *
  2971. * - html: string
  2972. * - ctx?: vite.ServerContext (only present during serve)
  2973. * - bundle?: rollup.OutputBundle (only present during build)
  2974. *
  2975. * It can either return a transformed string, or a list of html tag
  2976. * descriptors that will be injected into the `<head>` or `<body>`.
  2977. *
  2978. * By default the transform is applied **after** vite's internal html
  2979. * transform. If you need to apply the transform before vite, use an object:
  2980. * `{ order: 'pre', handler: hook }`
  2981. */
  2982. transformIndexHtml?: IndexHtmlTransform;
  2983. /**
  2984. * Perform custom handling of HMR updates.
  2985. * The handler receives a context containing changed filename, timestamp, a
  2986. * list of modules affected by the file change, and the dev server instance.
  2987. *
  2988. * - The hook can return a filtered list of modules to narrow down the update.
  2989. * e.g. for a Vue SFC, we can narrow down the part to update by comparing
  2990. * the descriptors.
  2991. *
  2992. * - The hook can also return an empty array and then perform custom updates
  2993. * by sending a custom hmr payload via server.ws.send().
  2994. *
  2995. * - If the hook doesn't return a value, the hmr update will be performed as
  2996. * normal.
  2997. */
  2998. handleHotUpdate?: ObjectHook<(this: void, ctx: HmrContext) => Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>>;
  2999. /**
  3000. * extend hooks with ssr flag
  3001. */
  3002. resolveId?: ObjectHook<(this: PluginContext, source: string, importer: string | undefined, options: {
  3003. attributes: Record<string, string>;
  3004. custom?: CustomPluginOptions;
  3005. ssr?: boolean;
  3006. isEntry: boolean;
  3007. }) => Promise<ResolveIdResult> | ResolveIdResult>;
  3008. load?: ObjectHook<(this: PluginContext, id: string, options?: {
  3009. ssr?: boolean;
  3010. }) => Promise<LoadResult> | LoadResult>;
  3011. transform?: ObjectHook<(this: TransformPluginContext, code: string, id: string, options?: {
  3012. ssr?: boolean;
  3013. }) => Promise<rollup.TransformResult> | rollup.TransformResult>;
  3014. }
  3015. type HookHandler<T> = T extends ObjectHook<infer H> ? H : T;
  3016. type PluginWithRequiredHook<K extends keyof Plugin> = Plugin & {
  3017. [P in K]: NonNullable<Plugin[P]>;
  3018. };
  3019. interface JsonOptions {
  3020. /**
  3021. * Generate a named export for every property of the JSON object
  3022. * @default true
  3023. */
  3024. namedExports?: boolean;
  3025. /**
  3026. * Generate performant output as JSON.parse("stringified").
  3027. * Enabling this will disable namedExports.
  3028. * @default false
  3029. */
  3030. stringify?: boolean;
  3031. }
  3032. interface ConfigEnv {
  3033. /**
  3034. * 'serve': during dev (`vite` command)
  3035. * 'build': when building for production (`vite build` command)
  3036. */
  3037. command: 'build' | 'serve';
  3038. mode: string;
  3039. isSsrBuild?: boolean;
  3040. isPreview?: boolean;
  3041. }
  3042. /**
  3043. * spa: include SPA fallback middleware and configure sirv with `single: true` in preview
  3044. *
  3045. * mpa: only include non-SPA HTML middlewares
  3046. *
  3047. * custom: don't include HTML middlewares
  3048. */
  3049. type AppType = 'spa' | 'mpa' | 'custom';
  3050. type UserConfigFnObject = (env: ConfigEnv) => UserConfig;
  3051. type UserConfigFnPromise = (env: ConfigEnv) => Promise<UserConfig>;
  3052. type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>;
  3053. type UserConfigExport = UserConfig | Promise<UserConfig> | UserConfigFnObject | UserConfigFnPromise | UserConfigFn;
  3054. /**
  3055. * Type helper to make it easier to use vite.config.ts
  3056. * accepts a direct {@link UserConfig} object, or a function that returns it.
  3057. * The function receives a {@link ConfigEnv} object.
  3058. */
  3059. declare function defineConfig(config: UserConfig): UserConfig;
  3060. declare function defineConfig(config: Promise<UserConfig>): Promise<UserConfig>;
  3061. declare function defineConfig(config: UserConfigFnObject): UserConfigFnObject;
  3062. declare function defineConfig(config: UserConfigExport): UserConfigExport;
  3063. type PluginOption = Plugin | false | null | undefined | PluginOption[] | Promise<Plugin | false | null | undefined | PluginOption[]>;
  3064. interface UserConfig {
  3065. /**
  3066. * Project root directory. Can be an absolute path, or a path relative from
  3067. * the location of the config file itself.
  3068. * @default process.cwd()
  3069. */
  3070. root?: string;
  3071. /**
  3072. * Base public path when served in development or production.
  3073. * @default '/'
  3074. */
  3075. base?: string;
  3076. /**
  3077. * Directory to serve as plain static assets. Files in this directory are
  3078. * served and copied to build dist dir as-is without transform. The value
  3079. * can be either an absolute file system path or a path relative to project root.
  3080. *
  3081. * Set to `false` or an empty string to disable copied static assets to build dist dir.
  3082. * @default 'public'
  3083. */
  3084. publicDir?: string | false;
  3085. /**
  3086. * Directory to save cache files. Files in this directory are pre-bundled
  3087. * deps or some other cache files that generated by vite, which can improve
  3088. * the performance. You can use `--force` flag or manually delete the directory
  3089. * to regenerate the cache files. The value can be either an absolute file
  3090. * system path or a path relative to project root.
  3091. * Default to `.vite` when no `package.json` is detected.
  3092. * @default 'node_modules/.vite'
  3093. */
  3094. cacheDir?: string;
  3095. /**
  3096. * Explicitly set a mode to run in. This will override the default mode for
  3097. * each command, and can be overridden by the command line --mode option.
  3098. */
  3099. mode?: string;
  3100. /**
  3101. * Define global variable replacements.
  3102. * Entries will be defined on `window` during dev and replaced during build.
  3103. */
  3104. define?: Record<string, any>;
  3105. /**
  3106. * Array of vite plugins to use.
  3107. */
  3108. plugins?: PluginOption[];
  3109. /**
  3110. * Configure resolver
  3111. */
  3112. resolve?: ResolveOptions & {
  3113. alias?: AliasOptions;
  3114. };
  3115. /**
  3116. * HTML related options
  3117. */
  3118. html?: HTMLOptions;
  3119. /**
  3120. * CSS related options (preprocessors and CSS modules)
  3121. */
  3122. css?: CSSOptions;
  3123. /**
  3124. * JSON loading options
  3125. */
  3126. json?: JsonOptions;
  3127. /**
  3128. * Transform options to pass to esbuild.
  3129. * Or set to `false` to disable esbuild.
  3130. */
  3131. esbuild?: ESBuildOptions | false;
  3132. /**
  3133. * Specify additional picomatch patterns to be treated as static assets.
  3134. */
  3135. assetsInclude?: string | RegExp | (string | RegExp)[];
  3136. /**
  3137. * Server specific options, e.g. host, port, https...
  3138. */
  3139. server?: ServerOptions;
  3140. /**
  3141. * Build specific options
  3142. */
  3143. build?: BuildOptions;
  3144. /**
  3145. * Preview specific options, e.g. host, port, https...
  3146. */
  3147. preview?: PreviewOptions;
  3148. /**
  3149. * Dep optimization options
  3150. */
  3151. optimizeDeps?: DepOptimizationOptions;
  3152. /**
  3153. * SSR specific options
  3154. */
  3155. ssr?: SSROptions;
  3156. /**
  3157. * Experimental features
  3158. *
  3159. * Features under this field could change in the future and might NOT follow semver.
  3160. * Please be careful and always pin Vite's version when using them.
  3161. * @experimental
  3162. */
  3163. experimental?: ExperimentalOptions;
  3164. /**
  3165. * Legacy options
  3166. *
  3167. * Features under this field only follow semver for patches, they could be removed in a
  3168. * future minor version. Please always pin Vite's version to a minor when using them.
  3169. */
  3170. legacy?: LegacyOptions;
  3171. /**
  3172. * Log level.
  3173. * @default 'info'
  3174. */
  3175. logLevel?: LogLevel;
  3176. /**
  3177. * Custom logger.
  3178. */
  3179. customLogger?: Logger;
  3180. /**
  3181. * @default true
  3182. */
  3183. clearScreen?: boolean;
  3184. /**
  3185. * Environment files directory. Can be an absolute path, or a path relative from
  3186. * root.
  3187. * @default root
  3188. */
  3189. envDir?: string;
  3190. /**
  3191. * Env variables starts with `envPrefix` will be exposed to your client source code via import.meta.env.
  3192. * @default 'VITE_'
  3193. */
  3194. envPrefix?: string | string[];
  3195. /**
  3196. * Worker bundle options
  3197. */
  3198. worker?: {
  3199. /**
  3200. * Output format for worker bundle
  3201. * @default 'iife'
  3202. */
  3203. format?: 'es' | 'iife';
  3204. /**
  3205. * Vite plugins that apply to worker bundle. The plugins returned by this function
  3206. * should be new instances every time it is called, because they are used for each
  3207. * rollup worker bundling process.
  3208. */
  3209. plugins?: () => PluginOption[];
  3210. /**
  3211. * Rollup options to build worker bundle
  3212. */
  3213. rollupOptions?: Omit<RollupOptions, 'plugins' | 'input' | 'onwarn' | 'preserveEntrySignatures'>;
  3214. };
  3215. /**
  3216. * Whether your application is a Single Page Application (SPA),
  3217. * a Multi-Page Application (MPA), or Custom Application (SSR
  3218. * and frameworks with custom HTML handling)
  3219. * @default 'spa'
  3220. */
  3221. appType?: AppType;
  3222. }
  3223. interface HTMLOptions {
  3224. /**
  3225. * A nonce value placeholder that will be used when generating script/style tags.
  3226. *
  3227. * Make sure that this placeholder will be replaced with a unique value for each request by the server.
  3228. */
  3229. cspNonce?: string;
  3230. }
  3231. interface ExperimentalOptions {
  3232. /**
  3233. * Append fake `&lang.(ext)` when queries are specified, to preserve the file extension for following plugins to process.
  3234. *
  3235. * @experimental
  3236. * @default false
  3237. */
  3238. importGlobRestoreExtension?: boolean;
  3239. /**
  3240. * Allow finegrain control over assets and public files paths
  3241. *
  3242. * @experimental
  3243. */
  3244. renderBuiltUrl?: RenderBuiltAssetUrl;
  3245. /**
  3246. * Enables support of HMR partial accept via `import.meta.hot.acceptExports`.
  3247. *
  3248. * @experimental
  3249. * @default false
  3250. */
  3251. hmrPartialAccept?: boolean;
  3252. /**
  3253. * Skips SSR transform to make it easier to use Vite with Node ESM loaders.
  3254. * @warning Enabling this will break normal operation of Vite's SSR in development mode.
  3255. *
  3256. * @experimental
  3257. * @default false
  3258. */
  3259. skipSsrTransform?: boolean;
  3260. }
  3261. interface LegacyOptions {
  3262. /**
  3263. * In Vite 4, SSR-externalized modules (modules not bundled and loaded by Node.js at runtime)
  3264. * are implicitly proxied in dev to automatically handle `default` and `__esModule` access.
  3265. * However, this does not correctly reflect how it works in the Node.js runtime, causing
  3266. * inconsistencies between dev and prod.
  3267. *
  3268. * In Vite 5, the proxy is removed so dev and prod are consistent, but if you still require
  3269. * the old behaviour, you can enable this option. If so, please leave your feedback at
  3270. * https://github.com/vitejs/vite/discussions/14697.
  3271. */
  3272. proxySsrExternalModules?: boolean;
  3273. /**
  3274. * In Vite 6.0.8 / 5.4.11 and below, WebSocket server was able to connect from any web pages. However,
  3275. * that could be exploited by a malicious web page.
  3276. *
  3277. * In Vite 6.0.9+ / 5.4.12+, the WebSocket server now requires a token to connect from a web page.
  3278. * But this may break some plugins and frameworks that connects to the WebSocket server
  3279. * on their own. Enabling this option will make Vite skip the token check.
  3280. *
  3281. * **We do not recommend enabling this option unless you are sure that you are fine with
  3282. * that security weakness.**
  3283. */
  3284. skipWebSocketTokenCheck?: boolean;
  3285. }
  3286. interface ResolvedWorkerOptions {
  3287. format: 'es' | 'iife';
  3288. plugins: (bundleChain: string[]) => Promise<Plugin[]>;
  3289. rollupOptions: RollupOptions;
  3290. }
  3291. interface InlineConfig extends UserConfig {
  3292. configFile?: string | false;
  3293. envFile?: false;
  3294. }
  3295. type ResolvedConfig = Readonly<Omit<UserConfig, 'plugins' | 'css' | 'assetsInclude' | 'optimizeDeps' | 'worker' | 'build'> & {
  3296. configFile: string | undefined;
  3297. configFileDependencies: string[];
  3298. inlineConfig: InlineConfig;
  3299. root: string;
  3300. base: string;
  3301. publicDir: string;
  3302. cacheDir: string;
  3303. command: 'build' | 'serve';
  3304. mode: string;
  3305. isWorker: boolean;
  3306. isProduction: boolean;
  3307. envDir: string;
  3308. env: Record<string, any>;
  3309. resolve: Required<ResolveOptions> & {
  3310. alias: Alias[];
  3311. };
  3312. plugins: readonly Plugin[];
  3313. css: ResolvedCSSOptions;
  3314. esbuild: ESBuildOptions | false;
  3315. server: ResolvedServerOptions;
  3316. build: ResolvedBuildOptions;
  3317. preview: ResolvedPreviewOptions;
  3318. ssr: ResolvedSSROptions;
  3319. assetsInclude: (file: string) => boolean;
  3320. logger: Logger;
  3321. createResolver: (options?: Partial<InternalResolveOptions>) => ResolveFn;
  3322. optimizeDeps: DepOptimizationOptions;
  3323. worker: ResolvedWorkerOptions;
  3324. appType: AppType;
  3325. experimental: ExperimentalOptions;
  3326. /**
  3327. * The token to connect to the WebSocket server from browsers.
  3328. *
  3329. * We recommend using `import.meta.hot` rather than connecting
  3330. * to the WebSocket server directly.
  3331. * If you have a usecase that requires connecting to the WebSocket
  3332. * server, please create an issue so that we can discuss.
  3333. *
  3334. * @deprecated
  3335. */
  3336. webSocketToken: string;
  3337. } & PluginHookUtils>;
  3338. interface PluginHookUtils {
  3339. getSortedPlugins: <K extends keyof Plugin>(hookName: K) => PluginWithRequiredHook<K>[];
  3340. getSortedPluginHooks: <K extends keyof Plugin>(hookName: K) => NonNullable<HookHandler<Plugin[K]>>[];
  3341. }
  3342. type ResolveFn = (id: string, importer?: string, aliasOnly?: boolean, ssr?: boolean) => Promise<string | undefined>;
  3343. declare function resolveConfig(inlineConfig: InlineConfig, command: 'build' | 'serve', defaultMode?: string, defaultNodeEnv?: string, isPreview?: boolean): Promise<ResolvedConfig>;
  3344. declare function sortUserPlugins(plugins: (Plugin | Plugin[])[] | undefined): [Plugin[], Plugin[], Plugin[]];
  3345. declare function loadConfigFromFile(configEnv: ConfigEnv, configFile?: string, configRoot?: string, logLevel?: LogLevel, customLogger?: Logger): Promise<{
  3346. path: string;
  3347. config: UserConfig;
  3348. dependencies: string[];
  3349. } | null>;
  3350. declare function buildErrorMessage(err: RollupError, args?: string[], includeStack?: boolean): string;
  3351. interface FetchModuleOptions {
  3352. inlineSourceMap?: boolean;
  3353. processSourceMap?<T extends NonNullable<TransformResult['map']>>(map: T): T;
  3354. }
  3355. /**
  3356. * Fetch module information for Vite runtime.
  3357. * @experimental
  3358. */
  3359. declare function fetchModule(server: ViteDevServer, url: string, importer?: string, options?: FetchModuleOptions): Promise<FetchResult>;
  3360. declare const VERSION: string;
  3361. declare const isCSSRequest: (request: string) => boolean;
  3362. /**
  3363. * @deprecated use build.rollupOptions.output.manualChunks or framework specific configuration
  3364. */
  3365. declare class SplitVendorChunkCache {
  3366. cache: Map<string, boolean>;
  3367. constructor();
  3368. reset(): void;
  3369. }
  3370. /**
  3371. * @deprecated use build.rollupOptions.output.manualChunks or framework specific configuration
  3372. */
  3373. declare function splitVendorChunk(options?: {
  3374. cache?: SplitVendorChunkCache;
  3375. }): GetManualChunk;
  3376. /**
  3377. * @deprecated use build.rollupOptions.output.manualChunks or framework specific configuration
  3378. */
  3379. declare function splitVendorChunkPlugin(): Plugin;
  3380. /**
  3381. * Inlined to keep `@rollup/pluginutils` in devDependencies
  3382. */
  3383. type FilterPattern = ReadonlyArray<string | RegExp> | string | RegExp | null;
  3384. declare const createFilter: (include?: FilterPattern, exclude?: FilterPattern, options?: {
  3385. resolve?: string | false | null;
  3386. }) => (id: string | unknown) => boolean;
  3387. declare const rollupVersion: string;
  3388. declare function normalizePath(id: string): string;
  3389. declare function mergeConfig<D extends Record<string, any>, O extends Record<string, any>>(defaults: D extends Function ? never : D, overrides: O extends Function ? never : O, isRoot?: boolean): Record<string, any>;
  3390. declare function mergeAlias(a?: AliasOptions, b?: AliasOptions): AliasOptions | undefined;
  3391. interface SendOptions {
  3392. etag?: string;
  3393. cacheControl?: string;
  3394. headers?: OutgoingHttpHeaders;
  3395. map?: SourceMap | {
  3396. mappings: '';
  3397. } | null;
  3398. }
  3399. declare function send(req: IncomingMessage, res: ServerResponse, content: string | Buffer, type: string, options: SendOptions): void;
  3400. /**
  3401. * Search up for the nearest workspace root
  3402. */
  3403. declare function searchForWorkspaceRoot(current: string, root?: string): string;
  3404. /**
  3405. * Check if the url is allowed to be served, via the `server.fs` config.
  3406. * @deprecated Use the `isFileLoadingAllowed` function instead.
  3407. */
  3408. declare function isFileServingAllowed(url: string, server: ViteDevServer): boolean;
  3409. declare function isFileLoadingAllowed(server: ViteDevServer, filePath: string): boolean;
  3410. declare function loadEnv(mode: string, envDir: string, prefixes?: string | string[]): Record<string, string>;
  3411. declare function resolveEnvPrefix({ envPrefix, }: UserConfig): string[];
  3412. type Manifest = Record<string, ManifestChunk>;
  3413. interface ManifestChunk {
  3414. src?: string;
  3415. file: string;
  3416. css?: string[];
  3417. assets?: string[];
  3418. isEntry?: boolean;
  3419. name?: string;
  3420. isDynamicEntry?: boolean;
  3421. imports?: string[];
  3422. dynamicImports?: string[];
  3423. }
  3424. /**
  3425. * @experimental
  3426. */
  3427. interface MainThreadRuntimeOptions extends Omit<ViteRuntimeOptions, 'root' | 'fetchModule' | 'hmr'> {
  3428. /**
  3429. * Disable HMR or configure HMR logger.
  3430. */
  3431. hmr?: false | {
  3432. logger?: false | HMRLogger;
  3433. };
  3434. /**
  3435. * Provide a custom module runner. This controls how the code is executed.
  3436. */
  3437. runner?: ViteModuleRunner;
  3438. }
  3439. /**
  3440. * Create an instance of the Vite SSR runtime that support HMR.
  3441. * @experimental
  3442. */
  3443. declare function createViteRuntime(server: ViteDevServer, options?: MainThreadRuntimeOptions): Promise<ViteRuntime>;
  3444. /**
  3445. * The connector class to establish HMR communication between the server and the Vite runtime.
  3446. * @experimental
  3447. */
  3448. declare class ServerHMRConnector implements HMRRuntimeConnection {
  3449. private handlers;
  3450. private hmrChannel;
  3451. private hmrClient;
  3452. private connected;
  3453. constructor(server: ViteDevServer);
  3454. isReady(): boolean;
  3455. send(message: string): void;
  3456. onUpdate(handler: (payload: HMRPayload) => void): void;
  3457. }
  3458. export { type Alias, type AliasOptions, type AnymatchFn, type AnymatchPattern, type AppType, type AwaitWriteFinishOptions, type BindCLIShortcutsOptions, type BuildOptions, type CLIShortcut, type CSSModulesOptions, type CSSOptions, type CommonServerOptions, type ConfigEnv, Connect, type CorsOptions, type CorsOrigin, type DepOptimizationConfig, type DepOptimizationMetadata, type DepOptimizationOptions, type ESBuildOptions, type ESBuildTransformResult, type ExperimentalOptions, type ExportsData, FSWatcher, type FetchModuleOptions, type FileSystemServeOptions, type FilterPattern, type HMRBroadcaster, type HMRBroadcasterClient, type HMRChannel, type HTMLOptions, type HmrContext, type HmrOptions, type HookHandler, type HtmlTagDescriptor, HttpProxy, type HttpServer, type IndexHtmlTransform, type IndexHtmlTransformContext, type IndexHtmlTransformHook, type IndexHtmlTransformResult, type InlineConfig, type InternalResolveOptions, type JsonOptions, type LegacyOptions, type LibraryFormats, type LibraryOptions, type LightningCSSOptions, type LogErrorOptions, type LogLevel, type LogOptions, type LogType, type Logger, type LoggerOptions, type MainThreadRuntimeOptions, type Manifest, type ManifestChunk, type MapToFunction, type AnymatchMatcher as Matcher, ModuleGraph, ModuleNode, type ModulePreloadOptions, type OptimizedDepInfo, type Plugin, PluginContainer, type PluginHookUtils, type PluginOption, type PreprocessCSSResult, type PreviewOptions, type PreviewServer, type PreviewServerHook, type ProxyOptions, type RenderBuiltAssetUrl, type ResolveFn, type ResolveModulePreloadDependenciesFn, type ResolveOptions, type ResolvedBuildOptions, type ResolvedCSSOptions, type ResolvedConfig, type ResolvedModulePreloadOptions, type ResolvedPreviewOptions, type ResolvedSSROptions, type ResolvedServerOptions, type ResolvedServerUrls, type ResolvedUrl, type ResolvedWorkerOptions, type ResolverFunction, type ResolverObject, type RollupCommonJSOptions, type RollupDynamicImportVarsOptions, type SSROptions, type SSRTarget, type SendOptions, type ServerHMRChannel, ServerHMRConnector, type ServerHook, type ServerOptions, SplitVendorChunkCache, type SsrDepOptimizationOptions, Terser, type TerserOptions, type TransformOptions, type TransformResult, type UserConfig, type UserConfigExport, type UserConfigFn, type UserConfigFnObject, type UserConfigFnPromise, type ViteDevServer, type WatchOptions, WebSocket, WebSocketAlias, type WebSocketClient, type WebSocketCustomListener, WebSocketServer, build, buildErrorMessage, createFilter, createLogger, createServer, createViteRuntime, defineConfig, fetchModule, formatPostcssSourceMap, isCSSRequest, isFileLoadingAllowed, isFileServingAllowed, loadConfigFromFile, loadEnv, mergeAlias, mergeConfig, normalizePath, optimizeDeps, preprocessCSS, preview, resolveConfig, resolveEnvPrefix, rollupVersion, searchForWorkspaceRoot, send, sortUserPlugins, splitVendorChunk, splitVendorChunkPlugin, transformWithEsbuild, VERSION as version };