index.d.ts 111 KB

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