UNPKG

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