index.d.ts 110 KB

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