市场夺宝奇兵
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3631 lines
144 KiB

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