vite 6.0.0-beta.7 → 6.0.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,7 +15,7 @@ import * as url from 'node:url';
15
15
  import { URL } from 'node:url';
16
16
  import * as stream from 'node:stream';
17
17
  import { Duplex, DuplexOptions } from 'node:stream';
18
- import { FetchFunctionOptions, FetchResult, ModuleRunnerOptions, ModuleRunnerHMRConnection, ModuleRunnerHmr, ModuleEvaluator, ModuleRunner } from 'vite/module-runner';
18
+ import { FetchFunctionOptions, FetchResult, ModuleRunnerOptions, ModuleRunnerHmr, ModuleEvaluator, ModuleRunner } from 'vite/module-runner';
19
19
  export { FetchFunction, FetchResult } from 'vite/module-runner';
20
20
  import { BuildOptions as esbuild_BuildOptions, TransformOptions as esbuild_TransformOptions, TransformResult as esbuild_TransformResult } from 'esbuild';
21
21
  export { TransformOptions as EsbuildTransformOptions, version as esbuildVersion } from 'esbuild';
@@ -1085,6 +1085,38 @@ interface HmrContext {
1085
1085
  server: ViteDevServer;
1086
1086
  }
1087
1087
  interface HotChannelClient {
1088
+ send(payload: HotPayload): void;
1089
+ }
1090
+ /** @deprecated use `HotChannelClient` instead */
1091
+ type HMRBroadcasterClient = HotChannelClient;
1092
+ type HotChannelListener<T extends string = string> = (data: InferCustomEventPayload<T>, client: HotChannelClient) => void;
1093
+ interface HotChannel<Api = any> {
1094
+ /**
1095
+ * Broadcast events to all clients
1096
+ */
1097
+ send?(payload: HotPayload): void;
1098
+ /**
1099
+ * Handle custom event emitted by `import.meta.hot.send`
1100
+ */
1101
+ on?<T extends string>(event: T, listener: HotChannelListener<T>): void;
1102
+ on?(event: 'connection', listener: () => void): void;
1103
+ /**
1104
+ * Unregister event listener
1105
+ */
1106
+ off?(event: string, listener: Function): void;
1107
+ /**
1108
+ * Start listening for messages
1109
+ */
1110
+ listen?(): void;
1111
+ /**
1112
+ * Disconnect all clients, called when server is closed or restarted.
1113
+ */
1114
+ close?(): Promise<unknown> | void;
1115
+ api?: Api;
1116
+ }
1117
+ /** @deprecated use `HotChannel` instead */
1118
+ type HMRChannel = HotChannel;
1119
+ interface NormalizedHotChannelClient {
1088
1120
  /**
1089
1121
  * Send event to the client
1090
1122
  */
@@ -1094,9 +1126,7 @@ interface HotChannelClient {
1094
1126
  */
1095
1127
  send(event: string, payload?: CustomPayload['data']): void;
1096
1128
  }
1097
- /** @deprecated use `HotChannelClient` instead */
1098
- type HMRBroadcasterClient = HotChannelClient;
1099
- interface HotChannel {
1129
+ interface NormalizedHotChannel<Api = any> {
1100
1130
  /**
1101
1131
  * Broadcast events to all clients
1102
1132
  */
@@ -1108,12 +1138,17 @@ interface HotChannel {
1108
1138
  /**
1109
1139
  * Handle custom event emitted by `import.meta.hot.send`
1110
1140
  */
1111
- on<T extends string>(event: T, listener: (data: InferCustomEventPayload<T>, client: HotChannelClient, ...args: any[]) => void): void;
1141
+ on<T extends string>(event: T, listener: (data: InferCustomEventPayload<T>, client: NormalizedHotChannelClient) => void): void;
1112
1142
  on(event: 'connection', listener: () => void): void;
1113
1143
  /**
1114
1144
  * Unregister event listener
1115
1145
  */
1116
1146
  off(event: string, listener: Function): void;
1147
+ handleInvoke(payload: HotPayload): Promise<{
1148
+ r: any;
1149
+ } | {
1150
+ e: any;
1151
+ }>;
1117
1152
  /**
1118
1153
  * Start listening for messages
1119
1154
  */
@@ -1122,21 +1157,19 @@ interface HotChannel {
1122
1157
  * Disconnect all clients, called when server is closed or restarted.
1123
1158
  */
1124
1159
  close(): Promise<unknown> | void;
1160
+ api?: Api;
1125
1161
  }
1126
- /** @deprecated use `HotChannel` instead */
1127
- type HMRChannel = HotChannel;
1128
- interface ServerHotChannel extends HotChannel {
1129
- api: {
1130
- innerEmitter: EventEmitter;
1131
- outsideEmitter: EventEmitter;
1132
- };
1133
- }
1162
+ type ServerHotChannelApi = {
1163
+ innerEmitter: EventEmitter;
1164
+ outsideEmitter: EventEmitter;
1165
+ };
1166
+ type ServerHotChannel = HotChannel<ServerHotChannelApi>;
1134
1167
  /** @deprecated use `ServerHotChannel` instead */
1135
1168
  type ServerHMRChannel = ServerHotChannel;
1136
1169
  declare function createServerHotChannel(): ServerHotChannel;
1137
1170
  /** @deprecated use `environment.hot` instead */
1138
- interface HotBroadcaster extends HotChannel {
1139
- readonly channels: HotChannel[];
1171
+ interface HotBroadcaster extends NormalizedHotChannel {
1172
+ readonly channels: NormalizedHotChannel[];
1140
1173
  /**
1141
1174
  * A noop.
1142
1175
  * @deprecated
@@ -1147,1592 +1180,1570 @@ interface HotBroadcaster extends HotChannel {
1147
1180
  /** @deprecated use `environment.hot` instead */
1148
1181
  type HMRBroadcaster = HotBroadcaster;
1149
1182
 
1150
- declare class RemoteEnvironmentTransport {
1151
- private readonly options;
1152
- constructor(options: {
1153
- send: (data: any) => void;
1154
- onMessage: (handler: (data: any) => void) => void;
1155
- });
1156
- register(environment: DevEnvironment): void;
1157
- }
1183
+ // Modified and inlined to avoid extra dependency
1184
+ // Source: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts
1158
1185
 
1159
- interface DevEnvironmentContext {
1160
- hot: false | HotChannel;
1161
- options?: EnvironmentOptions;
1162
- remoteRunner?: {
1163
- inlineSourceMap?: boolean;
1164
- transport?: RemoteEnvironmentTransport;
1165
- };
1166
- depsOptimizer?: DepsOptimizer;
1167
- }
1168
- declare class DevEnvironment extends BaseEnvironment {
1169
- mode: "dev";
1170
- moduleGraph: EnvironmentModuleGraph;
1171
- depsOptimizer?: DepsOptimizer;
1172
- get pluginContainer(): EnvironmentPluginContainer;
1173
- /**
1174
- * Hot channel for this environment. If not provided or disabled,
1175
- * it will be a noop channel that does nothing.
1176
- *
1177
- * @example
1178
- * environment.hot.send({ type: 'full-reload' })
1179
- */
1180
- hot: HotChannel;
1181
- constructor(name: string, config: ResolvedConfig, context: DevEnvironmentContext);
1182
- init(options?: {
1183
- watcher?: FSWatcher;
1184
- /**
1185
- * the previous instance used for the environment with the same name
1186
- *
1187
- * when using, the consumer should check if it's an instance generated from the same class or factory function
1188
- */
1189
- previousInstance?: DevEnvironment;
1190
- }): Promise<void>;
1191
- /**
1192
- * When the dev server is restarted, the methods are called in the following order:
1193
- * - new instance `init`
1194
- * - previous instance `close`
1195
- * - new instance `listen`
1196
- */
1197
- listen(server: ViteDevServer): Promise<void>;
1198
- fetchModule(id: string, importer?: string, options?: FetchFunctionOptions): Promise<FetchResult>;
1199
- reloadModule(module: EnvironmentModuleNode): Promise<void>;
1200
- transformRequest(url: string): Promise<TransformResult | null>;
1201
- warmupRequest(url: string): Promise<void>;
1202
- close(): Promise<void>;
1203
- /**
1204
- * Calling `await environment.waitForRequestsIdle(id)` will wait until all static imports
1205
- * are processed after the first transformRequest call. If called from a load or transform
1206
- * plugin hook, the id needs to be passed as a parameter to avoid deadlocks.
1207
- * Calling this function after the first static imports section of the module graph has been
1208
- * processed will resolve immediately.
1209
- * @experimental
1210
- */
1211
- waitForRequestsIdle(ignoredId?: string): Promise<void>;
1212
- }
1186
+ declare const WebSocketAlias: typeof WebSocket
1187
+ interface WebSocketAlias extends WebSocket {}
1188
+
1189
+ // WebSocket socket.
1190
+ declare class WebSocket extends EventEmitter {
1191
+ /** The connection is not yet open. */
1192
+ static readonly CONNECTING: 0
1193
+ /** The connection is open and ready to communicate. */
1194
+ static readonly OPEN: 1
1195
+ /** The connection is in the process of closing. */
1196
+ static readonly CLOSING: 2
1197
+ /** The connection is closed. */
1198
+ static readonly CLOSED: 3
1199
+
1200
+ binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments'
1201
+ readonly bufferedAmount: number
1202
+ readonly extensions: string
1203
+ /** Indicates whether the websocket is paused */
1204
+ readonly isPaused: boolean
1205
+ readonly protocol: string
1206
+ /** The current state of the connection */
1207
+ readonly readyState:
1208
+ | typeof WebSocket.CONNECTING
1209
+ | typeof WebSocket.OPEN
1210
+ | typeof WebSocket.CLOSING
1211
+ | typeof WebSocket.CLOSED
1212
+ readonly url: string
1213
+
1214
+ /** The connection is not yet open. */
1215
+ readonly CONNECTING: 0
1216
+ /** The connection is open and ready to communicate. */
1217
+ readonly OPEN: 1
1218
+ /** The connection is in the process of closing. */
1219
+ readonly CLOSING: 2
1220
+ /** The connection is closed. */
1221
+ readonly CLOSED: 3
1222
+
1223
+ onopen: ((event: WebSocket.Event) => void) | null
1224
+ onerror: ((event: WebSocket.ErrorEvent) => void) | null
1225
+ onclose: ((event: WebSocket.CloseEvent) => void) | null
1226
+ onmessage: ((event: WebSocket.MessageEvent) => void) | null
1227
+
1228
+ constructor(address: null)
1229
+ constructor(
1230
+ address: string | URL,
1231
+ options?: WebSocket.ClientOptions | ClientRequestArgs,
1232
+ )
1233
+ constructor(
1234
+ address: string | URL,
1235
+ protocols?: string | string[],
1236
+ options?: WebSocket.ClientOptions | ClientRequestArgs,
1237
+ )
1238
+
1239
+ close(code?: number, data?: string | Buffer): void
1240
+ ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void
1241
+ pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void
1242
+ send(data: any, cb?: (err?: Error) => void): void
1243
+ send(
1244
+ data: any,
1245
+ options: {
1246
+ mask?: boolean | undefined
1247
+ binary?: boolean | undefined
1248
+ compress?: boolean | undefined
1249
+ fin?: boolean | undefined
1250
+ },
1251
+ cb?: (err?: Error) => void,
1252
+ ): void
1253
+ terminate(): void
1213
1254
 
1214
- interface RollupCommonJSOptions {
1215
- /**
1216
- * A minimatch pattern, or array of patterns, which specifies the files in
1217
- * the build the plugin should operate on. By default, all files with
1218
- * extension `".cjs"` or those in `extensions` are included, but you can
1219
- * narrow this list by only including specific files. These files will be
1220
- * analyzed and transpiled if either the analysis does not find ES module
1221
- * specific statements or `transformMixedEsModules` is `true`.
1222
- * @default undefined
1223
- */
1224
- include?: string | RegExp | readonly (string | RegExp)[]
1225
- /**
1226
- * A minimatch pattern, or array of patterns, which specifies the files in
1227
- * the build the plugin should _ignore_. By default, all files with
1228
- * extensions other than those in `extensions` or `".cjs"` are ignored, but you
1229
- * can exclude additional files. See also the `include` option.
1230
- * @default undefined
1231
- */
1232
- exclude?: string | RegExp | readonly (string | RegExp)[]
1233
- /**
1234
- * For extensionless imports, search for extensions other than .js in the
1235
- * order specified. Note that you need to make sure that non-JavaScript files
1236
- * are transpiled by another plugin first.
1237
- * @default [ '.js' ]
1238
- */
1239
- extensions?: ReadonlyArray<string>
1240
- /**
1241
- * If true then uses of `global` won't be dealt with by this plugin
1242
- * @default false
1243
- */
1244
- ignoreGlobal?: boolean
1245
- /**
1246
- * If false, skips source map generation for CommonJS modules. This will
1247
- * improve performance.
1248
- * @default true
1249
- */
1250
- sourceMap?: boolean
1251
- /**
1252
- * Some `require` calls cannot be resolved statically to be translated to
1253
- * imports.
1254
- * When this option is set to `false`, the generated code will either
1255
- * directly throw an error when such a call is encountered or, when
1256
- * `dynamicRequireTargets` is used, when such a call cannot be resolved with a
1257
- * configured dynamic require target.
1258
- * Setting this option to `true` will instead leave the `require` call in the
1259
- * code or use it as a fallback for `dynamicRequireTargets`.
1260
- * @default false
1261
- */
1262
- ignoreDynamicRequires?: boolean
1263
- /**
1264
- * Instructs the plugin whether to enable mixed module transformations. This
1265
- * is useful in scenarios with modules that contain a mix of ES `import`
1266
- * statements and CommonJS `require` expressions. Set to `true` if `require`
1267
- * calls should be transformed to imports in mixed modules, or `false` if the
1268
- * `require` expressions should survive the transformation. The latter can be
1269
- * important if the code contains environment detection, or you are coding
1270
- * for an environment with special treatment for `require` calls such as
1271
- * ElectronJS. See also the `ignore` option.
1272
- * @default false
1273
- */
1274
- transformMixedEsModules?: boolean
1275
1255
  /**
1276
- * By default, this plugin will try to hoist `require` statements as imports
1277
- * to the top of each file. While this works well for many code bases and
1278
- * allows for very efficient ESM output, it does not perfectly capture
1279
- * CommonJS semantics as the order of side effects like log statements may
1280
- * change. But it is especially problematic when there are circular `require`
1281
- * calls between CommonJS modules as those often rely on the lazy execution of
1282
- * nested `require` calls.
1283
- *
1284
- * Setting this option to `true` will wrap all CommonJS files in functions
1285
- * which are executed when they are required for the first time, preserving
1286
- * NodeJS semantics. Note that this can have an impact on the size and
1287
- * performance of the generated code.
1288
- *
1289
- * The default value of `"auto"` will only wrap CommonJS files when they are
1290
- * part of a CommonJS dependency cycle, e.g. an index file that is required by
1291
- * many of its dependencies. All other CommonJS files are hoisted. This is the
1292
- * recommended setting for most code bases.
1293
- *
1294
- * `false` will entirely prevent wrapping and hoist all files. This may still
1295
- * work depending on the nature of cyclic dependencies but will often cause
1296
- * problems.
1297
- *
1298
- * You can also provide a minimatch pattern, or array of patterns, to only
1299
- * specify a subset of files which should be wrapped in functions for proper
1300
- * `require` semantics.
1301
- *
1302
- * `"debug"` works like `"auto"` but after bundling, it will display a warning
1303
- * containing a list of ids that have been wrapped which can be used as
1304
- * minimatch pattern for fine-tuning.
1305
- * @default "auto"
1256
+ * Pause the websocket causing it to stop emitting events. Some events can still be
1257
+ * emitted after this is called, until all buffered data is consumed. This method
1258
+ * is a noop if the ready state is `CONNECTING` or `CLOSED`.
1306
1259
  */
1307
- strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[]
1260
+ pause(): void
1308
1261
  /**
1309
- * Sometimes you have to leave require statements unconverted. Pass an array
1310
- * containing the IDs or a `id => boolean` function.
1311
- * @default []
1262
+ * Make a paused socket resume emitting events. This method is a noop if the ready
1263
+ * state is `CONNECTING` or `CLOSED`.
1312
1264
  */
1313
- ignore?: ReadonlyArray<string> | ((id: string) => boolean)
1314
- /**
1315
- * In most cases, where `require` calls are inside a `try-catch` clause,
1316
- * they should be left unconverted as it requires an optional dependency
1317
- * that may or may not be installed beside the rolled up package.
1318
- * Due to the conversion of `require` to a static `import` - the call is
1319
- * hoisted to the top of the file, outside the `try-catch` clause.
1320
- *
1321
- * - `true`: Default. All `require` calls inside a `try` will be left unconverted.
1322
- * - `false`: All `require` calls inside a `try` will be converted as if the
1323
- * `try-catch` clause is not there.
1324
- * - `remove`: Remove all `require` calls from inside any `try` block.
1325
- * - `string[]`: Pass an array containing the IDs to left unconverted.
1326
- * - `((id: string) => boolean|'remove')`: Pass a function that controls
1327
- * individual IDs.
1328
- *
1329
- * @default true
1330
- */
1331
- ignoreTryCatch?:
1332
- | boolean
1333
- | 'remove'
1334
- | ReadonlyArray<string>
1335
- | ((id: string) => boolean | 'remove')
1336
- /**
1337
- * Controls how to render imports from external dependencies. By default,
1338
- * this plugin assumes that all external dependencies are CommonJS. This
1339
- * means they are rendered as default imports to be compatible with e.g.
1340
- * NodeJS where ES modules can only import a default export from a CommonJS
1341
- * dependency.
1342
- *
1343
- * If you set `esmExternals` to `true`, this plugin assumes that all
1344
- * external dependencies are ES modules and respect the
1345
- * `requireReturnsDefault` option. If that option is not set, they will be
1346
- * rendered as namespace imports.
1347
- *
1348
- * You can also supply an array of ids to be treated as ES modules, or a
1349
- * function that will be passed each external id to determine whether it is
1350
- * an ES module.
1351
- * @default false
1352
- */
1353
- esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean)
1354
- /**
1355
- * Controls what is returned when requiring an ES module from a CommonJS file.
1356
- * When using the `esmExternals` option, this will also apply to external
1357
- * modules. By default, this plugin will render those imports as namespace
1358
- * imports i.e.
1359
- *
1360
- * ```js
1361
- * // input
1362
- * const foo = require('foo');
1363
- *
1364
- * // output
1365
- * import * as foo from 'foo';
1366
- * ```
1367
- *
1368
- * However, there are some situations where this may not be desired.
1369
- * For these situations, you can change Rollup's behaviour either globally or
1370
- * per module. To change it globally, set the `requireReturnsDefault` option
1371
- * to one of the following values:
1372
- *
1373
- * - `false`: This is the default, requiring an ES module returns its
1374
- * namespace. This is the only option that will also add a marker
1375
- * `__esModule: true` to the namespace to support interop patterns in
1376
- * CommonJS modules that are transpiled ES modules.
1377
- * - `"namespace"`: Like `false`, requiring an ES module returns its
1378
- * namespace, but the plugin does not add the `__esModule` marker and thus
1379
- * creates more efficient code. For external dependencies when using
1380
- * `esmExternals: true`, no additional interop code is generated.
1381
- * - `"auto"`: This is complementary to how `output.exports: "auto"` works in
1382
- * Rollup: If a module has a default export and no named exports, requiring
1383
- * that module returns the default export. In all other cases, the namespace
1384
- * is returned. For external dependencies when using `esmExternals: true`, a
1385
- * corresponding interop helper is added.
1386
- * - `"preferred"`: If a module has a default export, requiring that module
1387
- * always returns the default export, no matter whether additional named
1388
- * exports exist. This is similar to how previous versions of this plugin
1389
- * worked. Again for external dependencies when using `esmExternals: true`,
1390
- * an interop helper is added.
1391
- * - `true`: This will always try to return the default export on require
1392
- * without checking if it actually exists. This can throw at build time if
1393
- * there is no default export. This is how external dependencies are handled
1394
- * when `esmExternals` is not used. The advantage over the other options is
1395
- * that, like `false`, this does not add an interop helper for external
1396
- * dependencies, keeping the code lean.
1397
- *
1398
- * To change this for individual modules, you can supply a function for
1399
- * `requireReturnsDefault` instead. This function will then be called once for
1400
- * each required ES module or external dependency with the corresponding id
1401
- * and allows you to return different values for different modules.
1402
- * @default false
1403
- */
1404
- requireReturnsDefault?:
1405
- | boolean
1406
- | 'auto'
1407
- | 'preferred'
1408
- | 'namespace'
1409
- | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace')
1410
-
1411
- /**
1412
- * @default "auto"
1413
- */
1414
- defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto')
1415
- /**
1416
- * Some modules contain dynamic `require` calls, or require modules that
1417
- * contain circular dependencies, which are not handled well by static
1418
- * imports. Including those modules as `dynamicRequireTargets` will simulate a
1419
- * CommonJS (NodeJS-like) environment for them with support for dynamic
1420
- * dependencies. It also enables `strictRequires` for those modules.
1421
- *
1422
- * Note: In extreme cases, this feature may result in some paths being
1423
- * rendered as absolute in the final bundle. The plugin tries to avoid
1424
- * exposing paths from the local machine, but if you are `dynamicRequirePaths`
1425
- * with paths that are far away from your project's folder, that may require
1426
- * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`.
1427
- */
1428
- dynamicRequireTargets?: string | ReadonlyArray<string>
1429
- /**
1430
- * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory
1431
- * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/`
1432
- * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your
1433
- * home directory name. By default, it uses the current working directory.
1434
- */
1435
- dynamicRequireRoot?: string
1436
- }
1265
+ resume(): void
1437
1266
 
1438
- interface RollupDynamicImportVarsOptions {
1439
- /**
1440
- * Files to include in this plugin (default all).
1441
- * @default []
1442
- */
1443
- include?: string | RegExp | (string | RegExp)[]
1444
- /**
1445
- * Files to exclude in this plugin (default none).
1446
- * @default []
1447
- */
1448
- exclude?: string | RegExp | (string | RegExp)[]
1449
- /**
1450
- * 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.
1451
- * @default false
1452
- */
1453
- warnOnError?: boolean
1454
- }
1267
+ // HTML5 WebSocket events
1268
+ addEventListener(
1269
+ method: 'message',
1270
+ cb: (event: WebSocket.MessageEvent) => void,
1271
+ options?: WebSocket.EventListenerOptions,
1272
+ ): void
1273
+ addEventListener(
1274
+ method: 'close',
1275
+ cb: (event: WebSocket.CloseEvent) => void,
1276
+ options?: WebSocket.EventListenerOptions,
1277
+ ): void
1278
+ addEventListener(
1279
+ method: 'error',
1280
+ cb: (event: WebSocket.ErrorEvent) => void,
1281
+ options?: WebSocket.EventListenerOptions,
1282
+ ): void
1283
+ addEventListener(
1284
+ method: 'open',
1285
+ cb: (event: WebSocket.Event) => void,
1286
+ options?: WebSocket.EventListenerOptions,
1287
+ ): void
1455
1288
 
1456
- // Modified and inlined to avoid extra dependency
1457
- // Source: https://github.com/terser/terser/blob/master/tools/terser.d.ts
1458
- // BSD Licensed https://github.com/terser/terser/blob/master/LICENSE
1289
+ removeEventListener(
1290
+ method: 'message',
1291
+ cb: (event: WebSocket.MessageEvent) => void,
1292
+ ): void
1293
+ removeEventListener(
1294
+ method: 'close',
1295
+ cb: (event: WebSocket.CloseEvent) => void,
1296
+ ): void
1297
+ removeEventListener(
1298
+ method: 'error',
1299
+ cb: (event: WebSocket.ErrorEvent) => void,
1300
+ ): void
1301
+ removeEventListener(
1302
+ method: 'open',
1303
+ cb: (event: WebSocket.Event) => void,
1304
+ ): void
1459
1305
 
1460
- declare namespace Terser {
1461
- export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020
1306
+ // Events
1307
+ on(
1308
+ event: 'close',
1309
+ listener: (this: WebSocket, code: number, reason: Buffer) => void,
1310
+ ): this
1311
+ on(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1312
+ on(
1313
+ event: 'upgrade',
1314
+ listener: (this: WebSocket, request: IncomingMessage) => void,
1315
+ ): this
1316
+ on(
1317
+ event: 'message',
1318
+ listener: (
1319
+ this: WebSocket,
1320
+ data: WebSocket.RawData,
1321
+ isBinary: boolean,
1322
+ ) => void,
1323
+ ): this
1324
+ on(event: 'open', listener: (this: WebSocket) => void): this
1325
+ on(
1326
+ event: 'ping' | 'pong',
1327
+ listener: (this: WebSocket, data: Buffer) => void,
1328
+ ): this
1329
+ on(
1330
+ event: 'unexpected-response',
1331
+ listener: (
1332
+ this: WebSocket,
1333
+ request: ClientRequest,
1334
+ response: IncomingMessage,
1335
+ ) => void,
1336
+ ): this
1337
+ on(
1338
+ event: string | symbol,
1339
+ listener: (this: WebSocket, ...args: any[]) => void,
1340
+ ): this
1462
1341
 
1463
- export type ConsoleProperty = keyof typeof console
1464
- type DropConsoleOption = boolean | ConsoleProperty[]
1342
+ once(
1343
+ event: 'close',
1344
+ listener: (this: WebSocket, code: number, reason: Buffer) => void,
1345
+ ): this
1346
+ once(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1347
+ once(
1348
+ event: 'upgrade',
1349
+ listener: (this: WebSocket, request: IncomingMessage) => void,
1350
+ ): this
1351
+ once(
1352
+ event: 'message',
1353
+ listener: (
1354
+ this: WebSocket,
1355
+ data: WebSocket.RawData,
1356
+ isBinary: boolean,
1357
+ ) => void,
1358
+ ): this
1359
+ once(event: 'open', listener: (this: WebSocket) => void): this
1360
+ once(
1361
+ event: 'ping' | 'pong',
1362
+ listener: (this: WebSocket, data: Buffer) => void,
1363
+ ): this
1364
+ once(
1365
+ event: 'unexpected-response',
1366
+ listener: (
1367
+ this: WebSocket,
1368
+ request: ClientRequest,
1369
+ response: IncomingMessage,
1370
+ ) => void,
1371
+ ): this
1372
+ once(
1373
+ event: string | symbol,
1374
+ listener: (this: WebSocket, ...args: any[]) => void,
1375
+ ): this
1465
1376
 
1466
- export interface ParseOptions {
1467
- bare_returns?: boolean
1468
- /** @deprecated legacy option. Currently, all supported EcmaScript is valid to parse. */
1469
- ecma?: ECMA
1470
- html5_comments?: boolean
1471
- shebang?: boolean
1472
- }
1377
+ off(
1378
+ event: 'close',
1379
+ listener: (this: WebSocket, code: number, reason: Buffer) => void,
1380
+ ): this
1381
+ off(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1382
+ off(
1383
+ event: 'upgrade',
1384
+ listener: (this: WebSocket, request: IncomingMessage) => void,
1385
+ ): this
1386
+ off(
1387
+ event: 'message',
1388
+ listener: (
1389
+ this: WebSocket,
1390
+ data: WebSocket.RawData,
1391
+ isBinary: boolean,
1392
+ ) => void,
1393
+ ): this
1394
+ off(event: 'open', listener: (this: WebSocket) => void): this
1395
+ off(
1396
+ event: 'ping' | 'pong',
1397
+ listener: (this: WebSocket, data: Buffer) => void,
1398
+ ): this
1399
+ off(
1400
+ event: 'unexpected-response',
1401
+ listener: (
1402
+ this: WebSocket,
1403
+ request: ClientRequest,
1404
+ response: IncomingMessage,
1405
+ ) => void,
1406
+ ): this
1407
+ off(
1408
+ event: string | symbol,
1409
+ listener: (this: WebSocket, ...args: any[]) => void,
1410
+ ): this
1473
1411
 
1474
- export interface CompressOptions {
1475
- arguments?: boolean
1476
- arrows?: boolean
1477
- booleans_as_integers?: boolean
1478
- booleans?: boolean
1479
- collapse_vars?: boolean
1480
- comparisons?: boolean
1481
- computed_props?: boolean
1482
- conditionals?: boolean
1483
- dead_code?: boolean
1484
- defaults?: boolean
1485
- directives?: boolean
1486
- drop_console?: DropConsoleOption
1487
- drop_debugger?: boolean
1488
- ecma?: ECMA
1489
- evaluate?: boolean
1490
- expression?: boolean
1491
- global_defs?: object
1492
- hoist_funs?: boolean
1493
- hoist_props?: boolean
1494
- hoist_vars?: boolean
1495
- ie8?: boolean
1496
- if_return?: boolean
1497
- inline?: boolean | InlineFunctions
1498
- join_vars?: boolean
1499
- keep_classnames?: boolean | RegExp
1500
- keep_fargs?: boolean
1501
- keep_fnames?: boolean | RegExp
1502
- keep_infinity?: boolean
1503
- loops?: boolean
1504
- module?: boolean
1505
- negate_iife?: boolean
1506
- passes?: number
1507
- properties?: boolean
1508
- pure_funcs?: string[]
1509
- pure_new?: boolean
1510
- pure_getters?: boolean | 'strict'
1511
- reduce_funcs?: boolean
1512
- reduce_vars?: boolean
1513
- sequences?: boolean | number
1514
- side_effects?: boolean
1515
- switches?: boolean
1516
- toplevel?: boolean
1517
- top_retain?: null | string | string[] | RegExp
1518
- typeofs?: boolean
1519
- unsafe_arrows?: boolean
1520
- unsafe?: boolean
1521
- unsafe_comps?: boolean
1522
- unsafe_Function?: boolean
1523
- unsafe_math?: boolean
1524
- unsafe_symbols?: boolean
1525
- unsafe_methods?: boolean
1526
- unsafe_proto?: boolean
1527
- unsafe_regexp?: boolean
1528
- unsafe_undefined?: boolean
1529
- unused?: boolean
1530
- }
1412
+ addListener(
1413
+ event: 'close',
1414
+ listener: (code: number, reason: Buffer) => void,
1415
+ ): this
1416
+ addListener(event: 'error', listener: (err: Error) => void): this
1417
+ addListener(
1418
+ event: 'upgrade',
1419
+ listener: (request: IncomingMessage) => void,
1420
+ ): this
1421
+ addListener(
1422
+ event: 'message',
1423
+ listener: (data: WebSocket.RawData, isBinary: boolean) => void,
1424
+ ): this
1425
+ addListener(event: 'open', listener: () => void): this
1426
+ addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
1427
+ addListener(
1428
+ event: 'unexpected-response',
1429
+ listener: (request: ClientRequest, response: IncomingMessage) => void,
1430
+ ): this
1431
+ addListener(event: string | symbol, listener: (...args: any[]) => void): this
1531
1432
 
1532
- export enum InlineFunctions {
1533
- Disabled = 0,
1534
- SimpleFunctions = 1,
1535
- WithArguments = 2,
1536
- WithArgumentsAndVariables = 3,
1537
- }
1433
+ removeListener(
1434
+ event: 'close',
1435
+ listener: (code: number, reason: Buffer) => void,
1436
+ ): this
1437
+ removeListener(event: 'error', listener: (err: Error) => void): this
1438
+ removeListener(
1439
+ event: 'upgrade',
1440
+ listener: (request: IncomingMessage) => void,
1441
+ ): this
1442
+ removeListener(
1443
+ event: 'message',
1444
+ listener: (data: WebSocket.RawData, isBinary: boolean) => void,
1445
+ ): this
1446
+ removeListener(event: 'open', listener: () => void): this
1447
+ removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
1448
+ removeListener(
1449
+ event: 'unexpected-response',
1450
+ listener: (request: ClientRequest, response: IncomingMessage) => void,
1451
+ ): this
1452
+ removeListener(
1453
+ event: string | symbol,
1454
+ listener: (...args: any[]) => void,
1455
+ ): this
1456
+ }
1538
1457
 
1539
- export interface MangleOptions {
1540
- eval?: boolean
1541
- keep_classnames?: boolean | RegExp
1542
- keep_fnames?: boolean | RegExp
1543
- module?: boolean
1544
- nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
1545
- properties?: boolean | ManglePropertiesOptions
1546
- reserved?: string[]
1547
- safari10?: boolean
1548
- toplevel?: boolean
1549
- }
1458
+ declare namespace WebSocket {
1459
+ /**
1460
+ * Data represents the raw message payload received over the WebSocket.
1461
+ */
1462
+ type RawData = Buffer | ArrayBuffer | Buffer[]
1550
1463
 
1551
1464
  /**
1552
- * An identifier mangler for which the output is invariant with respect to the source code.
1465
+ * Data represents the message payload received over the WebSocket.
1553
1466
  */
1554
- export interface SimpleIdentifierMangler {
1555
- /**
1556
- * Obtains the nth most favored (usually shortest) identifier to rename a variable to.
1557
- * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word.
1558
- * This function is expected to be stable; Evaluating get(n) === get(n) should always return true.
1559
- * @param n The ordinal of the identifier.
1560
- */
1561
- get(n: number): string
1562
- }
1467
+ type Data = string | Buffer | ArrayBuffer | Buffer[]
1563
1468
 
1564
1469
  /**
1565
- * An identifier mangler that leverages character frequency analysis to determine identifier precedence.
1470
+ * CertMeta represents the accepted types for certificate & key data.
1566
1471
  */
1567
- export interface WeightedIdentifierMangler extends SimpleIdentifierMangler {
1568
- /**
1569
- * Modifies the internal weighting of the input characters by the specified delta.
1570
- * Will be invoked on the entire printed AST, and then deduct mangleable identifiers.
1571
- * @param chars The characters to modify the weighting of.
1572
- * @param delta The numeric weight to add to the characters.
1573
- */
1574
- consider(chars: string, delta: number): number
1575
- /**
1576
- * Resets character weights.
1577
- */
1578
- reset(): void
1579
- /**
1580
- * Sorts identifiers by character frequency, in preparation for calls to get(n).
1581
- */
1582
- sort(): void
1583
- }
1472
+ type CertMeta = string | string[] | Buffer | Buffer[]
1584
1473
 
1585
- export interface ManglePropertiesOptions {
1586
- builtins?: boolean
1587
- debug?: boolean
1588
- keep_quoted?: boolean | 'strict'
1589
- nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
1590
- regex?: RegExp | string
1591
- reserved?: string[]
1474
+ /**
1475
+ * VerifyClientCallbackSync is a synchronous callback used to inspect the
1476
+ * incoming message. The return value (boolean) of the function determines
1477
+ * whether or not to accept the handshake.
1478
+ */
1479
+ type VerifyClientCallbackSync = (info: {
1480
+ origin: string
1481
+ secure: boolean
1482
+ req: IncomingMessage
1483
+ }) => boolean
1484
+
1485
+ /**
1486
+ * VerifyClientCallbackAsync is an asynchronous callback used to inspect the
1487
+ * incoming message. The return value (boolean) of the function determines
1488
+ * whether or not to accept the handshake.
1489
+ */
1490
+ type VerifyClientCallbackAsync = (
1491
+ info: { origin: string; secure: boolean; req: IncomingMessage },
1492
+ callback: (
1493
+ res: boolean,
1494
+ code?: number,
1495
+ message?: string,
1496
+ headers?: OutgoingHttpHeaders,
1497
+ ) => void,
1498
+ ) => void
1499
+
1500
+ interface ClientOptions extends SecureContextOptions {
1501
+ protocol?: string | undefined
1502
+ followRedirects?: boolean | undefined
1503
+ generateMask?(mask: Buffer): void
1504
+ handshakeTimeout?: number | undefined
1505
+ maxRedirects?: number | undefined
1506
+ perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
1507
+ localAddress?: string | undefined
1508
+ protocolVersion?: number | undefined
1509
+ headers?: { [key: string]: string } | undefined
1510
+ origin?: string | undefined
1511
+ agent?: Agent | undefined
1512
+ host?: string | undefined
1513
+ family?: number | undefined
1514
+ checkServerIdentity?(servername: string, cert: CertMeta): boolean
1515
+ rejectUnauthorized?: boolean | undefined
1516
+ maxPayload?: number | undefined
1517
+ skipUTF8Validation?: boolean | undefined
1592
1518
  }
1593
1519
 
1594
- export interface FormatOptions {
1595
- ascii_only?: boolean
1596
- /** @deprecated Not implemented anymore */
1597
- beautify?: boolean
1598
- braces?: boolean
1599
- comments?:
1600
- | boolean
1601
- | 'all'
1602
- | 'some'
1603
- | RegExp
1604
- | ((
1605
- node: any,
1606
- comment: {
1607
- value: string
1608
- type: 'comment1' | 'comment2' | 'comment3' | 'comment4'
1609
- pos: number
1610
- line: number
1611
- col: number
1612
- },
1613
- ) => boolean)
1614
- ecma?: ECMA
1615
- ie8?: boolean
1616
- keep_numbers?: boolean
1617
- indent_level?: number
1618
- indent_start?: number
1619
- inline_script?: boolean
1620
- keep_quoted_props?: boolean
1621
- max_line_len?: number | false
1622
- preamble?: string
1623
- preserve_annotations?: boolean
1624
- quote_keys?: boolean
1625
- quote_style?: OutputQuoteStyle
1626
- safari10?: boolean
1627
- semicolons?: boolean
1628
- shebang?: boolean
1629
- shorthand?: boolean
1630
- source_map?: SourceMapOptions
1631
- webkit?: boolean
1632
- width?: number
1633
- wrap_iife?: boolean
1634
- wrap_func_args?: boolean
1520
+ interface PerMessageDeflateOptions {
1521
+ serverNoContextTakeover?: boolean | undefined
1522
+ clientNoContextTakeover?: boolean | undefined
1523
+ serverMaxWindowBits?: number | undefined
1524
+ clientMaxWindowBits?: number | undefined
1525
+ zlibDeflateOptions?:
1526
+ | {
1527
+ flush?: number | undefined
1528
+ finishFlush?: number | undefined
1529
+ chunkSize?: number | undefined
1530
+ windowBits?: number | undefined
1531
+ level?: number | undefined
1532
+ memLevel?: number | undefined
1533
+ strategy?: number | undefined
1534
+ dictionary?: Buffer | Buffer[] | DataView | undefined
1535
+ info?: boolean | undefined
1536
+ }
1537
+ | undefined
1538
+ zlibInflateOptions?: ZlibOptions | undefined
1539
+ threshold?: number | undefined
1540
+ concurrencyLimit?: number | undefined
1635
1541
  }
1636
1542
 
1637
- export enum OutputQuoteStyle {
1638
- PreferDouble = 0,
1639
- AlwaysSingle = 1,
1640
- AlwaysDouble = 2,
1641
- AlwaysOriginal = 3,
1543
+ interface Event {
1544
+ type: string
1545
+ target: WebSocket
1642
1546
  }
1643
1547
 
1644
- export interface MinifyOptions {
1645
- compress?: boolean | CompressOptions
1646
- ecma?: ECMA
1647
- enclose?: boolean | string
1648
- ie8?: boolean
1649
- keep_classnames?: boolean | RegExp
1650
- keep_fnames?: boolean | RegExp
1651
- mangle?: boolean | MangleOptions
1652
- module?: boolean
1653
- nameCache?: object
1654
- format?: FormatOptions
1655
- /** @deprecated */
1656
- output?: FormatOptions
1657
- parse?: ParseOptions
1658
- safari10?: boolean
1659
- sourceMap?: boolean | SourceMapOptions
1660
- toplevel?: boolean
1548
+ interface ErrorEvent {
1549
+ error: any
1550
+ message: string
1551
+ type: string
1552
+ target: WebSocket
1661
1553
  }
1662
1554
 
1663
- export interface MinifyOutput {
1664
- code?: string
1665
- map?: object | string
1666
- decoded_map?: object | null
1555
+ interface CloseEvent {
1556
+ wasClean: boolean
1557
+ code: number
1558
+ reason: string
1559
+ type: string
1560
+ target: WebSocket
1667
1561
  }
1668
1562
 
1669
- export interface SourceMapOptions {
1670
- /** Source map object, 'inline' or source map file content */
1671
- content?: object | string
1672
- includeSources?: boolean
1673
- filename?: string
1674
- root?: string
1675
- asObject?: boolean
1676
- url?: string | 'inline'
1563
+ interface MessageEvent {
1564
+ data: Data
1565
+ type: string
1566
+ target: WebSocket
1677
1567
  }
1678
- }
1679
1568
 
1680
- interface TerserOptions extends Terser.MinifyOptions {
1681
- /**
1682
- * Vite-specific option to specify the max number of workers to spawn
1683
- * when minifying files with terser.
1684
- *
1685
- * @default number of CPUs minus 1
1686
- */
1687
- maxWorkers?: number;
1688
- }
1569
+ interface EventListenerOptions {
1570
+ once?: boolean | undefined
1571
+ }
1689
1572
 
1690
- interface FsUtils {
1691
- existsSync: (path: string) => boolean;
1692
- isDirectory: (path: string) => boolean;
1693
- tryResolveRealFile: (path: string, preserveSymlinks?: boolean) => string | undefined;
1694
- tryResolveRealFileWithExtensions: (path: string, extensions: string[], preserveSymlinks?: boolean) => string | undefined;
1695
- tryResolveRealFileOrType: (path: string, preserveSymlinks?: boolean) => {
1696
- path?: string;
1697
- type: 'directory' | 'file';
1698
- } | undefined;
1699
- initWatcher?: (watcher: FSWatcher) => void;
1700
- }
1573
+ interface ServerOptions {
1574
+ host?: string | undefined
1575
+ port?: number | undefined
1576
+ backlog?: number | undefined
1577
+ server?: Server | HttpsServer | undefined
1578
+ verifyClient?:
1579
+ | VerifyClientCallbackAsync
1580
+ | VerifyClientCallbackSync
1581
+ | undefined
1582
+ handleProtocols?: (
1583
+ protocols: Set<string>,
1584
+ request: IncomingMessage,
1585
+ ) => string | false
1586
+ path?: string | undefined
1587
+ noServer?: boolean | undefined
1588
+ clientTracking?: boolean | undefined
1589
+ perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
1590
+ maxPayload?: number | undefined
1591
+ skipUTF8Validation?: boolean | undefined
1592
+ WebSocket?: typeof WebSocket.WebSocket | undefined
1593
+ }
1701
1594
 
1702
- interface EnvironmentResolveOptions {
1703
- /**
1704
- * @default ['browser', 'module', 'jsnext:main', 'jsnext']
1705
- */
1706
- mainFields?: string[];
1707
- conditions?: string[];
1708
- externalConditions?: string[];
1709
- /**
1710
- * @default ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']
1711
- */
1712
- extensions?: string[];
1713
- dedupe?: string[];
1714
- /**
1715
- * Prevent listed dependencies from being externalized and will get bundled in build.
1716
- * Only works in server environments for now. Previously this was `ssr.noExternal`.
1717
- * @experimental
1718
- */
1719
- noExternal?: string | RegExp | (string | RegExp)[] | true;
1720
- /**
1721
- * Externalize the given dependencies and their transitive dependencies.
1722
- * Only works in server environments for now. Previously this was `ssr.external`.
1723
- * @experimental
1724
- */
1725
- external?: string[] | true;
1726
- }
1727
- interface ResolveOptions extends EnvironmentResolveOptions {
1728
- /**
1729
- * @default false
1730
- */
1731
- preserveSymlinks?: boolean;
1732
- }
1733
- interface ResolvePluginOptions {
1734
- root: string;
1735
- isBuild: boolean;
1736
- isProduction: boolean;
1737
- packageCache?: PackageCache;
1738
- fsUtils?: FsUtils;
1739
- /**
1740
- * src code mode also attempts the following:
1741
- * - resolving /xxx as URLs
1742
- * - resolving bare imports from optimized deps
1743
- */
1744
- asSrc?: boolean;
1745
- tryIndex?: boolean;
1746
- tryPrefix?: string;
1747
- preferRelative?: boolean;
1748
- isRequire?: boolean;
1749
- webCompatible?: boolean;
1750
- isFromTsImporter?: boolean;
1751
- scan?: boolean;
1752
- ssrOptimizeCheck?: boolean;
1753
- /**
1754
- * @deprecated environment.config are used instead
1755
- */
1756
- ssrConfig?: SSROptions;
1757
- }
1758
- interface InternalResolveOptions extends Required<ResolveOptions>, ResolvePluginOptions {
1759
- }
1760
- type InternalResolveOptionsWithOverrideConditions = InternalResolveOptions & {};
1595
+ interface AddressInfo {
1596
+ address: string
1597
+ family: string
1598
+ port: number
1599
+ }
1761
1600
 
1762
- /** Cache for package.json resolution and package.json contents */
1763
- type PackageCache = Map<string, PackageData>;
1764
- interface PackageData {
1765
- dir: string;
1766
- hasSideEffects: (id: string) => boolean | 'no-treeshake' | null;
1767
- setResolvedCache: (key: string, entry: string, options: InternalResolveOptionsWithOverrideConditions) => void;
1768
- getResolvedCache: (key: string, options: InternalResolveOptionsWithOverrideConditions) => string | undefined;
1769
- data: {
1770
- [field: string]: any;
1771
- name: string;
1772
- type: string;
1773
- version: string;
1774
- main: string;
1775
- module: string;
1776
- browser: string | Record<string, string | false>;
1777
- exports: string | Record<string, any> | string[];
1778
- imports: Record<string, any>;
1779
- dependencies: Record<string, string>;
1780
- };
1781
- }
1601
+ // WebSocket Server
1602
+ class Server<T extends WebSocket = WebSocket> extends EventEmitter {
1603
+ options: ServerOptions
1604
+ path: string
1605
+ clients: Set<T>
1782
1606
 
1783
- interface BuildEnvironmentOptions {
1784
- /**
1785
- * Compatibility transform target. The transform is performed with esbuild
1786
- * and the lowest supported target is es2015/es6. Note this only handles
1787
- * syntax transformation and does not cover polyfills (except for dynamic
1788
- * import)
1789
- *
1790
- * Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules,
1791
- * transpile targeting browsers that natively support dynamic es module imports.
1792
- * https://caniuse.com/es6-module-dynamic-import
1793
- *
1794
- * Another special value is 'esnext' - which only performs minimal transpiling
1795
- * (for minification compat) and assumes native dynamic imports support.
1796
- *
1797
- * For custom targets, see https://esbuild.github.io/api/#target and
1798
- * https://esbuild.github.io/content-types/#javascript for more details.
1799
- * @default 'modules'
1800
- */
1801
- target?: 'modules' | esbuild_TransformOptions['target'] | false;
1802
- /**
1803
- * whether to inject module preload polyfill.
1804
- * Note: does not apply to library mode.
1805
- * @default true
1806
- * @deprecated use `modulePreload.polyfill` instead
1807
- */
1808
- polyfillModulePreload?: boolean;
1809
- /**
1810
- * Configure module preload
1811
- * Note: does not apply to library mode.
1812
- * @default true
1813
- */
1814
- modulePreload?: boolean | ModulePreloadOptions;
1815
- /**
1816
- * Directory relative from `root` where build output will be placed. If the
1817
- * directory exists, it will be removed before the build.
1818
- * @default 'dist'
1819
- */
1820
- outDir?: string;
1821
- /**
1822
- * Directory relative from `outDir` where the built js/css/image assets will
1823
- * be placed.
1824
- * @default 'assets'
1825
- */
1826
- assetsDir?: string;
1607
+ constructor(options?: ServerOptions, callback?: () => void)
1608
+
1609
+ address(): AddressInfo | string
1610
+ close(cb?: (err?: Error) => void): void
1611
+ handleUpgrade(
1612
+ request: IncomingMessage,
1613
+ socket: Duplex,
1614
+ upgradeHead: Buffer,
1615
+ callback: (client: T, request: IncomingMessage) => void,
1616
+ ): void
1617
+ shouldHandle(request: IncomingMessage): boolean | Promise<boolean>
1618
+
1619
+ // Events
1620
+ on(
1621
+ event: 'connection',
1622
+ cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1623
+ ): this
1624
+ on(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1625
+ on(
1626
+ event: 'headers',
1627
+ cb: (
1628
+ this: Server<T>,
1629
+ headers: string[],
1630
+ request: IncomingMessage,
1631
+ ) => void,
1632
+ ): this
1633
+ on(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1634
+ on(
1635
+ event: string | symbol,
1636
+ listener: (this: Server<T>, ...args: any[]) => void,
1637
+ ): this
1638
+
1639
+ once(
1640
+ event: 'connection',
1641
+ cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1642
+ ): this
1643
+ once(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1644
+ once(
1645
+ event: 'headers',
1646
+ cb: (
1647
+ this: Server<T>,
1648
+ headers: string[],
1649
+ request: IncomingMessage,
1650
+ ) => void,
1651
+ ): this
1652
+ once(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1653
+ once(
1654
+ event: string | symbol,
1655
+ listener: (this: Server<T>, ...args: any[]) => void,
1656
+ ): this
1657
+
1658
+ off(
1659
+ event: 'connection',
1660
+ cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1661
+ ): this
1662
+ off(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1663
+ off(
1664
+ event: 'headers',
1665
+ cb: (
1666
+ this: Server<T>,
1667
+ headers: string[],
1668
+ request: IncomingMessage,
1669
+ ) => void,
1670
+ ): this
1671
+ off(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1672
+ off(
1673
+ event: string | symbol,
1674
+ listener: (this: Server<T>, ...args: any[]) => void,
1675
+ ): this
1676
+
1677
+ addListener(
1678
+ event: 'connection',
1679
+ cb: (client: T, request: IncomingMessage) => void,
1680
+ ): this
1681
+ addListener(event: 'error', cb: (err: Error) => void): this
1682
+ addListener(
1683
+ event: 'headers',
1684
+ cb: (headers: string[], request: IncomingMessage) => void,
1685
+ ): this
1686
+ addListener(event: 'close' | 'listening', cb: () => void): this
1687
+ addListener(
1688
+ event: string | symbol,
1689
+ listener: (...args: any[]) => void,
1690
+ ): this
1691
+
1692
+ removeListener(event: 'connection', cb: (client: T) => void): this
1693
+ removeListener(event: 'error', cb: (err: Error) => void): this
1694
+ removeListener(
1695
+ event: 'headers',
1696
+ cb: (headers: string[], request: IncomingMessage) => void,
1697
+ ): this
1698
+ removeListener(event: 'close' | 'listening', cb: () => void): this
1699
+ removeListener(
1700
+ event: string | symbol,
1701
+ listener: (...args: any[]) => void,
1702
+ ): this
1703
+ }
1704
+
1705
+ const WebSocketServer: typeof Server
1706
+ interface WebSocketServer extends Server {}
1707
+ const WebSocket: typeof WebSocketAlias
1708
+ interface WebSocket extends WebSocketAlias {}
1709
+
1710
+ // WebSocket stream
1711
+ function createWebSocketStream(
1712
+ websocket: WebSocket,
1713
+ options?: DuplexOptions,
1714
+ ): Duplex
1715
+ }
1716
+
1717
+ type WebSocketCustomListener<T> = (data: T, client: WebSocketClient, invoke?: 'send' | `send:${string}`) => void;
1718
+ declare const isWebSocketServer: unique symbol;
1719
+ interface WebSocketServer extends NormalizedHotChannel {
1827
1720
  /**
1828
- * Static asset files smaller than this number (in bytes) will be inlined as
1829
- * base64 strings. Default limit is `4096` (4 KiB). Set to `0` to disable.
1830
- * @default 4096
1721
+ * Handle custom event emitted by `import.meta.hot.send`
1831
1722
  */
1832
- assetsInlineLimit?: number | ((filePath: string, content: Buffer) => boolean | undefined);
1723
+ on: WebSocket.Server['on'] & {
1724
+ <T extends string>(event: T, listener: WebSocketCustomListener<InferCustomEventPayload<T>>): void;
1725
+ };
1833
1726
  /**
1834
- * Whether to code-split CSS. When enabled, CSS in async chunks will be
1835
- * inlined as strings in the chunk and inserted via dynamically created
1836
- * style tags when the chunk is loaded.
1837
- * @default true
1727
+ * Unregister event listener.
1838
1728
  */
1839
- cssCodeSplit?: boolean;
1729
+ off: WebSocket.Server['off'] & {
1730
+ (event: string, listener: Function): void;
1731
+ };
1840
1732
  /**
1841
- * An optional separate target for CSS minification.
1842
- * As esbuild only supports configuring targets to mainstream
1843
- * browsers, users may need this option when they are targeting
1844
- * a niche browser that comes with most modern JavaScript features
1845
- * but has poor CSS support, e.g. Android WeChat WebView, which
1846
- * doesn't support the #RGBA syntax.
1847
- * @default target
1733
+ * Listen on port and host
1848
1734
  */
1849
- cssTarget?: esbuild_TransformOptions['target'] | false;
1735
+ listen(): void;
1850
1736
  /**
1851
- * Override CSS minification specifically instead of defaulting to `build.minify`,
1852
- * so you can configure minification for JS and CSS separately.
1853
- * @default 'esbuild'
1737
+ * Disconnect all clients and terminate the server.
1854
1738
  */
1855
- cssMinify?: boolean | 'esbuild' | 'lightningcss';
1739
+ close(): Promise<void>;
1740
+ [isWebSocketServer]: true;
1856
1741
  /**
1857
- * If `true`, a separate sourcemap file will be created. If 'inline', the
1858
- * sourcemap will be appended to the resulting output file as data URI.
1859
- * 'hidden' works like `true` except that the corresponding sourcemap
1860
- * comments in the bundled files are suppressed.
1861
- * @default false
1742
+ * Get all connected clients.
1862
1743
  */
1863
- sourcemap?: boolean | 'inline' | 'hidden';
1744
+ clients: Set<WebSocketClient>;
1745
+ }
1746
+ interface WebSocketClient extends HotChannelClient {
1864
1747
  /**
1865
- * Set to `false` to disable minification, or specify the minifier to use.
1866
- * Available options are 'terser' or 'esbuild'.
1867
- * @default 'esbuild'
1748
+ * The raw WebSocket instance
1749
+ * @advanced
1868
1750
  */
1869
- minify?: boolean | 'terser' | 'esbuild';
1751
+ socket: WebSocket;
1752
+ }
1753
+
1754
+ interface DevEnvironmentContext {
1755
+ hot: boolean;
1756
+ transport?: HotChannel | WebSocketServer;
1757
+ options?: EnvironmentOptions;
1758
+ remoteRunner?: {
1759
+ inlineSourceMap?: boolean;
1760
+ };
1761
+ depsOptimizer?: DepsOptimizer;
1762
+ }
1763
+ declare class DevEnvironment extends BaseEnvironment {
1764
+ mode: "dev";
1765
+ moduleGraph: EnvironmentModuleGraph;
1766
+ depsOptimizer?: DepsOptimizer;
1767
+ get pluginContainer(): EnvironmentPluginContainer;
1870
1768
  /**
1871
- * Options for terser
1872
- * https://terser.org/docs/api-reference#minify-options
1769
+ * Hot channel for this environment. If not provided or disabled,
1770
+ * it will be a noop channel that does nothing.
1873
1771
  *
1874
- * In addition, you can also pass a `maxWorkers: number` option to specify the
1875
- * max number of workers to spawn. Defaults to the number of CPUs minus 1.
1876
- */
1877
- terserOptions?: TerserOptions;
1878
- /**
1879
- * Will be merged with internal rollup options.
1880
- * https://rollupjs.org/configuration-options/
1881
- */
1882
- rollupOptions?: RollupOptions;
1883
- /**
1884
- * Options to pass on to `@rollup/plugin-commonjs`
1885
- */
1886
- commonjsOptions?: RollupCommonJSOptions;
1887
- /**
1888
- * Options to pass on to `@rollup/plugin-dynamic-import-vars`
1889
- */
1890
- dynamicImportVarsOptions?: RollupDynamicImportVarsOptions;
1891
- /**
1892
- * Whether to write bundle to disk
1893
- * @default true
1772
+ * @example
1773
+ * environment.hot.send({ type: 'full-reload' })
1894
1774
  */
1895
- write?: boolean;
1775
+ hot: NormalizedHotChannel;
1776
+ constructor(name: string, config: ResolvedConfig, context: DevEnvironmentContext);
1777
+ init(options?: {
1778
+ watcher?: FSWatcher;
1779
+ /**
1780
+ * the previous instance used for the environment with the same name
1781
+ *
1782
+ * when using, the consumer should check if it's an instance generated from the same class or factory function
1783
+ */
1784
+ previousInstance?: DevEnvironment;
1785
+ }): Promise<void>;
1896
1786
  /**
1897
- * Empty outDir on write.
1898
- * @default true when outDir is a sub directory of project root
1787
+ * When the dev server is restarted, the methods are called in the following order:
1788
+ * - new instance `init`
1789
+ * - previous instance `close`
1790
+ * - new instance `listen`
1899
1791
  */
1900
- emptyOutDir?: boolean | null;
1792
+ listen(server: ViteDevServer): Promise<void>;
1793
+ fetchModule(id: string, importer?: string, options?: FetchFunctionOptions): Promise<FetchResult>;
1794
+ reloadModule(module: EnvironmentModuleNode): Promise<void>;
1795
+ transformRequest(url: string): Promise<TransformResult | null>;
1796
+ warmupRequest(url: string): Promise<void>;
1797
+ close(): Promise<void>;
1901
1798
  /**
1902
- * Copy the public directory to outDir on write.
1903
- * @default true
1799
+ * Calling `await environment.waitForRequestsIdle(id)` will wait until all static imports
1800
+ * are processed after the first transformRequest call. If called from a load or transform
1801
+ * plugin hook, the id needs to be passed as a parameter to avoid deadlocks.
1802
+ * Calling this function after the first static imports section of the module graph has been
1803
+ * processed will resolve immediately.
1804
+ * @experimental
1904
1805
  */
1905
- copyPublicDir?: boolean;
1906
- /**
1907
- * Whether to emit a .vite/manifest.json under assets dir to map hash-less filenames
1908
- * to their hashed versions. Useful when you want to generate your own HTML
1909
- * instead of using the one generated by Vite.
1910
- *
1911
- * Example:
1912
- *
1913
- * ```json
1914
- * {
1915
- * "main.js": {
1916
- * "file": "main.68fe3fad.js",
1917
- * "css": "main.e6b63442.css",
1918
- * "imports": [...],
1919
- * "dynamicImports": [...]
1920
- * }
1921
- * }
1922
- * ```
1923
- * @default false
1924
- */
1925
- manifest?: boolean | string;
1926
- /**
1927
- * Build in library mode. The value should be the global name of the lib in
1928
- * UMD mode. This will produce esm + cjs + umd bundle formats with default
1929
- * configurations that are suitable for distributing libraries.
1930
- * @default false
1931
- */
1932
- lib?: LibraryOptions | false;
1933
- /**
1934
- * Produce SSR oriented build. Note this requires specifying SSR entry via
1935
- * `rollupOptions.input`.
1936
- * @default false
1937
- */
1938
- ssr?: boolean | string;
1939
- /**
1940
- * Generate SSR manifest for determining style links and asset preload
1941
- * directives in production.
1942
- * @default false
1943
- */
1944
- ssrManifest?: boolean | string;
1945
- /**
1946
- * Emit assets during SSR.
1947
- * @default false
1948
- */
1949
- ssrEmitAssets?: boolean;
1950
- /**
1951
- * Emit assets during build. Frameworks can set environments.ssr.build.emitAssets
1952
- * By default, it is true for the client and false for other environments.
1953
- */
1954
- emitAssets?: boolean;
1955
- /**
1956
- * Set to false to disable reporting compressed chunk sizes.
1957
- * Can slightly improve build speed.
1958
- * @default true
1959
- */
1960
- reportCompressedSize?: boolean;
1961
- /**
1962
- * Adjust chunk size warning limit (in kB).
1963
- * @default 500
1964
- */
1965
- chunkSizeWarningLimit?: number;
1966
- /**
1967
- * Rollup watch options
1968
- * https://rollupjs.org/configuration-options/#watch
1969
- * @default null
1970
- */
1971
- watch?: WatcherOptions | null;
1972
- /**
1973
- * create the Build Environment instance
1974
- */
1975
- createEnvironment?: (name: string, config: ResolvedConfig) => Promise<BuildEnvironment> | BuildEnvironment;
1976
- }
1977
- type BuildOptions = BuildEnvironmentOptions;
1978
- interface LibraryOptions {
1979
- /**
1980
- * Path of library entry
1981
- */
1982
- entry: InputOption;
1983
- /**
1984
- * The name of the exposed global variable. Required when the `formats` option includes
1985
- * `umd` or `iife`
1986
- */
1987
- name?: string;
1988
- /**
1989
- * Output bundle formats
1990
- * @default ['es', 'umd']
1991
- */
1992
- formats?: LibraryFormats[];
1993
- /**
1994
- * The name of the package file output. The default file name is the name option
1995
- * of the project package.json. It can also be defined as a function taking the
1996
- * format as an argument.
1997
- */
1998
- fileName?: string | ((format: ModuleFormat, entryName: string) => string);
1999
- /**
2000
- * The name of the CSS file output if the library imports CSS. Defaults to the
2001
- * same value as `build.lib.fileName` if it's set a string, otherwise it falls
2002
- * back to the name option of the project package.json.
2003
- */
2004
- cssFileName?: string;
2005
- }
2006
- type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife' | 'system';
2007
- interface ModulePreloadOptions {
2008
- /**
2009
- * Whether to inject a module preload polyfill.
2010
- * Note: does not apply to library mode.
2011
- * @default true
2012
- */
2013
- polyfill?: boolean;
2014
- /**
2015
- * Resolve the list of dependencies to preload for a given dynamic import
2016
- * @experimental
2017
- */
2018
- resolveDependencies?: ResolveModulePreloadDependenciesFn;
2019
- }
2020
- interface ResolvedModulePreloadOptions {
2021
- polyfill: boolean;
2022
- resolveDependencies?: ResolveModulePreloadDependenciesFn;
2023
- }
2024
- type ResolveModulePreloadDependenciesFn = (filename: string, deps: string[], context: {
2025
- hostId: string;
2026
- hostType: 'html' | 'js';
2027
- }) => string[];
2028
- interface ResolvedBuildEnvironmentOptions extends Required<Omit<BuildEnvironmentOptions, 'polyfillModulePreload'>> {
2029
- modulePreload: false | ResolvedModulePreloadOptions;
2030
- }
2031
- interface ResolvedBuildOptions extends Required<Omit<BuildOptions, 'polyfillModulePreload'>> {
2032
- modulePreload: false | ResolvedModulePreloadOptions;
2033
- }
2034
- /**
2035
- * Bundles a single environment for production.
2036
- * Returns a Promise containing the build result.
2037
- */
2038
- declare function build(inlineConfig?: InlineConfig): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
2039
- type RenderBuiltAssetUrl = (filename: string, type: {
2040
- type: 'asset' | 'public';
2041
- hostId: string;
2042
- hostType: 'js' | 'css' | 'html';
2043
- ssr: boolean;
2044
- }) => string | {
2045
- relative?: boolean;
2046
- runtime?: string;
2047
- } | undefined;
2048
- declare class BuildEnvironment extends BaseEnvironment {
2049
- mode: "build";
2050
- constructor(name: string, config: ResolvedConfig, setup?: {
2051
- options?: EnvironmentOptions;
2052
- });
2053
- init(): Promise<void>;
2054
- }
2055
- interface ViteBuilder {
2056
- environments: Record<string, BuildEnvironment>;
2057
- config: ResolvedConfig;
2058
- buildApp(): Promise<void>;
2059
- build(environment: BuildEnvironment): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
2060
- }
2061
- interface BuilderOptions {
2062
- /**
2063
- * Whether to share the config instance among environments to align with the behavior of dev server.
2064
- *
2065
- * @default false
2066
- * @experimental
2067
- */
2068
- sharedConfigBuild?: boolean;
2069
- /**
2070
- * Whether to share the plugin instances among environments to align with the behavior of dev server.
2071
- *
2072
- * @default false
2073
- * @experimental
2074
- */
2075
- sharedPlugins?: boolean;
2076
- buildApp?: (builder: ViteBuilder) => Promise<void>;
2077
- }
2078
- type ResolvedBuilderOptions = Required<BuilderOptions>;
2079
- /**
2080
- * Creates a ViteBuilder to orchestrate building multiple environments.
2081
- * @experimental
2082
- */
2083
- declare function createBuilder(inlineConfig?: InlineConfig, useLegacyBuilder?: null | boolean): Promise<ViteBuilder>;
2084
-
2085
- type Environment = DevEnvironment | BuildEnvironment | UnknownEnvironment;
2086
-
2087
- declare class EnvironmentPluginContainer {
2088
- environment: Environment;
2089
- plugins: Plugin[];
2090
- watcher?: FSWatcher | undefined;
2091
- private _pluginContextMap;
2092
- private _resolvedRollupOptions?;
2093
- private _processesing;
2094
- private _seenResolves;
2095
- private _moduleNodeToLoadAddedImports;
2096
- getSortedPluginHooks: PluginHookUtils['getSortedPluginHooks'];
2097
- getSortedPlugins: PluginHookUtils['getSortedPlugins'];
2098
- moduleGraph: EnvironmentModuleGraph | undefined;
2099
- watchFiles: Set<string>;
2100
- minimalContext: MinimalPluginContext;
2101
- private _started;
2102
- private _buildStartPromise;
2103
- private _closed;
2104
- private _updateModuleLoadAddedImports;
2105
- private _getAddedImports;
2106
- getModuleInfo(id: string): ModuleInfo | null;
2107
- private handleHookPromise;
2108
- get options(): InputOptions;
2109
- resolveRollupOptions(): Promise<InputOptions>;
2110
- private _getPluginContext;
2111
- private hookParallel;
2112
- buildStart(_options?: InputOptions): Promise<void>;
2113
- resolveId(rawId: string, importer?: string | undefined, options?: {
2114
- attributes?: Record<string, string>;
2115
- custom?: CustomPluginOptions;
2116
- skip?: Set<Plugin>;
2117
- isEntry?: boolean;
2118
- }): Promise<PartialResolvedId | null>;
2119
- load(id: string): Promise<LoadResult | null>;
2120
- transform(code: string, id: string, options?: {
2121
- inMap?: SourceDescription['map'];
2122
- }): Promise<{
2123
- code: string;
2124
- map: SourceMap | {
2125
- mappings: '';
2126
- } | null;
2127
- }>;
2128
- watchChange(id: string, change: {
2129
- event: 'create' | 'update' | 'delete';
2130
- }): Promise<void>;
2131
- close(): Promise<void>;
2132
- }
2133
- declare class PluginContainer {
2134
- private environments;
2135
- constructor(environments: Record<string, Environment>);
2136
- private _getEnvironment;
2137
- private _getPluginContainer;
2138
- getModuleInfo(id: string): ModuleInfo | null;
2139
- get options(): InputOptions;
2140
- buildStart(_options?: InputOptions): Promise<void>;
2141
- watchChange(id: string, change: {
2142
- event: 'create' | 'update' | 'delete';
2143
- }): Promise<void>;
2144
- resolveId(rawId: string, importer?: string, options?: {
2145
- attributes?: Record<string, string>;
2146
- custom?: CustomPluginOptions;
2147
- skip?: Set<Plugin>;
2148
- ssr?: boolean;
2149
- isEntry?: boolean;
2150
- }): Promise<PartialResolvedId | null>;
2151
- load(id: string, options?: {
2152
- ssr?: boolean;
2153
- }): Promise<LoadResult | null>;
2154
- transform(code: string, id: string, options?: {
2155
- ssr?: boolean;
2156
- environment?: Environment;
2157
- inMap?: SourceDescription['map'];
2158
- }): Promise<{
2159
- code: string;
2160
- map: SourceMap | {
2161
- mappings: '';
2162
- } | null;
2163
- }>;
2164
- close(): Promise<void>;
1806
+ waitForRequestsIdle(ignoredId?: string): Promise<void>;
2165
1807
  }
2166
1808
 
2167
- // Modified and inlined to avoid extra dependency
2168
- // Source: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts
2169
-
2170
- declare const WebSocketAlias: typeof WebSocket
2171
- interface WebSocketAlias extends WebSocket {}
2172
-
2173
- // WebSocket socket.
2174
- declare class WebSocket extends EventEmitter {
2175
- /** The connection is not yet open. */
2176
- static readonly CONNECTING: 0
2177
- /** The connection is open and ready to communicate. */
2178
- static readonly OPEN: 1
2179
- /** The connection is in the process of closing. */
2180
- static readonly CLOSING: 2
2181
- /** The connection is closed. */
2182
- static readonly CLOSED: 3
2183
-
2184
- binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments'
2185
- readonly bufferedAmount: number
2186
- readonly extensions: string
2187
- /** Indicates whether the websocket is paused */
2188
- readonly isPaused: boolean
2189
- readonly protocol: string
2190
- /** The current state of the connection */
2191
- readonly readyState:
2192
- | typeof WebSocket.CONNECTING
2193
- | typeof WebSocket.OPEN
2194
- | typeof WebSocket.CLOSING
2195
- | typeof WebSocket.CLOSED
2196
- readonly url: string
2197
-
2198
- /** The connection is not yet open. */
2199
- readonly CONNECTING: 0
2200
- /** The connection is open and ready to communicate. */
2201
- readonly OPEN: 1
2202
- /** The connection is in the process of closing. */
2203
- readonly CLOSING: 2
2204
- /** The connection is closed. */
2205
- readonly CLOSED: 3
2206
-
2207
- onopen: ((event: WebSocket.Event) => void) | null
2208
- onerror: ((event: WebSocket.ErrorEvent) => void) | null
2209
- onclose: ((event: WebSocket.CloseEvent) => void) | null
2210
- onmessage: ((event: WebSocket.MessageEvent) => void) | null
2211
-
2212
- constructor(address: null)
2213
- constructor(
2214
- address: string | URL,
2215
- options?: WebSocket.ClientOptions | ClientRequestArgs,
2216
- )
2217
- constructor(
2218
- address: string | URL,
2219
- protocols?: string | string[],
2220
- options?: WebSocket.ClientOptions | ClientRequestArgs,
2221
- )
2222
-
2223
- close(code?: number, data?: string | Buffer): void
2224
- ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void
2225
- pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void
2226
- send(data: any, cb?: (err?: Error) => void): void
2227
- send(
2228
- data: any,
2229
- options: {
2230
- mask?: boolean | undefined
2231
- binary?: boolean | undefined
2232
- compress?: boolean | undefined
2233
- fin?: boolean | undefined
2234
- },
2235
- cb?: (err?: Error) => void,
2236
- ): void
2237
- terminate(): void
2238
-
1809
+ interface RollupCommonJSOptions {
1810
+ /**
1811
+ * A minimatch pattern, or array of patterns, which specifies the files in
1812
+ * the build the plugin should operate on. By default, all files with
1813
+ * extension `".cjs"` or those in `extensions` are included, but you can
1814
+ * narrow this list by only including specific files. These files will be
1815
+ * analyzed and transpiled if either the analysis does not find ES module
1816
+ * specific statements or `transformMixedEsModules` is `true`.
1817
+ * @default undefined
1818
+ */
1819
+ include?: string | RegExp | readonly (string | RegExp)[]
1820
+ /**
1821
+ * A minimatch pattern, or array of patterns, which specifies the files in
1822
+ * the build the plugin should _ignore_. By default, all files with
1823
+ * extensions other than those in `extensions` or `".cjs"` are ignored, but you
1824
+ * can exclude additional files. See also the `include` option.
1825
+ * @default undefined
1826
+ */
1827
+ exclude?: string | RegExp | readonly (string | RegExp)[]
1828
+ /**
1829
+ * For extensionless imports, search for extensions other than .js in the
1830
+ * order specified. Note that you need to make sure that non-JavaScript files
1831
+ * are transpiled by another plugin first.
1832
+ * @default [ '.js' ]
1833
+ */
1834
+ extensions?: ReadonlyArray<string>
1835
+ /**
1836
+ * If true then uses of `global` won't be dealt with by this plugin
1837
+ * @default false
1838
+ */
1839
+ ignoreGlobal?: boolean
1840
+ /**
1841
+ * If false, skips source map generation for CommonJS modules. This will
1842
+ * improve performance.
1843
+ * @default true
1844
+ */
1845
+ sourceMap?: boolean
1846
+ /**
1847
+ * Some `require` calls cannot be resolved statically to be translated to
1848
+ * imports.
1849
+ * When this option is set to `false`, the generated code will either
1850
+ * directly throw an error when such a call is encountered or, when
1851
+ * `dynamicRequireTargets` is used, when such a call cannot be resolved with a
1852
+ * configured dynamic require target.
1853
+ * Setting this option to `true` will instead leave the `require` call in the
1854
+ * code or use it as a fallback for `dynamicRequireTargets`.
1855
+ * @default false
1856
+ */
1857
+ ignoreDynamicRequires?: boolean
2239
1858
  /**
2240
- * Pause the websocket causing it to stop emitting events. Some events can still be
2241
- * emitted after this is called, until all buffered data is consumed. This method
2242
- * is a noop if the ready state is `CONNECTING` or `CLOSED`.
1859
+ * Instructs the plugin whether to enable mixed module transformations. This
1860
+ * is useful in scenarios with modules that contain a mix of ES `import`
1861
+ * statements and CommonJS `require` expressions. Set to `true` if `require`
1862
+ * calls should be transformed to imports in mixed modules, or `false` if the
1863
+ * `require` expressions should survive the transformation. The latter can be
1864
+ * important if the code contains environment detection, or you are coding
1865
+ * for an environment with special treatment for `require` calls such as
1866
+ * ElectronJS. See also the `ignore` option.
1867
+ * @default false
2243
1868
  */
2244
- pause(): void
1869
+ transformMixedEsModules?: boolean
2245
1870
  /**
2246
- * Make a paused socket resume emitting events. This method is a noop if the ready
2247
- * state is `CONNECTING` or `CLOSED`.
1871
+ * By default, this plugin will try to hoist `require` statements as imports
1872
+ * to the top of each file. While this works well for many code bases and
1873
+ * allows for very efficient ESM output, it does not perfectly capture
1874
+ * CommonJS semantics as the order of side effects like log statements may
1875
+ * change. But it is especially problematic when there are circular `require`
1876
+ * calls between CommonJS modules as those often rely on the lazy execution of
1877
+ * nested `require` calls.
1878
+ *
1879
+ * Setting this option to `true` will wrap all CommonJS files in functions
1880
+ * which are executed when they are required for the first time, preserving
1881
+ * NodeJS semantics. Note that this can have an impact on the size and
1882
+ * performance of the generated code.
1883
+ *
1884
+ * The default value of `"auto"` will only wrap CommonJS files when they are
1885
+ * part of a CommonJS dependency cycle, e.g. an index file that is required by
1886
+ * many of its dependencies. All other CommonJS files are hoisted. This is the
1887
+ * recommended setting for most code bases.
1888
+ *
1889
+ * `false` will entirely prevent wrapping and hoist all files. This may still
1890
+ * work depending on the nature of cyclic dependencies but will often cause
1891
+ * problems.
1892
+ *
1893
+ * You can also provide a minimatch pattern, or array of patterns, to only
1894
+ * specify a subset of files which should be wrapped in functions for proper
1895
+ * `require` semantics.
1896
+ *
1897
+ * `"debug"` works like `"auto"` but after bundling, it will display a warning
1898
+ * containing a list of ids that have been wrapped which can be used as
1899
+ * minimatch pattern for fine-tuning.
1900
+ * @default "auto"
2248
1901
  */
2249
- resume(): void
2250
-
2251
- // HTML5 WebSocket events
2252
- addEventListener(
2253
- method: 'message',
2254
- cb: (event: WebSocket.MessageEvent) => void,
2255
- options?: WebSocket.EventListenerOptions,
2256
- ): void
2257
- addEventListener(
2258
- method: 'close',
2259
- cb: (event: WebSocket.CloseEvent) => void,
2260
- options?: WebSocket.EventListenerOptions,
2261
- ): void
2262
- addEventListener(
2263
- method: 'error',
2264
- cb: (event: WebSocket.ErrorEvent) => void,
2265
- options?: WebSocket.EventListenerOptions,
2266
- ): void
2267
- addEventListener(
2268
- method: 'open',
2269
- cb: (event: WebSocket.Event) => void,
2270
- options?: WebSocket.EventListenerOptions,
2271
- ): void
2272
-
2273
- removeEventListener(
2274
- method: 'message',
2275
- cb: (event: WebSocket.MessageEvent) => void,
2276
- ): void
2277
- removeEventListener(
2278
- method: 'close',
2279
- cb: (event: WebSocket.CloseEvent) => void,
2280
- ): void
2281
- removeEventListener(
2282
- method: 'error',
2283
- cb: (event: WebSocket.ErrorEvent) => void,
2284
- ): void
2285
- removeEventListener(
2286
- method: 'open',
2287
- cb: (event: WebSocket.Event) => void,
2288
- ): void
2289
-
2290
- // Events
2291
- on(
2292
- event: 'close',
2293
- listener: (this: WebSocket, code: number, reason: Buffer) => void,
2294
- ): this
2295
- on(event: 'error', listener: (this: WebSocket, err: Error) => void): this
2296
- on(
2297
- event: 'upgrade',
2298
- listener: (this: WebSocket, request: IncomingMessage) => void,
2299
- ): this
2300
- on(
2301
- event: 'message',
2302
- listener: (
2303
- this: WebSocket,
2304
- data: WebSocket.RawData,
2305
- isBinary: boolean,
2306
- ) => void,
2307
- ): this
2308
- on(event: 'open', listener: (this: WebSocket) => void): this
2309
- on(
2310
- event: 'ping' | 'pong',
2311
- listener: (this: WebSocket, data: Buffer) => void,
2312
- ): this
2313
- on(
2314
- event: 'unexpected-response',
2315
- listener: (
2316
- this: WebSocket,
2317
- request: ClientRequest,
2318
- response: IncomingMessage,
2319
- ) => void,
2320
- ): this
2321
- on(
2322
- event: string | symbol,
2323
- listener: (this: WebSocket, ...args: any[]) => void,
2324
- ): this
2325
-
2326
- once(
2327
- event: 'close',
2328
- listener: (this: WebSocket, code: number, reason: Buffer) => void,
2329
- ): this
2330
- once(event: 'error', listener: (this: WebSocket, err: Error) => void): this
2331
- once(
2332
- event: 'upgrade',
2333
- listener: (this: WebSocket, request: IncomingMessage) => void,
2334
- ): this
2335
- once(
2336
- event: 'message',
2337
- listener: (
2338
- this: WebSocket,
2339
- data: WebSocket.RawData,
2340
- isBinary: boolean,
2341
- ) => void,
2342
- ): this
2343
- once(event: 'open', listener: (this: WebSocket) => void): this
2344
- once(
2345
- event: 'ping' | 'pong',
2346
- listener: (this: WebSocket, data: Buffer) => void,
2347
- ): this
2348
- once(
2349
- event: 'unexpected-response',
2350
- listener: (
2351
- this: WebSocket,
2352
- request: ClientRequest,
2353
- response: IncomingMessage,
2354
- ) => void,
2355
- ): this
2356
- once(
2357
- event: string | symbol,
2358
- listener: (this: WebSocket, ...args: any[]) => void,
2359
- ): this
2360
-
2361
- off(
2362
- event: 'close',
2363
- listener: (this: WebSocket, code: number, reason: Buffer) => void,
2364
- ): this
2365
- off(event: 'error', listener: (this: WebSocket, err: Error) => void): this
2366
- off(
2367
- event: 'upgrade',
2368
- listener: (this: WebSocket, request: IncomingMessage) => void,
2369
- ): this
2370
- off(
2371
- event: 'message',
2372
- listener: (
2373
- this: WebSocket,
2374
- data: WebSocket.RawData,
2375
- isBinary: boolean,
2376
- ) => void,
2377
- ): this
2378
- off(event: 'open', listener: (this: WebSocket) => void): this
2379
- off(
2380
- event: 'ping' | 'pong',
2381
- listener: (this: WebSocket, data: Buffer) => void,
2382
- ): this
2383
- off(
2384
- event: 'unexpected-response',
2385
- listener: (
2386
- this: WebSocket,
2387
- request: ClientRequest,
2388
- response: IncomingMessage,
2389
- ) => void,
2390
- ): this
2391
- off(
2392
- event: string | symbol,
2393
- listener: (this: WebSocket, ...args: any[]) => void,
2394
- ): this
2395
-
2396
- addListener(
2397
- event: 'close',
2398
- listener: (code: number, reason: Buffer) => void,
2399
- ): this
2400
- addListener(event: 'error', listener: (err: Error) => void): this
2401
- addListener(
2402
- event: 'upgrade',
2403
- listener: (request: IncomingMessage) => void,
2404
- ): this
2405
- addListener(
2406
- event: 'message',
2407
- listener: (data: WebSocket.RawData, isBinary: boolean) => void,
2408
- ): this
2409
- addListener(event: 'open', listener: () => void): this
2410
- addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
2411
- addListener(
2412
- event: 'unexpected-response',
2413
- listener: (request: ClientRequest, response: IncomingMessage) => void,
2414
- ): this
2415
- addListener(event: string | symbol, listener: (...args: any[]) => void): this
2416
-
2417
- removeListener(
2418
- event: 'close',
2419
- listener: (code: number, reason: Buffer) => void,
2420
- ): this
2421
- removeListener(event: 'error', listener: (err: Error) => void): this
2422
- removeListener(
2423
- event: 'upgrade',
2424
- listener: (request: IncomingMessage) => void,
2425
- ): this
2426
- removeListener(
2427
- event: 'message',
2428
- listener: (data: WebSocket.RawData, isBinary: boolean) => void,
2429
- ): this
2430
- removeListener(event: 'open', listener: () => void): this
2431
- removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
2432
- removeListener(
2433
- event: 'unexpected-response',
2434
- listener: (request: ClientRequest, response: IncomingMessage) => void,
2435
- ): this
2436
- removeListener(
2437
- event: string | symbol,
2438
- listener: (...args: any[]) => void,
2439
- ): this
2440
- }
2441
-
2442
- declare namespace WebSocket {
1902
+ strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[]
1903
+ /**
1904
+ * Sometimes you have to leave require statements unconverted. Pass an array
1905
+ * containing the IDs or a `id => boolean` function.
1906
+ * @default []
1907
+ */
1908
+ ignore?: ReadonlyArray<string> | ((id: string) => boolean)
1909
+ /**
1910
+ * In most cases, where `require` calls are inside a `try-catch` clause,
1911
+ * they should be left unconverted as it requires an optional dependency
1912
+ * that may or may not be installed beside the rolled up package.
1913
+ * Due to the conversion of `require` to a static `import` - the call is
1914
+ * hoisted to the top of the file, outside the `try-catch` clause.
1915
+ *
1916
+ * - `true`: Default. All `require` calls inside a `try` will be left unconverted.
1917
+ * - `false`: All `require` calls inside a `try` will be converted as if the
1918
+ * `try-catch` clause is not there.
1919
+ * - `remove`: Remove all `require` calls from inside any `try` block.
1920
+ * - `string[]`: Pass an array containing the IDs to left unconverted.
1921
+ * - `((id: string) => boolean|'remove')`: Pass a function that controls
1922
+ * individual IDs.
1923
+ *
1924
+ * @default true
1925
+ */
1926
+ ignoreTryCatch?:
1927
+ | boolean
1928
+ | 'remove'
1929
+ | ReadonlyArray<string>
1930
+ | ((id: string) => boolean | 'remove')
2443
1931
  /**
2444
- * Data represents the raw message payload received over the WebSocket.
1932
+ * Controls how to render imports from external dependencies. By default,
1933
+ * this plugin assumes that all external dependencies are CommonJS. This
1934
+ * means they are rendered as default imports to be compatible with e.g.
1935
+ * NodeJS where ES modules can only import a default export from a CommonJS
1936
+ * dependency.
1937
+ *
1938
+ * If you set `esmExternals` to `true`, this plugin assumes that all
1939
+ * external dependencies are ES modules and respect the
1940
+ * `requireReturnsDefault` option. If that option is not set, they will be
1941
+ * rendered as namespace imports.
1942
+ *
1943
+ * You can also supply an array of ids to be treated as ES modules, or a
1944
+ * function that will be passed each external id to determine whether it is
1945
+ * an ES module.
1946
+ * @default false
2445
1947
  */
2446
- type RawData = Buffer | ArrayBuffer | Buffer[]
2447
-
1948
+ esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean)
2448
1949
  /**
2449
- * Data represents the message payload received over the WebSocket.
1950
+ * Controls what is returned when requiring an ES module from a CommonJS file.
1951
+ * When using the `esmExternals` option, this will also apply to external
1952
+ * modules. By default, this plugin will render those imports as namespace
1953
+ * imports i.e.
1954
+ *
1955
+ * ```js
1956
+ * // input
1957
+ * const foo = require('foo');
1958
+ *
1959
+ * // output
1960
+ * import * as foo from 'foo';
1961
+ * ```
1962
+ *
1963
+ * However, there are some situations where this may not be desired.
1964
+ * For these situations, you can change Rollup's behaviour either globally or
1965
+ * per module. To change it globally, set the `requireReturnsDefault` option
1966
+ * to one of the following values:
1967
+ *
1968
+ * - `false`: This is the default, requiring an ES module returns its
1969
+ * namespace. This is the only option that will also add a marker
1970
+ * `__esModule: true` to the namespace to support interop patterns in
1971
+ * CommonJS modules that are transpiled ES modules.
1972
+ * - `"namespace"`: Like `false`, requiring an ES module returns its
1973
+ * namespace, but the plugin does not add the `__esModule` marker and thus
1974
+ * creates more efficient code. For external dependencies when using
1975
+ * `esmExternals: true`, no additional interop code is generated.
1976
+ * - `"auto"`: This is complementary to how `output.exports: "auto"` works in
1977
+ * Rollup: If a module has a default export and no named exports, requiring
1978
+ * that module returns the default export. In all other cases, the namespace
1979
+ * is returned. For external dependencies when using `esmExternals: true`, a
1980
+ * corresponding interop helper is added.
1981
+ * - `"preferred"`: If a module has a default export, requiring that module
1982
+ * always returns the default export, no matter whether additional named
1983
+ * exports exist. This is similar to how previous versions of this plugin
1984
+ * worked. Again for external dependencies when using `esmExternals: true`,
1985
+ * an interop helper is added.
1986
+ * - `true`: This will always try to return the default export on require
1987
+ * without checking if it actually exists. This can throw at build time if
1988
+ * there is no default export. This is how external dependencies are handled
1989
+ * when `esmExternals` is not used. The advantage over the other options is
1990
+ * that, like `false`, this does not add an interop helper for external
1991
+ * dependencies, keeping the code lean.
1992
+ *
1993
+ * To change this for individual modules, you can supply a function for
1994
+ * `requireReturnsDefault` instead. This function will then be called once for
1995
+ * each required ES module or external dependency with the corresponding id
1996
+ * and allows you to return different values for different modules.
1997
+ * @default false
2450
1998
  */
2451
- type Data = string | Buffer | ArrayBuffer | Buffer[]
1999
+ requireReturnsDefault?:
2000
+ | boolean
2001
+ | 'auto'
2002
+ | 'preferred'
2003
+ | 'namespace'
2004
+ | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace')
2452
2005
 
2453
2006
  /**
2454
- * CertMeta represents the accepted types for certificate & key data.
2007
+ * @default "auto"
2455
2008
  */
2456
- type CertMeta = string | string[] | Buffer | Buffer[]
2457
-
2009
+ defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto')
2458
2010
  /**
2459
- * VerifyClientCallbackSync is a synchronous callback used to inspect the
2460
- * incoming message. The return value (boolean) of the function determines
2461
- * whether or not to accept the handshake.
2011
+ * Some modules contain dynamic `require` calls, or require modules that
2012
+ * contain circular dependencies, which are not handled well by static
2013
+ * imports. Including those modules as `dynamicRequireTargets` will simulate a
2014
+ * CommonJS (NodeJS-like) environment for them with support for dynamic
2015
+ * dependencies. It also enables `strictRequires` for those modules.
2016
+ *
2017
+ * Note: In extreme cases, this feature may result in some paths being
2018
+ * rendered as absolute in the final bundle. The plugin tries to avoid
2019
+ * exposing paths from the local machine, but if you are `dynamicRequirePaths`
2020
+ * with paths that are far away from your project's folder, that may require
2021
+ * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`.
2462
2022
  */
2463
- type VerifyClientCallbackSync = (info: {
2464
- origin: string
2465
- secure: boolean
2466
- req: IncomingMessage
2467
- }) => boolean
2023
+ dynamicRequireTargets?: string | ReadonlyArray<string>
2024
+ /**
2025
+ * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory
2026
+ * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/`
2027
+ * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your
2028
+ * home directory name. By default, it uses the current working directory.
2029
+ */
2030
+ dynamicRequireRoot?: string
2031
+ }
2468
2032
 
2033
+ interface RollupDynamicImportVarsOptions {
2469
2034
  /**
2470
- * VerifyClientCallbackAsync is an asynchronous callback used to inspect the
2471
- * incoming message. The return value (boolean) of the function determines
2472
- * whether or not to accept the handshake.
2035
+ * Files to include in this plugin (default all).
2036
+ * @default []
2473
2037
  */
2474
- type VerifyClientCallbackAsync = (
2475
- info: { origin: string; secure: boolean; req: IncomingMessage },
2476
- callback: (
2477
- res: boolean,
2478
- code?: number,
2479
- message?: string,
2480
- headers?: OutgoingHttpHeaders,
2481
- ) => void,
2482
- ) => void
2038
+ include?: string | RegExp | (string | RegExp)[]
2039
+ /**
2040
+ * Files to exclude in this plugin (default none).
2041
+ * @default []
2042
+ */
2043
+ exclude?: string | RegExp | (string | RegExp)[]
2044
+ /**
2045
+ * 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.
2046
+ * @default false
2047
+ */
2048
+ warnOnError?: boolean
2049
+ }
2483
2050
 
2484
- interface ClientOptions extends SecureContextOptions {
2485
- protocol?: string | undefined
2486
- followRedirects?: boolean | undefined
2487
- generateMask?(mask: Buffer): void
2488
- handshakeTimeout?: number | undefined
2489
- maxRedirects?: number | undefined
2490
- perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
2491
- localAddress?: string | undefined
2492
- protocolVersion?: number | undefined
2493
- headers?: { [key: string]: string } | undefined
2494
- origin?: string | undefined
2495
- agent?: Agent | undefined
2496
- host?: string | undefined
2497
- family?: number | undefined
2498
- checkServerIdentity?(servername: string, cert: CertMeta): boolean
2499
- rejectUnauthorized?: boolean | undefined
2500
- maxPayload?: number | undefined
2501
- skipUTF8Validation?: boolean | undefined
2051
+ // Modified and inlined to avoid extra dependency
2052
+ // Source: https://github.com/terser/terser/blob/master/tools/terser.d.ts
2053
+ // BSD Licensed https://github.com/terser/terser/blob/master/LICENSE
2054
+
2055
+ declare namespace Terser {
2056
+ export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020
2057
+
2058
+ export type ConsoleProperty = keyof typeof console
2059
+ type DropConsoleOption = boolean | ConsoleProperty[]
2060
+
2061
+ export interface ParseOptions {
2062
+ bare_returns?: boolean
2063
+ /** @deprecated legacy option. Currently, all supported EcmaScript is valid to parse. */
2064
+ ecma?: ECMA
2065
+ html5_comments?: boolean
2066
+ shebang?: boolean
2502
2067
  }
2503
2068
 
2504
- interface PerMessageDeflateOptions {
2505
- serverNoContextTakeover?: boolean | undefined
2506
- clientNoContextTakeover?: boolean | undefined
2507
- serverMaxWindowBits?: number | undefined
2508
- clientMaxWindowBits?: number | undefined
2509
- zlibDeflateOptions?:
2510
- | {
2511
- flush?: number | undefined
2512
- finishFlush?: number | undefined
2513
- chunkSize?: number | undefined
2514
- windowBits?: number | undefined
2515
- level?: number | undefined
2516
- memLevel?: number | undefined
2517
- strategy?: number | undefined
2518
- dictionary?: Buffer | Buffer[] | DataView | undefined
2519
- info?: boolean | undefined
2520
- }
2521
- | undefined
2522
- zlibInflateOptions?: ZlibOptions | undefined
2523
- threshold?: number | undefined
2524
- concurrencyLimit?: number | undefined
2069
+ export interface CompressOptions {
2070
+ arguments?: boolean
2071
+ arrows?: boolean
2072
+ booleans_as_integers?: boolean
2073
+ booleans?: boolean
2074
+ collapse_vars?: boolean
2075
+ comparisons?: boolean
2076
+ computed_props?: boolean
2077
+ conditionals?: boolean
2078
+ dead_code?: boolean
2079
+ defaults?: boolean
2080
+ directives?: boolean
2081
+ drop_console?: DropConsoleOption
2082
+ drop_debugger?: boolean
2083
+ ecma?: ECMA
2084
+ evaluate?: boolean
2085
+ expression?: boolean
2086
+ global_defs?: object
2087
+ hoist_funs?: boolean
2088
+ hoist_props?: boolean
2089
+ hoist_vars?: boolean
2090
+ ie8?: boolean
2091
+ if_return?: boolean
2092
+ inline?: boolean | InlineFunctions
2093
+ join_vars?: boolean
2094
+ keep_classnames?: boolean | RegExp
2095
+ keep_fargs?: boolean
2096
+ keep_fnames?: boolean | RegExp
2097
+ keep_infinity?: boolean
2098
+ loops?: boolean
2099
+ module?: boolean
2100
+ negate_iife?: boolean
2101
+ passes?: number
2102
+ properties?: boolean
2103
+ pure_funcs?: string[]
2104
+ pure_new?: boolean
2105
+ pure_getters?: boolean | 'strict'
2106
+ reduce_funcs?: boolean
2107
+ reduce_vars?: boolean
2108
+ sequences?: boolean | number
2109
+ side_effects?: boolean
2110
+ switches?: boolean
2111
+ toplevel?: boolean
2112
+ top_retain?: null | string | string[] | RegExp
2113
+ typeofs?: boolean
2114
+ unsafe_arrows?: boolean
2115
+ unsafe?: boolean
2116
+ unsafe_comps?: boolean
2117
+ unsafe_Function?: boolean
2118
+ unsafe_math?: boolean
2119
+ unsafe_symbols?: boolean
2120
+ unsafe_methods?: boolean
2121
+ unsafe_proto?: boolean
2122
+ unsafe_regexp?: boolean
2123
+ unsafe_undefined?: boolean
2124
+ unused?: boolean
2525
2125
  }
2526
2126
 
2527
- interface Event {
2528
- type: string
2529
- target: WebSocket
2127
+ export enum InlineFunctions {
2128
+ Disabled = 0,
2129
+ SimpleFunctions = 1,
2130
+ WithArguments = 2,
2131
+ WithArgumentsAndVariables = 3,
2530
2132
  }
2531
2133
 
2532
- interface ErrorEvent {
2533
- error: any
2534
- message: string
2535
- type: string
2536
- target: WebSocket
2134
+ export interface MangleOptions {
2135
+ eval?: boolean
2136
+ keep_classnames?: boolean | RegExp
2137
+ keep_fnames?: boolean | RegExp
2138
+ module?: boolean
2139
+ nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
2140
+ properties?: boolean | ManglePropertiesOptions
2141
+ reserved?: string[]
2142
+ safari10?: boolean
2143
+ toplevel?: boolean
2537
2144
  }
2538
2145
 
2539
- interface CloseEvent {
2540
- wasClean: boolean
2541
- code: number
2542
- reason: string
2543
- type: string
2544
- target: WebSocket
2146
+ /**
2147
+ * An identifier mangler for which the output is invariant with respect to the source code.
2148
+ */
2149
+ export interface SimpleIdentifierMangler {
2150
+ /**
2151
+ * Obtains the nth most favored (usually shortest) identifier to rename a variable to.
2152
+ * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word.
2153
+ * This function is expected to be stable; Evaluating get(n) === get(n) should always return true.
2154
+ * @param n The ordinal of the identifier.
2155
+ */
2156
+ get(n: number): string
2545
2157
  }
2546
2158
 
2547
- interface MessageEvent {
2548
- data: Data
2549
- type: string
2550
- target: WebSocket
2159
+ /**
2160
+ * An identifier mangler that leverages character frequency analysis to determine identifier precedence.
2161
+ */
2162
+ export interface WeightedIdentifierMangler extends SimpleIdentifierMangler {
2163
+ /**
2164
+ * Modifies the internal weighting of the input characters by the specified delta.
2165
+ * Will be invoked on the entire printed AST, and then deduct mangleable identifiers.
2166
+ * @param chars The characters to modify the weighting of.
2167
+ * @param delta The numeric weight to add to the characters.
2168
+ */
2169
+ consider(chars: string, delta: number): number
2170
+ /**
2171
+ * Resets character weights.
2172
+ */
2173
+ reset(): void
2174
+ /**
2175
+ * Sorts identifiers by character frequency, in preparation for calls to get(n).
2176
+ */
2177
+ sort(): void
2551
2178
  }
2552
2179
 
2553
- interface EventListenerOptions {
2554
- once?: boolean | undefined
2180
+ export interface ManglePropertiesOptions {
2181
+ builtins?: boolean
2182
+ debug?: boolean
2183
+ keep_quoted?: boolean | 'strict'
2184
+ nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
2185
+ regex?: RegExp | string
2186
+ reserved?: string[]
2555
2187
  }
2556
2188
 
2557
- interface ServerOptions {
2558
- host?: string | undefined
2559
- port?: number | undefined
2560
- backlog?: number | undefined
2561
- server?: Server | HttpsServer | undefined
2562
- verifyClient?:
2563
- | VerifyClientCallbackAsync
2564
- | VerifyClientCallbackSync
2565
- | undefined
2566
- handleProtocols?: (
2567
- protocols: Set<string>,
2568
- request: IncomingMessage,
2569
- ) => string | false
2570
- path?: string | undefined
2571
- noServer?: boolean | undefined
2572
- clientTracking?: boolean | undefined
2573
- perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
2574
- maxPayload?: number | undefined
2575
- skipUTF8Validation?: boolean | undefined
2576
- WebSocket?: typeof WebSocket.WebSocket | undefined
2189
+ export interface FormatOptions {
2190
+ ascii_only?: boolean
2191
+ /** @deprecated Not implemented anymore */
2192
+ beautify?: boolean
2193
+ braces?: boolean
2194
+ comments?:
2195
+ | boolean
2196
+ | 'all'
2197
+ | 'some'
2198
+ | RegExp
2199
+ | ((
2200
+ node: any,
2201
+ comment: {
2202
+ value: string
2203
+ type: 'comment1' | 'comment2' | 'comment3' | 'comment4'
2204
+ pos: number
2205
+ line: number
2206
+ col: number
2207
+ },
2208
+ ) => boolean)
2209
+ ecma?: ECMA
2210
+ ie8?: boolean
2211
+ keep_numbers?: boolean
2212
+ indent_level?: number
2213
+ indent_start?: number
2214
+ inline_script?: boolean
2215
+ keep_quoted_props?: boolean
2216
+ max_line_len?: number | false
2217
+ preamble?: string
2218
+ preserve_annotations?: boolean
2219
+ quote_keys?: boolean
2220
+ quote_style?: OutputQuoteStyle
2221
+ safari10?: boolean
2222
+ semicolons?: boolean
2223
+ shebang?: boolean
2224
+ shorthand?: boolean
2225
+ source_map?: SourceMapOptions
2226
+ webkit?: boolean
2227
+ width?: number
2228
+ wrap_iife?: boolean
2229
+ wrap_func_args?: boolean
2577
2230
  }
2578
2231
 
2579
- interface AddressInfo {
2580
- address: string
2581
- family: string
2582
- port: number
2232
+ export enum OutputQuoteStyle {
2233
+ PreferDouble = 0,
2234
+ AlwaysSingle = 1,
2235
+ AlwaysDouble = 2,
2236
+ AlwaysOriginal = 3,
2583
2237
  }
2584
2238
 
2585
- // WebSocket Server
2586
- class Server<T extends WebSocket = WebSocket> extends EventEmitter {
2587
- options: ServerOptions
2588
- path: string
2589
- clients: Set<T>
2590
-
2591
- constructor(options?: ServerOptions, callback?: () => void)
2592
-
2593
- address(): AddressInfo | string
2594
- close(cb?: (err?: Error) => void): void
2595
- handleUpgrade(
2596
- request: IncomingMessage,
2597
- socket: Duplex,
2598
- upgradeHead: Buffer,
2599
- callback: (client: T, request: IncomingMessage) => void,
2600
- ): void
2601
- shouldHandle(request: IncomingMessage): boolean | Promise<boolean>
2602
-
2603
- // Events
2604
- on(
2605
- event: 'connection',
2606
- cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
2607
- ): this
2608
- on(event: 'error', cb: (this: Server<T>, error: Error) => void): this
2609
- on(
2610
- event: 'headers',
2611
- cb: (
2612
- this: Server<T>,
2613
- headers: string[],
2614
- request: IncomingMessage,
2615
- ) => void,
2616
- ): this
2617
- on(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
2618
- on(
2619
- event: string | symbol,
2620
- listener: (this: Server<T>, ...args: any[]) => void,
2621
- ): this
2622
-
2623
- once(
2624
- event: 'connection',
2625
- cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
2626
- ): this
2627
- once(event: 'error', cb: (this: Server<T>, error: Error) => void): this
2628
- once(
2629
- event: 'headers',
2630
- cb: (
2631
- this: Server<T>,
2632
- headers: string[],
2633
- request: IncomingMessage,
2634
- ) => void,
2635
- ): this
2636
- once(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
2637
- once(
2638
- event: string | symbol,
2639
- listener: (this: Server<T>, ...args: any[]) => void,
2640
- ): this
2641
-
2642
- off(
2643
- event: 'connection',
2644
- cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
2645
- ): this
2646
- off(event: 'error', cb: (this: Server<T>, error: Error) => void): this
2647
- off(
2648
- event: 'headers',
2649
- cb: (
2650
- this: Server<T>,
2651
- headers: string[],
2652
- request: IncomingMessage,
2653
- ) => void,
2654
- ): this
2655
- off(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
2656
- off(
2657
- event: string | symbol,
2658
- listener: (this: Server<T>, ...args: any[]) => void,
2659
- ): this
2239
+ export interface MinifyOptions {
2240
+ compress?: boolean | CompressOptions
2241
+ ecma?: ECMA
2242
+ enclose?: boolean | string
2243
+ ie8?: boolean
2244
+ keep_classnames?: boolean | RegExp
2245
+ keep_fnames?: boolean | RegExp
2246
+ mangle?: boolean | MangleOptions
2247
+ module?: boolean
2248
+ nameCache?: object
2249
+ format?: FormatOptions
2250
+ /** @deprecated */
2251
+ output?: FormatOptions
2252
+ parse?: ParseOptions
2253
+ safari10?: boolean
2254
+ sourceMap?: boolean | SourceMapOptions
2255
+ toplevel?: boolean
2256
+ }
2660
2257
 
2661
- addListener(
2662
- event: 'connection',
2663
- cb: (client: T, request: IncomingMessage) => void,
2664
- ): this
2665
- addListener(event: 'error', cb: (err: Error) => void): this
2666
- addListener(
2667
- event: 'headers',
2668
- cb: (headers: string[], request: IncomingMessage) => void,
2669
- ): this
2670
- addListener(event: 'close' | 'listening', cb: () => void): this
2671
- addListener(
2672
- event: string | symbol,
2673
- listener: (...args: any[]) => void,
2674
- ): this
2258
+ export interface MinifyOutput {
2259
+ code?: string
2260
+ map?: object | string
2261
+ decoded_map?: object | null
2262
+ }
2675
2263
 
2676
- removeListener(event: 'connection', cb: (client: T) => void): this
2677
- removeListener(event: 'error', cb: (err: Error) => void): this
2678
- removeListener(
2679
- event: 'headers',
2680
- cb: (headers: string[], request: IncomingMessage) => void,
2681
- ): this
2682
- removeListener(event: 'close' | 'listening', cb: () => void): this
2683
- removeListener(
2684
- event: string | symbol,
2685
- listener: (...args: any[]) => void,
2686
- ): this
2264
+ export interface SourceMapOptions {
2265
+ /** Source map object, 'inline' or source map file content */
2266
+ content?: object | string
2267
+ includeSources?: boolean
2268
+ filename?: string
2269
+ root?: string
2270
+ asObject?: boolean
2271
+ url?: string | 'inline'
2687
2272
  }
2273
+ }
2688
2274
 
2689
- const WebSocketServer: typeof Server
2690
- interface WebSocketServer extends Server {}
2691
- const WebSocket: typeof WebSocketAlias
2692
- interface WebSocket extends WebSocketAlias {}
2275
+ interface TerserOptions extends Terser.MinifyOptions {
2276
+ /**
2277
+ * Vite-specific option to specify the max number of workers to spawn
2278
+ * when minifying files with terser.
2279
+ *
2280
+ * @default number of CPUs minus 1
2281
+ */
2282
+ maxWorkers?: number;
2283
+ }
2693
2284
 
2694
- // WebSocket stream
2695
- function createWebSocketStream(
2696
- websocket: WebSocket,
2697
- options?: DuplexOptions,
2698
- ): Duplex
2285
+ interface EnvironmentResolveOptions {
2286
+ /**
2287
+ * @default ['browser', 'module', 'jsnext:main', 'jsnext']
2288
+ */
2289
+ mainFields?: string[];
2290
+ conditions?: string[];
2291
+ externalConditions?: string[];
2292
+ /**
2293
+ * @default ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']
2294
+ */
2295
+ extensions?: string[];
2296
+ dedupe?: string[];
2297
+ /**
2298
+ * Prevent listed dependencies from being externalized and will get bundled in build.
2299
+ * Only works in server environments for now. Previously this was `ssr.noExternal`.
2300
+ * @experimental
2301
+ */
2302
+ noExternal?: string | RegExp | (string | RegExp)[] | true;
2303
+ /**
2304
+ * Externalize the given dependencies and their transitive dependencies.
2305
+ * Only works in server environments for now. Previously this was `ssr.external`.
2306
+ * @experimental
2307
+ */
2308
+ external?: string[] | true;
2309
+ }
2310
+ interface ResolveOptions extends EnvironmentResolveOptions {
2311
+ /**
2312
+ * @default false
2313
+ */
2314
+ preserveSymlinks?: boolean;
2315
+ }
2316
+ interface ResolvePluginOptions {
2317
+ root: string;
2318
+ isBuild: boolean;
2319
+ isProduction: boolean;
2320
+ packageCache?: PackageCache;
2321
+ /**
2322
+ * src code mode also attempts the following:
2323
+ * - resolving /xxx as URLs
2324
+ * - resolving bare imports from optimized deps
2325
+ */
2326
+ asSrc?: boolean;
2327
+ tryIndex?: boolean;
2328
+ tryPrefix?: string;
2329
+ preferRelative?: boolean;
2330
+ isRequire?: boolean;
2331
+ isFromTsImporter?: boolean;
2332
+ scan?: boolean;
2333
+ /**
2334
+ * @deprecated environment.config are used instead
2335
+ */
2336
+ ssrConfig?: SSROptions;
2337
+ }
2338
+ interface InternalResolveOptions extends Required<ResolveOptions>, ResolvePluginOptions {
2339
+ }
2340
+
2341
+ /** Cache for package.json resolution and package.json contents */
2342
+ type PackageCache = Map<string, PackageData>;
2343
+ interface PackageData {
2344
+ dir: string;
2345
+ hasSideEffects: (id: string) => boolean | 'no-treeshake' | null;
2346
+ setResolvedCache: (key: string, entry: string, options: InternalResolveOptions) => void;
2347
+ getResolvedCache: (key: string, options: InternalResolveOptions) => string | undefined;
2348
+ data: {
2349
+ [field: string]: any;
2350
+ name: string;
2351
+ type: string;
2352
+ version: string;
2353
+ main: string;
2354
+ module: string;
2355
+ browser: string | Record<string, string | false>;
2356
+ exports: string | Record<string, any> | string[];
2357
+ imports: Record<string, any>;
2358
+ dependencies: Record<string, string>;
2359
+ };
2360
+ }
2361
+
2362
+ interface BuildEnvironmentOptions {
2363
+ /**
2364
+ * Compatibility transform target. The transform is performed with esbuild
2365
+ * and the lowest supported target is es2015/es6. Note this only handles
2366
+ * syntax transformation and does not cover polyfills (except for dynamic
2367
+ * import)
2368
+ *
2369
+ * Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules,
2370
+ * transpile targeting browsers that natively support dynamic es module imports.
2371
+ * https://caniuse.com/es6-module-dynamic-import
2372
+ *
2373
+ * Another special value is 'esnext' - which only performs minimal transpiling
2374
+ * (for minification compat) and assumes native dynamic imports support.
2375
+ *
2376
+ * For custom targets, see https://esbuild.github.io/api/#target and
2377
+ * https://esbuild.github.io/content-types/#javascript for more details.
2378
+ * @default 'modules'
2379
+ */
2380
+ target?: 'modules' | esbuild_TransformOptions['target'] | false;
2381
+ /**
2382
+ * whether to inject module preload polyfill.
2383
+ * Note: does not apply to library mode.
2384
+ * @default true
2385
+ * @deprecated use `modulePreload.polyfill` instead
2386
+ */
2387
+ polyfillModulePreload?: boolean;
2388
+ /**
2389
+ * Configure module preload
2390
+ * Note: does not apply to library mode.
2391
+ * @default true
2392
+ */
2393
+ modulePreload?: boolean | ModulePreloadOptions;
2394
+ /**
2395
+ * Directory relative from `root` where build output will be placed. If the
2396
+ * directory exists, it will be removed before the build.
2397
+ * @default 'dist'
2398
+ */
2399
+ outDir?: string;
2400
+ /**
2401
+ * Directory relative from `outDir` where the built js/css/image assets will
2402
+ * be placed.
2403
+ * @default 'assets'
2404
+ */
2405
+ assetsDir?: string;
2406
+ /**
2407
+ * Static asset files smaller than this number (in bytes) will be inlined as
2408
+ * base64 strings. If a callback is passed, a boolean can be returned to opt-in
2409
+ * or opt-out of inlining. If nothing is returned the default logic applies.
2410
+ *
2411
+ * Default limit is `4096` (4 KiB). Set to `0` to disable.
2412
+ * @default 4096
2413
+ */
2414
+ assetsInlineLimit?: number | ((filePath: string, content: Buffer) => boolean | undefined);
2415
+ /**
2416
+ * Whether to code-split CSS. When enabled, CSS in async chunks will be
2417
+ * inlined as strings in the chunk and inserted via dynamically created
2418
+ * style tags when the chunk is loaded.
2419
+ * @default true
2420
+ */
2421
+ cssCodeSplit?: boolean;
2422
+ /**
2423
+ * An optional separate target for CSS minification.
2424
+ * As esbuild only supports configuring targets to mainstream
2425
+ * browsers, users may need this option when they are targeting
2426
+ * a niche browser that comes with most modern JavaScript features
2427
+ * but has poor CSS support, e.g. Android WeChat WebView, which
2428
+ * doesn't support the #RGBA syntax.
2429
+ * @default target
2430
+ */
2431
+ cssTarget?: esbuild_TransformOptions['target'] | false;
2432
+ /**
2433
+ * Override CSS minification specifically instead of defaulting to `build.minify`,
2434
+ * so you can configure minification for JS and CSS separately.
2435
+ * @default 'esbuild'
2436
+ */
2437
+ cssMinify?: boolean | 'esbuild' | 'lightningcss';
2438
+ /**
2439
+ * If `true`, a separate sourcemap file will be created. If 'inline', the
2440
+ * sourcemap will be appended to the resulting output file as data URI.
2441
+ * 'hidden' works like `true` except that the corresponding sourcemap
2442
+ * comments in the bundled files are suppressed.
2443
+ * @default false
2444
+ */
2445
+ sourcemap?: boolean | 'inline' | 'hidden';
2446
+ /**
2447
+ * Set to `false` to disable minification, or specify the minifier to use.
2448
+ * Available options are 'terser' or 'esbuild'.
2449
+ * @default 'esbuild'
2450
+ */
2451
+ minify?: boolean | 'terser' | 'esbuild';
2452
+ /**
2453
+ * Options for terser
2454
+ * https://terser.org/docs/api-reference#minify-options
2455
+ *
2456
+ * In addition, you can also pass a `maxWorkers: number` option to specify the
2457
+ * max number of workers to spawn. Defaults to the number of CPUs minus 1.
2458
+ */
2459
+ terserOptions?: TerserOptions;
2460
+ /**
2461
+ * Will be merged with internal rollup options.
2462
+ * https://rollupjs.org/configuration-options/
2463
+ */
2464
+ rollupOptions?: RollupOptions;
2465
+ /**
2466
+ * Options to pass on to `@rollup/plugin-commonjs`
2467
+ */
2468
+ commonjsOptions?: RollupCommonJSOptions;
2469
+ /**
2470
+ * Options to pass on to `@rollup/plugin-dynamic-import-vars`
2471
+ */
2472
+ dynamicImportVarsOptions?: RollupDynamicImportVarsOptions;
2473
+ /**
2474
+ * Whether to write bundle to disk
2475
+ * @default true
2476
+ */
2477
+ write?: boolean;
2478
+ /**
2479
+ * Empty outDir on write.
2480
+ * @default true when outDir is a sub directory of project root
2481
+ */
2482
+ emptyOutDir?: boolean | null;
2483
+ /**
2484
+ * Copy the public directory to outDir on write.
2485
+ * @default true
2486
+ */
2487
+ copyPublicDir?: boolean;
2488
+ /**
2489
+ * Whether to emit a .vite/manifest.json under assets dir to map hash-less filenames
2490
+ * to their hashed versions. Useful when you want to generate your own HTML
2491
+ * instead of using the one generated by Vite.
2492
+ *
2493
+ * Example:
2494
+ *
2495
+ * ```json
2496
+ * {
2497
+ * "main.js": {
2498
+ * "file": "main.68fe3fad.js",
2499
+ * "css": "main.e6b63442.css",
2500
+ * "imports": [...],
2501
+ * "dynamicImports": [...]
2502
+ * }
2503
+ * }
2504
+ * ```
2505
+ * @default false
2506
+ */
2507
+ manifest?: boolean | string;
2508
+ /**
2509
+ * Build in library mode. The value should be the global name of the lib in
2510
+ * UMD mode. This will produce esm + cjs + umd bundle formats with default
2511
+ * configurations that are suitable for distributing libraries.
2512
+ * @default false
2513
+ */
2514
+ lib?: LibraryOptions | false;
2515
+ /**
2516
+ * Produce SSR oriented build. Note this requires specifying SSR entry via
2517
+ * `rollupOptions.input`.
2518
+ * @default false
2519
+ */
2520
+ ssr?: boolean | string;
2521
+ /**
2522
+ * Generate SSR manifest for determining style links and asset preload
2523
+ * directives in production.
2524
+ * @default false
2525
+ */
2526
+ ssrManifest?: boolean | string;
2527
+ /**
2528
+ * Emit assets during SSR.
2529
+ * @default false
2530
+ */
2531
+ ssrEmitAssets?: boolean;
2532
+ /**
2533
+ * Emit assets during build. Frameworks can set environments.ssr.build.emitAssets
2534
+ * By default, it is true for the client and false for other environments.
2535
+ */
2536
+ emitAssets?: boolean;
2537
+ /**
2538
+ * Set to false to disable reporting compressed chunk sizes.
2539
+ * Can slightly improve build speed.
2540
+ * @default true
2541
+ */
2542
+ reportCompressedSize?: boolean;
2543
+ /**
2544
+ * Adjust chunk size warning limit (in kB).
2545
+ * @default 500
2546
+ */
2547
+ chunkSizeWarningLimit?: number;
2548
+ /**
2549
+ * Rollup watch options
2550
+ * https://rollupjs.org/configuration-options/#watch
2551
+ * @default null
2552
+ */
2553
+ watch?: WatcherOptions | null;
2554
+ /**
2555
+ * create the Build Environment instance
2556
+ */
2557
+ createEnvironment?: (name: string, config: ResolvedConfig) => Promise<BuildEnvironment> | BuildEnvironment;
2699
2558
  }
2700
-
2701
- type WebSocketCustomListener<T> = (data: T, client: WebSocketClient) => void;
2702
- declare const isWebSocketServer: unique symbol;
2703
- interface WebSocketServer extends HotChannel {
2704
- [isWebSocketServer]: true;
2559
+ type BuildOptions = BuildEnvironmentOptions;
2560
+ interface LibraryOptions {
2705
2561
  /**
2706
- * Listen on port and host
2562
+ * Path of library entry
2707
2563
  */
2708
- listen(): void;
2564
+ entry: InputOption;
2709
2565
  /**
2710
- * Get all connected clients.
2566
+ * The name of the exposed global variable. Required when the `formats` option includes
2567
+ * `umd` or `iife`
2711
2568
  */
2712
- clients: Set<WebSocketClient>;
2569
+ name?: string;
2713
2570
  /**
2714
- * Disconnect all clients and terminate the server.
2571
+ * Output bundle formats
2572
+ * @default ['es', 'umd']
2715
2573
  */
2716
- close(): Promise<void>;
2574
+ formats?: LibraryFormats[];
2717
2575
  /**
2718
- * Handle custom event emitted by `import.meta.hot.send`
2576
+ * The name of the package file output. The default file name is the name option
2577
+ * of the project package.json. It can also be defined as a function taking the
2578
+ * format as an argument.
2719
2579
  */
2720
- on: WebSocket.Server['on'] & {
2721
- <T extends string>(event: T, listener: WebSocketCustomListener<InferCustomEventPayload<T>>): void;
2722
- };
2580
+ fileName?: string | ((format: ModuleFormat, entryName: string) => string);
2723
2581
  /**
2724
- * Unregister event listener.
2582
+ * The name of the CSS file output if the library imports CSS. Defaults to the
2583
+ * same value as `build.lib.fileName` if it's set a string, otherwise it falls
2584
+ * back to the name option of the project package.json.
2725
2585
  */
2726
- off: WebSocket.Server['off'] & {
2727
- (event: string, listener: Function): void;
2728
- };
2586
+ cssFileName?: string;
2729
2587
  }
2730
- interface WebSocketClient extends HotChannelClient {
2588
+ type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife' | 'system';
2589
+ interface ModulePreloadOptions {
2731
2590
  /**
2732
- * The raw WebSocket instance
2733
- * @advanced
2591
+ * Whether to inject a module preload polyfill.
2592
+ * Note: does not apply to library mode.
2593
+ * @default true
2734
2594
  */
2735
- socket: WebSocket;
2595
+ polyfill?: boolean;
2596
+ /**
2597
+ * Resolve the list of dependencies to preload for a given dynamic import
2598
+ * @experimental
2599
+ */
2600
+ resolveDependencies?: ResolveModulePreloadDependenciesFn;
2601
+ }
2602
+ interface ResolvedModulePreloadOptions {
2603
+ polyfill: boolean;
2604
+ resolveDependencies?: ResolveModulePreloadDependenciesFn;
2605
+ }
2606
+ type ResolveModulePreloadDependenciesFn = (filename: string, deps: string[], context: {
2607
+ hostId: string;
2608
+ hostType: 'html' | 'js';
2609
+ }) => string[];
2610
+ interface ResolvedBuildEnvironmentOptions extends Required<Omit<BuildEnvironmentOptions, 'polyfillModulePreload'>> {
2611
+ modulePreload: false | ResolvedModulePreloadOptions;
2612
+ }
2613
+ interface ResolvedBuildOptions extends Required<Omit<BuildOptions, 'polyfillModulePreload'>> {
2614
+ modulePreload: false | ResolvedModulePreloadOptions;
2615
+ }
2616
+ /**
2617
+ * Bundles a single environment for production.
2618
+ * Returns a Promise containing the build result.
2619
+ */
2620
+ declare function build(inlineConfig?: InlineConfig): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
2621
+ type RenderBuiltAssetUrl = (filename: string, type: {
2622
+ type: 'asset' | 'public';
2623
+ hostId: string;
2624
+ hostType: 'js' | 'css' | 'html';
2625
+ ssr: boolean;
2626
+ }) => string | {
2627
+ relative?: boolean;
2628
+ runtime?: string;
2629
+ } | undefined;
2630
+ declare class BuildEnvironment extends BaseEnvironment {
2631
+ mode: "build";
2632
+ constructor(name: string, config: ResolvedConfig, setup?: {
2633
+ options?: EnvironmentOptions;
2634
+ });
2635
+ init(): Promise<void>;
2636
+ }
2637
+ interface ViteBuilder {
2638
+ environments: Record<string, BuildEnvironment>;
2639
+ config: ResolvedConfig;
2640
+ buildApp(): Promise<void>;
2641
+ build(environment: BuildEnvironment): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
2642
+ }
2643
+ interface BuilderOptions {
2644
+ /**
2645
+ * Whether to share the config instance among environments to align with the behavior of dev server.
2646
+ *
2647
+ * @default false
2648
+ * @experimental
2649
+ */
2650
+ sharedConfigBuild?: boolean;
2651
+ /**
2652
+ * Whether to share the plugin instances among environments to align with the behavior of dev server.
2653
+ *
2654
+ * @default false
2655
+ * @experimental
2656
+ */
2657
+ sharedPlugins?: boolean;
2658
+ buildApp?: (builder: ViteBuilder) => Promise<void>;
2659
+ }
2660
+ type ResolvedBuilderOptions = Required<BuilderOptions>;
2661
+ /**
2662
+ * Creates a ViteBuilder to orchestrate building multiple environments.
2663
+ * @experimental
2664
+ */
2665
+ declare function createBuilder(inlineConfig?: InlineConfig, useLegacyBuilder?: null | boolean): Promise<ViteBuilder>;
2666
+
2667
+ type Environment = DevEnvironment | BuildEnvironment | UnknownEnvironment;
2668
+
2669
+ declare class EnvironmentPluginContainer {
2670
+ environment: Environment;
2671
+ plugins: Plugin[];
2672
+ watcher?: FSWatcher | undefined;
2673
+ private _pluginContextMap;
2674
+ private _resolvedRollupOptions?;
2675
+ private _processesing;
2676
+ private _seenResolves;
2677
+ private _moduleNodeToLoadAddedImports;
2678
+ getSortedPluginHooks: PluginHookUtils['getSortedPluginHooks'];
2679
+ getSortedPlugins: PluginHookUtils['getSortedPlugins'];
2680
+ moduleGraph: EnvironmentModuleGraph | undefined;
2681
+ watchFiles: Set<string>;
2682
+ minimalContext: MinimalPluginContext;
2683
+ private _started;
2684
+ private _buildStartPromise;
2685
+ private _closed;
2686
+ private _updateModuleLoadAddedImports;
2687
+ private _getAddedImports;
2688
+ getModuleInfo(id: string): ModuleInfo | null;
2689
+ private handleHookPromise;
2690
+ get options(): InputOptions;
2691
+ resolveRollupOptions(): Promise<InputOptions>;
2692
+ private _getPluginContext;
2693
+ private hookParallel;
2694
+ buildStart(_options?: InputOptions): Promise<void>;
2695
+ resolveId(rawId: string, importer?: string | undefined, options?: {
2696
+ attributes?: Record<string, string>;
2697
+ custom?: CustomPluginOptions;
2698
+ skip?: Set<Plugin>;
2699
+ isEntry?: boolean;
2700
+ }): Promise<PartialResolvedId | null>;
2701
+ load(id: string): Promise<LoadResult | null>;
2702
+ transform(code: string, id: string, options?: {
2703
+ inMap?: SourceDescription['map'];
2704
+ }): Promise<{
2705
+ code: string;
2706
+ map: SourceMap | {
2707
+ mappings: '';
2708
+ } | null;
2709
+ }>;
2710
+ watchChange(id: string, change: {
2711
+ event: 'create' | 'update' | 'delete';
2712
+ }): Promise<void>;
2713
+ close(): Promise<void>;
2714
+ }
2715
+ declare class PluginContainer {
2716
+ private environments;
2717
+ constructor(environments: Record<string, Environment>);
2718
+ private _getEnvironment;
2719
+ private _getPluginContainer;
2720
+ getModuleInfo(id: string): ModuleInfo | null;
2721
+ get options(): InputOptions;
2722
+ buildStart(_options?: InputOptions): Promise<void>;
2723
+ watchChange(id: string, change: {
2724
+ event: 'create' | 'update' | 'delete';
2725
+ }): Promise<void>;
2726
+ resolveId(rawId: string, importer?: string, options?: {
2727
+ attributes?: Record<string, string>;
2728
+ custom?: CustomPluginOptions;
2729
+ skip?: Set<Plugin>;
2730
+ ssr?: boolean;
2731
+ isEntry?: boolean;
2732
+ }): Promise<PartialResolvedId | null>;
2733
+ load(id: string, options?: {
2734
+ ssr?: boolean;
2735
+ }): Promise<LoadResult | null>;
2736
+ transform(code: string, id: string, options?: {
2737
+ ssr?: boolean;
2738
+ environment?: Environment;
2739
+ inMap?: SourceDescription['map'];
2740
+ }): Promise<{
2741
+ code: string;
2742
+ map: SourceMap | {
2743
+ mappings: '';
2744
+ } | null;
2745
+ }>;
2746
+ close(): Promise<void>;
2736
2747
  }
2737
2748
 
2738
2749
  interface ServerOptions extends CommonServerOptions {
@@ -2843,13 +2854,6 @@ interface FileSystemServeOptions {
2843
2854
  * @default ['.env', '.env.*', '*.{crt,pem}', '**\/.git/**']
2844
2855
  */
2845
2856
  deny?: string[];
2846
- /**
2847
- * Enable caching of fs calls. It is enabled by default if no custom watch ignored patterns are provided.
2848
- *
2849
- * @experimental
2850
- * @default undefined
2851
- */
2852
- cachedChecks?: boolean;
2853
2857
  }
2854
2858
  type ServerHook = (this: void, server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>;
2855
2859
  type HttpServer = http.Server | Http2SecureServer;
@@ -3381,7 +3385,7 @@ interface SSROptions {
3381
3385
  /**
3382
3386
  * Define the target for the ssr build. The browser field in package.json
3383
3387
  * is ignored for node but used if webworker is the target
3384
- * This option may be replaced by the experimental `environmentOptions.webCompatible`
3388
+ * This option will be removed in a future major version
3385
3389
  * @default 'node'
3386
3390
  */
3387
3391
  target?: SSRTarget;
@@ -3518,10 +3522,10 @@ interface SharedEnvironmentOptions {
3518
3522
  */
3519
3523
  consumer?: 'client' | 'server';
3520
3524
  /**
3521
- * Runtime Compatibility
3522
- * Temporal options, we should remove these in favor of fine-grained control
3525
+ * If true, `process.env` referenced in code will be preserved as-is and evaluated in runtime.
3526
+ * Otherwise, it is statically replaced as an empty object.
3523
3527
  */
3524
- webCompatible?: boolean;
3528
+ keepProcessEnv?: boolean;
3525
3529
  /**
3526
3530
  * Optimize deps config
3527
3531
  */
@@ -3542,12 +3546,12 @@ type ResolvedEnvironmentOptions = {
3542
3546
  define?: Record<string, any>;
3543
3547
  resolve: ResolvedResolveOptions;
3544
3548
  consumer: 'client' | 'server';
3545
- webCompatible: boolean;
3549
+ keepProcessEnv?: boolean;
3546
3550
  optimizeDeps: DepOptimizationOptions;
3547
3551
  dev: ResolvedDevEnvironmentOptions;
3548
3552
  build: ResolvedBuildEnvironmentOptions;
3549
3553
  };
3550
- type DefaultEnvironmentOptions = Omit<EnvironmentOptions, 'consumer' | 'webCompatible' | 'resolve'> & {
3554
+ type DefaultEnvironmentOptions = Omit<EnvironmentOptions, 'consumer' | 'resolve'> & {
3551
3555
  resolve?: AllResolveOptions;
3552
3556
  };
3553
3557
  interface UserConfig extends DefaultEnvironmentOptions {
@@ -3848,7 +3852,6 @@ interface ServerModuleRunnerOptions extends Omit<ModuleRunnerOptions, 'root' | '
3848
3852
  * Disable HMR or configure HMR logger.
3849
3853
  */
3850
3854
  hmr?: false | {
3851
- connection?: ModuleRunnerHMRConnection;
3852
3855
  logger?: ModuleRunnerHmr['logger'];
3853
3856
  };
3854
3857
  /**
@@ -3866,7 +3869,7 @@ declare function createRunnableDevEnvironment(name: string, config: ResolvedConf
3866
3869
  interface RunnableDevEnvironmentContext extends Omit<DevEnvironmentContext, 'hot'> {
3867
3870
  runner?: (environment: RunnableDevEnvironment, options?: ServerModuleRunnerOptions) => ModuleRunner;
3868
3871
  runnerOptions?: ServerModuleRunnerOptions;
3869
- hot?: false | HotChannel;
3872
+ hot?: boolean;
3870
3873
  }
3871
3874
  declare function isRunnableDevEnvironment(environment: Environment): environment is RunnableDevEnvironment;
3872
3875
  declare class RunnableDevEnvironment extends DevEnvironment {
@@ -3889,21 +3892,6 @@ interface FetchModuleOptions {
3889
3892
  */
3890
3893
  declare function fetchModule(environment: DevEnvironment, url: string, importer?: string, options?: FetchModuleOptions): Promise<FetchResult>;
3891
3894
 
3892
- /**
3893
- * The connector class to establish HMR communication between the server and the Vite runtime.
3894
- * @experimental
3895
- */
3896
- declare class ServerHMRConnector implements ModuleRunnerHMRConnection {
3897
- private hotChannel;
3898
- private handlers;
3899
- private hmrClient;
3900
- private connected;
3901
- constructor(hotChannel: ServerHotChannel);
3902
- isReady(): boolean;
3903
- send(payload_: HotPayload): void;
3904
- onUpdate(handler: (payload: HotPayload) => void): void;
3905
- }
3906
-
3907
3895
  interface ModuleRunnerTransformOptions {
3908
3896
  json?: {
3909
3897
  stringify?: boolean;
@@ -3988,4 +3976,4 @@ interface ManifestChunk {
3988
3976
  dynamicImports?: string[];
3989
3977
  }
3990
3978
 
3991
- export { type Alias, type AliasOptions, type AnymatchFn, type AnymatchPattern, type AppType, type BindCLIShortcutsOptions, BuildEnvironment, type BuildEnvironmentOptions, type BuildOptions, type BuilderOptions, type CLIShortcut, type CSSModulesOptions, type CSSOptions, type CommonServerOptions, type ConfigEnv, Connect, type CorsOptions, type CorsOrigin, type DepOptimizationConfig, type DepOptimizationMetadata, type DepOptimizationOptions, DevEnvironment, type DevEnvironmentContext, type DevEnvironmentOptions, type ESBuildOptions, type ESBuildTransformResult, type Environment, EnvironmentModuleGraph, EnvironmentModuleNode, type EnvironmentOptions, type ExperimentalOptions, type ExportsData, FSWatcher, type FetchModuleOptions, type FileSystemServeOptions, type FilterPattern, type HMRBroadcaster, type HMRBroadcasterClient, type HMRChannel, type HTMLOptions, type HmrContext, type HmrOptions, type HookHandler, type HotChannel, type HotChannelClient, type HotUpdateOptions, type HtmlTagDescriptor, HttpProxy, type HttpServer, type IndexHtmlTransform, type IndexHtmlTransformContext, type IndexHtmlTransformHook, type IndexHtmlTransformResult, type InlineConfig, type InternalResolveOptions, type JsonOptions, type LegacyOptions, type LessPreprocessorOptions, type LibraryFormats, type LibraryOptions, type LogErrorOptions, type LogLevel, type LogOptions, type LogType, type Logger, type LoggerOptions, type Manifest, type ManifestChunk, type MapToFunction, type AnymatchMatcher as Matcher, ModuleGraph, ModuleNode, type ModulePreloadOptions, type ModuleRunnerTransformOptions, type OptimizedDepInfo, type Plugin, PluginContainer, type PluginHookUtils, type PluginOption, type PreprocessCSSResult, type PreviewOptions, type PreviewServer, type PreviewServerHook, type ProxyOptions, RemoteEnvironmentTransport, type RenderBuiltAssetUrl, type ResolveFn, type ResolveModulePreloadDependenciesFn, type ResolveOptions, type ResolvedBuildEnvironmentOptions, type ResolvedBuildOptions, type ResolvedCSSOptions, type ResolvedConfig, type ResolvedDevEnvironmentOptions, type ResolvedModulePreloadOptions, type ResolvedPreviewOptions, type ResolvedSSROptions, type ResolvedServerOptions, type ResolvedServerUrls, type ResolvedUrl, type ResolvedWorkerOptions, type ResolverFunction, type ResolverObject, type RollupCommonJSOptions, type RollupDynamicImportVarsOptions, RunnableDevEnvironment, type RunnableDevEnvironmentContext, type SSROptions, type SSRTarget, type SassPreprocessorOptions, type SendOptions, type ServerHMRChannel, ServerHMRConnector, type ServerHook, type ServerHotChannel, type ServerModuleRunnerOptions, type ServerOptions, SplitVendorChunkCache, type SsrDepOptimizationConfig, type StylusPreprocessorOptions, Terser, type TerserOptions, type TransformOptions, type TransformResult, type UserConfig, type UserConfigExport, type UserConfigFn, type UserConfigFnObject, type UserConfigFnPromise, type ViteBuilder, type ViteDevServer, type WatchOptions, WebSocket, WebSocketAlias, type WebSocketClient, type WebSocketCustomListener, WebSocketServer, build, buildErrorMessage, createBuilder, createFilter, createIdResolver, createLogger, createRunnableDevEnvironment, createServer, createServerHotChannel, createServerModuleRunner, defineConfig, fetchModule, formatPostcssSourceMap, isCSSRequest, isFileLoadingAllowed, isFileServingAllowed, isRunnableDevEnvironment, loadConfigFromFile, loadEnv, mergeAlias, mergeConfig, ssrTransform as moduleRunnerTransform, normalizePath, optimizeDeps, preprocessCSS, preview, resolveConfig, resolveEnvPrefix, rollupVersion, searchForWorkspaceRoot, send, sortUserPlugins, splitVendorChunk, splitVendorChunkPlugin, transformWithEsbuild, VERSION as version };
3979
+ export { type Alias, type AliasOptions, type AnymatchFn, type AnymatchPattern, type AppType, type BindCLIShortcutsOptions, BuildEnvironment, type BuildEnvironmentOptions, type BuildOptions, type BuilderOptions, type CLIShortcut, type CSSModulesOptions, type CSSOptions, type CommonServerOptions, type ConfigEnv, Connect, type CorsOptions, type CorsOrigin, type DepOptimizationConfig, type DepOptimizationMetadata, type DepOptimizationOptions, DevEnvironment, type DevEnvironmentContext, type DevEnvironmentOptions, type ESBuildOptions, type ESBuildTransformResult, type Environment, EnvironmentModuleGraph, EnvironmentModuleNode, type EnvironmentOptions, type ExperimentalOptions, type ExportsData, FSWatcher, type FetchModuleOptions, type FileSystemServeOptions, type FilterPattern, type HMRBroadcaster, type HMRBroadcasterClient, type HMRChannel, type HTMLOptions, type HmrContext, type HmrOptions, type HookHandler, type HotChannel, type HotChannelClient, type HotChannelListener, type HotUpdateOptions, type HtmlTagDescriptor, HttpProxy, type HttpServer, type IndexHtmlTransform, type IndexHtmlTransformContext, type IndexHtmlTransformHook, type IndexHtmlTransformResult, type InlineConfig, type InternalResolveOptions, type JsonOptions, type LegacyOptions, type LessPreprocessorOptions, type LibraryFormats, type LibraryOptions, type LogErrorOptions, type LogLevel, type LogOptions, type LogType, type Logger, type LoggerOptions, type Manifest, type ManifestChunk, type MapToFunction, type AnymatchMatcher as Matcher, ModuleGraph, ModuleNode, type ModulePreloadOptions, type ModuleRunnerTransformOptions, type OptimizedDepInfo, type Plugin, PluginContainer, type PluginHookUtils, type PluginOption, type PreprocessCSSResult, type PreviewOptions, type PreviewServer, type PreviewServerHook, type ProxyOptions, type RenderBuiltAssetUrl, type ResolveFn, type ResolveModulePreloadDependenciesFn, type ResolveOptions, type ResolvedBuildEnvironmentOptions, type ResolvedBuildOptions, type ResolvedCSSOptions, type ResolvedConfig, type ResolvedDevEnvironmentOptions, type ResolvedModulePreloadOptions, type ResolvedPreviewOptions, type ResolvedSSROptions, type ResolvedServerOptions, type ResolvedServerUrls, type ResolvedUrl, type ResolvedWorkerOptions, type ResolverFunction, type ResolverObject, type RollupCommonJSOptions, type RollupDynamicImportVarsOptions, RunnableDevEnvironment, type RunnableDevEnvironmentContext, type SSROptions, type SSRTarget, type SassPreprocessorOptions, type SendOptions, type ServerHMRChannel, type ServerHook, type ServerHotChannel, type ServerModuleRunnerOptions, type ServerOptions, SplitVendorChunkCache, type SsrDepOptimizationConfig, type StylusPreprocessorOptions, Terser, type TerserOptions, type TransformOptions, type TransformResult, type UserConfig, type UserConfigExport, type UserConfigFn, type UserConfigFnObject, type UserConfigFnPromise, type ViteBuilder, type ViteDevServer, type WatchOptions, WebSocket, WebSocketAlias, type WebSocketClient, type WebSocketCustomListener, WebSocketServer, build, buildErrorMessage, createBuilder, createFilter, createIdResolver, createLogger, createRunnableDevEnvironment, createServer, createServerHotChannel, createServerModuleRunner, defineConfig, fetchModule, formatPostcssSourceMap, isCSSRequest, isFileLoadingAllowed, isFileServingAllowed, isRunnableDevEnvironment, loadConfigFromFile, loadEnv, mergeAlias, mergeConfig, ssrTransform as moduleRunnerTransform, normalizePath, optimizeDeps, preprocessCSS, preview, resolveConfig, resolveEnvPrefix, rollupVersion, searchForWorkspaceRoot, send, sortUserPlugins, splitVendorChunk, splitVendorChunkPlugin, transformWithEsbuild, VERSION as version };