index.d.ts 98 KB

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