This commit is contained in:
2025-04-17 19:16:42 +02:00
parent 94a90edabd
commit ab2db755ef
88 changed files with 8427 additions and 10994 deletions

View File

@@ -56,13 +56,16 @@ class HMRContext {
decline() {
}
invalidate(message) {
const firstInvalidatedBy = this.hmrClient.currentFirstInvalidatedBy ?? this.ownerPath;
this.hmrClient.notifyListeners("vite:invalidate", {
path: this.ownerPath,
message
message,
firstInvalidatedBy
});
this.send("vite:invalidate", {
path: this.ownerPath,
message
message,
firstInvalidatedBy
});
this.hmrClient.logger.debug(
`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
@@ -160,7 +163,7 @@ class HMRClient {
});
}
warnFailedUpdate(err, path) {
if (!err.message.includes("fetch")) {
if (!(err instanceof Error) || !err.message.includes("fetch")) {
this.logger.error(err);
}
this.logger.error(
@@ -184,7 +187,7 @@ class HMRClient {
}
}
async fetchUpdate(update) {
const { path, acceptedPath } = update;
const { path, acceptedPath, firstInvalidatedBy } = update;
const mod = this.hotModulesMap.get(path);
if (!mod) {
return;
@@ -204,13 +207,20 @@ class HMRClient {
}
}
return () => {
for (const { deps, fn } of qualifiedCallbacks) {
fn(
deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)
);
try {
this.currentFirstInvalidatedBy = firstInvalidatedBy;
for (const { deps, fn } of qualifiedCallbacks) {
fn(
deps.map(
(dep) => dep === acceptedPath ? fetchedModule : void 0
)
);
}
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
this.logger.debug(`hot updated: ${loggedPath}`);
} finally {
this.currentFirstInvalidatedBy = void 0;
}
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
this.logger.debug(`hot updated: ${loggedPath}`);
};
}
}
@@ -475,6 +485,42 @@ const createWebSocketModuleRunnerTransport = (options) => {
};
};
function createHMRHandler(handler) {
const queue = new Queue();
return (payload) => queue.enqueue(() => handler(payload));
}
class Queue {
constructor() {
this.queue = [];
this.pending = false;
}
enqueue(promise) {
return new Promise((resolve, reject) => {
this.queue.push({
promise,
resolve,
reject
});
this.dequeue();
});
}
dequeue() {
if (this.pending) {
return false;
}
const item = this.queue.shift();
if (!item) {
return false;
}
this.pending = true;
item.promise().then(item.resolve).catch(item.reject).finally(() => {
this.pending = false;
this.dequeue();
});
return true;
}
}
const hmrConfigName = __HMR_CONFIG_NAME__;
const base$1 = __BASE__ || "/";
function h(e, attrs = {}, ...children) {
@@ -859,14 +905,14 @@ const hmrClient = new HMRClient(
return await importPromise;
}
);
transport.connect(handleMessage);
transport.connect(createHMRHandler(handleMessage));
async function handleMessage(payload) {
switch (payload.type) {
case "connected":
console.debug(`[vite] connected.`);
break;
case "update":
notifyListeners("vite:beforeUpdate", payload);
await hmrClient.notifyListeners("vite:beforeUpdate", payload);
if (hasDocument) {
if (isFirstUpdate && hasErrorOverlay()) {
location.reload();
@@ -909,10 +955,10 @@ async function handleMessage(payload) {
});
})
);
notifyListeners("vite:afterUpdate", payload);
await hmrClient.notifyListeners("vite:afterUpdate", payload);
break;
case "custom": {
notifyListeners(payload.event, payload.data);
await hmrClient.notifyListeners(payload.event, payload.data);
if (payload.event === "vite:ws:disconnect") {
if (hasDocument && !willUnload) {
console.log(`[vite] server connection lost. Polling for restart...`);
@@ -926,7 +972,7 @@ async function handleMessage(payload) {
break;
}
case "full-reload":
notifyListeners("vite:beforeFullReload", payload);
await hmrClient.notifyListeners("vite:beforeFullReload", payload);
if (hasDocument) {
if (payload.path && payload.path.endsWith(".html")) {
const pagePath = decodeURI(location.pathname);
@@ -941,11 +987,11 @@ async function handleMessage(payload) {
}
break;
case "prune":
notifyListeners("vite:beforePrune", payload);
await hmrClient.notifyListeners("vite:beforePrune", payload);
await hmrClient.prunePaths(payload.paths);
break;
case "error": {
notifyListeners("vite:error", payload);
await hmrClient.notifyListeners("vite:error", payload);
if (hasDocument) {
const err = payload.err;
if (enableOverlay) {
@@ -968,9 +1014,6 @@ ${err.stack}`
}
}
}
function notifyListeners(event, data) {
hmrClient.notifyListeners(event, data);
}
const enableOverlay = __HMR_ENABLE_OVERLAY__;
const hasDocument = "document" in globalThis;
function createErrorOverlay(err) {

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -1,4 +1,4 @@
import { P as getDefaultExportFromCjs } from './dep-Bid9ssRr.js';
import { P as getDefaultExportFromCjs } from './dep-Bxmd1Uxj.js';
import require$$0 from 'path';
import { l as lib } from './dep-3RmXg9uo.js';

View File

@@ -1,4 +1,4 @@
import { Q as commonjsGlobal, P as getDefaultExportFromCjs } from './dep-Bid9ssRr.js';
import { Q as commonjsGlobal, P as getDefaultExportFromCjs } from './dep-Bxmd1Uxj.js';
import require$$0$2 from 'fs';
import require$$0 from 'postcss';
import require$$0$1 from 'path';

13
node_modules/vite/dist/node/cli.js generated vendored
View File

@@ -2,16 +2,18 @@ import path from 'node:path';
import fs__default from 'node:fs';
import { performance } from 'node:perf_hooks';
import { EventEmitter } from 'events';
import { O as colors, I as createLogger, r as resolveConfig } from './chunks/dep-Bid9ssRr.js';
import { O as colors, I as createLogger, r as resolveConfig } from './chunks/dep-Bxmd1Uxj.js';
import { VERSION } from './constants.js';
import 'node:fs/promises';
import 'node:url';
import 'node:util';
import 'node:module';
import 'node:crypto';
import 'picomatch';
import 'esbuild';
import 'path';
import 'fs';
import 'fdir';
import 'node:child_process';
import 'node:http';
import 'node:https';
@@ -33,6 +35,7 @@ import 'module';
import 'node:readline';
import 'node:process';
import 'node:events';
import 'tinyglobby';
import 'crypto';
import 'node:assert';
import 'node:v8';
@@ -745,7 +748,7 @@ cli.command("[root]", "start dev server").alias("serve").alias("dev").option("--
`[boolean] force the optimizer to ignore the cache and re-bundle`
).action(async (root, options) => {
filterDuplicateOptions(options);
const { createServer } = await import('./chunks/dep-Bid9ssRr.js').then(function (n) { return n.S; });
const { createServer } = await import('./chunks/dep-Bxmd1Uxj.js').then(function (n) { return n.S; });
try {
const server = await createServer({
root,
@@ -840,7 +843,7 @@ cli.command("build [root]", "build for production").option("--target <target>",
).option("-w, --watch", `[boolean] rebuilds when modules have changed on disk`).option("--app", `[boolean] same as \`builder: {}\``).action(
async (root, options) => {
filterDuplicateOptions(options);
const { createBuilder } = await import('./chunks/dep-Bid9ssRr.js').then(function (n) { return n.T; });
const { createBuilder } = await import('./chunks/dep-Bxmd1Uxj.js').then(function (n) { return n.T; });
const buildOptions = cleanGlobalCLIOptions(
cleanBuilderCLIOptions(options)
);
@@ -879,7 +882,7 @@ cli.command(
).action(
async (root, options) => {
filterDuplicateOptions(options);
const { optimizeDeps } = await import('./chunks/dep-Bid9ssRr.js').then(function (n) { return n.R; });
const { optimizeDeps } = await import('./chunks/dep-Bxmd1Uxj.js').then(function (n) { return n.R; });
try {
const config = await resolveConfig(
{
@@ -906,7 +909,7 @@ ${e.stack}`),
cli.command("preview [root]", "locally preview production build").option("--host [host]", `[string] specify hostname`, { type: [convertHost] }).option("--port <port>", `[number] specify port`).option("--strictPort", `[boolean] exit if specified port is already in use`).option("--open [path]", `[boolean | string] open browser on startup`).option("--outDir <dir>", `[string] output directory (default: dist)`).action(
async (root, options) => {
filterDuplicateOptions(options);
const { preview } = await import('./chunks/dep-Bid9ssRr.js').then(function (n) { return n.U; });
const { preview } = await import('./chunks/dep-Bxmd1Uxj.js').then(function (n) { return n.U; });
try {
const server = await preview({
root,

View File

@@ -31,7 +31,7 @@ export { LightningCSSOptions } from '../../types/internal/lightningcssOptions.js
import { SassLegacyPreprocessBaseOptions, SassModernPreprocessBaseOptions, LessPreprocessorBaseOptions, StylusPreprocessorBaseOptions } from '../../types/internal/cssPreprocessorOptions.js';
import { M as ModuleRunnerTransport } from './moduleRunnerTransport.d-CXw_Ws6P.js';
export { GeneralImportGlobOptions, ImportGlobFunction, ImportGlobOptions, KnownAsTypeMap } from '../../types/importGlob.js';
export { ChunkMetadata } from '../../types/metadata.js';
export { ChunkMetadata, CustomPluginOptionsVite } from '../../types/metadata.js';
interface Alias {
find: string | RegExp
@@ -848,7 +848,7 @@ declare class BaseEnvironment extends PartialEnvironment {
* const isDev = environment.mode === 'dev' // good
* ```
*
* You should also not check against `"unknown"` specfically. It's
* You should also not check against `"unknown"` specifically. It's
* a placeholder for more possible environment types.
*/
declare class UnknownEnvironment extends BaseEnvironment {
@@ -3200,6 +3200,11 @@ type IndexHtmlTransform = IndexHtmlTransformHook | {
handler: IndexHtmlTransformHook;
};
type StringFilter<Value = string | RegExp> = Value | Array<Value> | {
include?: Value | Array<Value>;
exclude?: Value | Array<Value>;
};
/**
* Vite plugins extends the Rollup plugin interface with a few extra
* vite-specific options. A valid vite plugin is also a valid Rollup plugin.
@@ -3280,13 +3285,26 @@ interface Plugin<A = any> extends rollup.Plugin<A> {
custom?: CustomPluginOptions;
ssr?: boolean;
isEntry: boolean;
}) => Promise<ResolveIdResult> | ResolveIdResult>;
}) => Promise<ResolveIdResult> | ResolveIdResult, {
filter?: {
id?: StringFilter<RegExp>;
};
}>;
load?: ObjectHook<(this: PluginContext, id: string, options?: {
ssr?: boolean;
}) => Promise<LoadResult> | LoadResult>;
}) => Promise<LoadResult> | LoadResult, {
filter?: {
id?: StringFilter;
};
}>;
transform?: ObjectHook<(this: TransformPluginContext, code: string, id: string, options?: {
ssr?: boolean;
}) => Promise<rollup.TransformResult> | rollup.TransformResult>;
}) => Promise<rollup.TransformResult> | rollup.TransformResult, {
filter?: {
id?: StringFilter;
code?: StringFilter;
};
}>;
/**
* Opt-in this plugin into the shared plugins pipeline.
* For backward-compatibility, plugins are re-recreated for each environment
@@ -3383,8 +3401,13 @@ interface Plugin<A = any> extends rollup.Plugin<A> {
* The hook receives the following arguments:
*
* - html: string
* - ctx?: vite.ServerContext (only present during serve)
* - bundle?: rollup.OutputBundle (only present during build)
* - ctx: IndexHtmlTransformContext, which contains:
* - path: public path when served
* - filename: filename on disk
* - server?: ViteDevServer (only present during serve)
* - bundle?: rollup.OutputBundle (only present during build)
* - chunk?: rollup.OutputChunk
* - originalUrl?: string
*
* It can either return a transformed string, or a list of html tag
* descriptors that will be injected into the `<head>` or `<body>`.
@@ -3427,7 +3450,7 @@ interface CSSOptions {
/**
* Using lightningcss is an experimental option to handle CSS modules,
* assets and imports via Lightning CSS. It requires to install it as a
* peer dependency. This is incompatible with the use of preprocessors.
* peer dependency.
*
* @default 'postcss'
* @experimental
@@ -3484,7 +3507,7 @@ interface CSSModulesOptions {
*/
localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | ((originalClassName: string, generatedClassName: string, inputFile: string) => string);
}
type ResolvedCSSOptions = Omit<CSSOptions, 'lightningcss'> & Required<Pick<CSSOptions, 'transformer'>> & {
type ResolvedCSSOptions = Omit<CSSOptions, 'lightningcss'> & Required<Pick<CSSOptions, 'transformer' | 'devSourcemap'>> & {
lightningcss?: LightningCSSOptions;
};
interface PreprocessCSSResult {
@@ -3723,7 +3746,7 @@ type ResolvedEnvironmentOptions = {
dev: ResolvedDevEnvironmentOptions;
build: ResolvedBuildEnvironmentOptions;
};
type DefaultEnvironmentOptions = Omit<EnvironmentOptions, 'consumer' | 'resolve'> & {
type DefaultEnvironmentOptions = Omit<EnvironmentOptions, 'consumer' | 'resolve' | 'keepProcessEnv'> & {
resolve?: AllResolveOptions;
};
interface UserConfig extends DefaultEnvironmentOptions {
@@ -3837,7 +3860,7 @@ interface UserConfig extends DefaultEnvironmentOptions {
* root.
* @default root
*/
envDir?: string;
envDir?: string | false;
/**
* Env variables starts with `envPrefix` will be exposed to your client source code via import.meta.env.
* @default 'VITE_'
@@ -3965,6 +3988,7 @@ interface InlineConfig extends UserConfig {
configFile?: string | false;
/** @experimental */
configLoader?: 'bundle' | 'runner' | 'native';
/** @deprecated */
envFile?: false;
forceOptimizeDeps?: boolean;
}
@@ -3980,7 +4004,7 @@ interface ResolvedConfig extends Readonly<Omit<UserConfig, 'plugins' | 'css' | '
mode: string;
isWorker: boolean;
isProduction: boolean;
envDir: string;
envDir: string | false;
env: Record<string, any>;
resolve: Required<ResolveOptions> & {
alias: Alias[];
@@ -4081,6 +4105,17 @@ declare class RunnableDevEnvironment extends DevEnvironment {
close(): Promise<void>;
}
interface FetchableDevEnvironmentContext extends DevEnvironmentContext {
handleRequest(request: Request): Promise<Response> | Response;
}
declare function createFetchableDevEnvironment(name: string, config: ResolvedConfig, context: FetchableDevEnvironmentContext): FetchableDevEnvironment;
declare function isFetchableDevEnvironment(environment: Environment): environment is FetchableDevEnvironment;
declare class FetchableDevEnvironment extends DevEnvironment {
private _handleRequest;
constructor(name: string, config: ResolvedConfig, context: FetchableDevEnvironmentContext);
dispatchFetch(request: Request): Promise<Response>;
}
interface RunnerImportResult<T> {
module: T;
dependencies: string[];
@@ -4175,7 +4210,7 @@ declare function isFileServingAllowed(config: ResolvedConfig, url: string): bool
declare function isFileServingAllowed(url: string, server: ViteDevServer): boolean;
declare function isFileLoadingAllowed(config: ResolvedConfig, filePath: string): boolean;
declare function loadEnv(mode: string, envDir: string, prefixes?: string | string[]): Record<string, string>;
declare function loadEnv(mode: string, envDir: string | false, prefixes?: string | string[]): Record<string, string>;
declare function resolveEnvPrefix({ envPrefix, }: UserConfig): string[];
type Manifest = Record<string, ManifestChunk>;
@@ -4191,4 +4226,4 @@ interface ManifestChunk {
dynamicImports?: string[];
}
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 NormalizedHotChannel, type NormalizedHotChannelClient, type NormalizedServerHotChannel, 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, type SkipInformation, 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, createServerModuleRunnerTransport, defaultAllowedOrigins, DEFAULT_CLIENT_CONDITIONS as defaultClientConditions, DEFAULT_CLIENT_MAIN_FIELDS as defaultClientMainFields, DEFAULT_SERVER_CONDITIONS as defaultServerConditions, DEFAULT_SERVER_MAIN_FIELDS as defaultServerMainFields, defineConfig, fetchModule, formatPostcssSourceMap, isCSSRequest, isFileLoadingAllowed, isFileServingAllowed, isRunnableDevEnvironment, loadConfigFromFile, loadEnv, mergeAlias, mergeConfig, ssrTransform as moduleRunnerTransform, normalizePath, optimizeDeps, perEnvironmentPlugin, perEnvironmentState, preprocessCSS, preview, resolveConfig, resolveEnvPrefix, rollupVersion, runnerImport, searchForWorkspaceRoot, send, sortUserPlugins, splitVendorChunk, splitVendorChunkPlugin, transformWithEsbuild, VERSION as version };
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, FetchableDevEnvironment, type FetchableDevEnvironmentContext, 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 NormalizedHotChannel, type NormalizedHotChannelClient, type NormalizedServerHotChannel, 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, type SkipInformation, 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, createFetchableDevEnvironment, createFilter, createIdResolver, createLogger, createRunnableDevEnvironment, createServer, createServerHotChannel, createServerModuleRunner, createServerModuleRunnerTransport, defaultAllowedOrigins, DEFAULT_CLIENT_CONDITIONS as defaultClientConditions, DEFAULT_CLIENT_MAIN_FIELDS as defaultClientMainFields, DEFAULT_SERVER_CONDITIONS as defaultServerConditions, DEFAULT_SERVER_MAIN_FIELDS as defaultServerMainFields, defineConfig, fetchModule, formatPostcssSourceMap, isCSSRequest, isFetchableDevEnvironment, isFileLoadingAllowed, isFileServingAllowed, isRunnableDevEnvironment, loadConfigFromFile, loadEnv, mergeAlias, mergeConfig, ssrTransform as moduleRunnerTransform, normalizePath, optimizeDeps, perEnvironmentPlugin, perEnvironmentState, preprocessCSS, preview, resolveConfig, resolveEnvPrefix, rollupVersion, runnerImport, searchForWorkspaceRoot, send, sortUserPlugins, splitVendorChunk, splitVendorChunkPlugin, transformWithEsbuild, VERSION as version };

47
node_modules/vite/dist/node/index.js generated vendored
View File

@@ -1,6 +1,6 @@
export { parseAst, parseAstAsync } from 'rollup/parseAst';
import { a as arraify, i as isInNodeModules } from './chunks/dep-Bid9ssRr.js';
export { B as BuildEnvironment, D as DevEnvironment, f as build, m as buildErrorMessage, g as createBuilder, F as createFilter, h as createIdResolver, I as createLogger, n as createRunnableDevEnvironment, c as createServer, y as createServerHotChannel, w as createServerModuleRunner, x as createServerModuleRunnerTransport, d as defineConfig, v as fetchModule, j as formatPostcssSourceMap, L as isFileLoadingAllowed, K as isFileServingAllowed, q as isRunnableDevEnvironment, l as loadConfigFromFile, M as loadEnv, E as mergeAlias, C as mergeConfig, z as moduleRunnerTransform, A as normalizePath, o as optimizeDeps, p as perEnvironmentPlugin, b as perEnvironmentState, k as preprocessCSS, e as preview, r as resolveConfig, N as resolveEnvPrefix, G as rollupVersion, u as runnerImport, J as searchForWorkspaceRoot, H as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-Bid9ssRr.js';
import { a as arraify, i as isInNodeModules, D as DevEnvironment } from './chunks/dep-Bxmd1Uxj.js';
export { B as BuildEnvironment, f as build, m as buildErrorMessage, g as createBuilder, F as createFilter, h as createIdResolver, I as createLogger, n as createRunnableDevEnvironment, c as createServer, y as createServerHotChannel, w as createServerModuleRunner, x as createServerModuleRunnerTransport, d as defineConfig, v as fetchModule, j as formatPostcssSourceMap, L as isFileLoadingAllowed, K as isFileServingAllowed, q as isRunnableDevEnvironment, l as loadConfigFromFile, M as loadEnv, E as mergeAlias, C as mergeConfig, z as moduleRunnerTransform, A as normalizePath, o as optimizeDeps, p as perEnvironmentPlugin, b as perEnvironmentState, k as preprocessCSS, e as preview, r as resolveConfig, N as resolveEnvPrefix, G as rollupVersion, u as runnerImport, J as searchForWorkspaceRoot, H as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-Bxmd1Uxj.js';
export { defaultAllowedOrigins, DEFAULT_CLIENT_CONDITIONS as defaultClientConditions, DEFAULT_CLIENT_MAIN_FIELDS as defaultClientMainFields, DEFAULT_SERVER_CONDITIONS as defaultServerConditions, DEFAULT_SERVER_MAIN_FIELDS as defaultServerMainFields, VERSION as version } from './constants.js';
export { version as esbuildVersion } from 'esbuild';
import 'node:fs';
@@ -11,8 +11,10 @@ import 'node:util';
import 'node:perf_hooks';
import 'node:module';
import 'node:crypto';
import 'picomatch';
import 'path';
import 'fs';
import 'fdir';
import 'node:child_process';
import 'node:http';
import 'node:https';
@@ -34,6 +36,7 @@ import 'module';
import 'node:readline';
import 'node:process';
import 'node:events';
import 'tinyglobby';
import 'crypto';
import 'node:assert';
import 'node:v8';
@@ -150,4 +153,42 @@ function splitVendorChunkPlugin() {
};
}
export { isCSSRequest, splitVendorChunk, splitVendorChunkPlugin };
function createFetchableDevEnvironment(name, config, context) {
if (typeof Request === "undefined" || typeof Response === "undefined") {
throw new TypeError(
"FetchableDevEnvironment requires a global `Request` and `Response` object."
);
}
if (!context.handleRequest) {
throw new TypeError(
"FetchableDevEnvironment requires a `handleRequest` method during initialisation."
);
}
return new FetchableDevEnvironment(name, config, context);
}
function isFetchableDevEnvironment(environment) {
return environment instanceof FetchableDevEnvironment;
}
class FetchableDevEnvironment extends DevEnvironment {
_handleRequest;
constructor(name, config, context) {
super(name, config, context);
this._handleRequest = context.handleRequest;
}
async dispatchFetch(request) {
if (!(request instanceof Request)) {
throw new TypeError(
"FetchableDevEnvironment `dispatchFetch` must receive a `Request` object."
);
}
const response = await this._handleRequest(request);
if (!(response instanceof Response)) {
throw new TypeError(
"FetchableDevEnvironment `context.handleRequest` must return a `Response` object."
);
}
return response;
}
}
export { DevEnvironment, createFetchableDevEnvironment, isCSSRequest, isFetchableDevEnvironment, splitVendorChunk, splitVendorChunkPlugin };

View File

@@ -51,6 +51,7 @@ declare class HMRClient {
dataMap: Map<string, any>;
customListenersMap: CustomListenersMap;
ctxToListenersMap: Map<string, CustomListenersMap>;
currentFirstInvalidatedBy: string | undefined;
constructor(logger: HMRLogger, transport: NormalizedModuleRunnerTransport, importUpdatedModule: (update: Update) => Promise<ModuleNamespace>);
notifyListeners<T extends string>(event: T, data: InferCustomEventPayload<T>): Promise<void>;
send(payload: HotPayload): void;

View File

@@ -383,12 +383,15 @@ class HMRContext {
decline() {
}
invalidate(message) {
const firstInvalidatedBy = this.hmrClient.currentFirstInvalidatedBy ?? this.ownerPath;
this.hmrClient.notifyListeners("vite:invalidate", {
path: this.ownerPath,
message
message,
firstInvalidatedBy
}), this.send("vite:invalidate", {
path: this.ownerPath,
message
message,
firstInvalidatedBy
}), this.hmrClient.logger.debug(
`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
);
@@ -439,6 +442,7 @@ class HMRClient {
dataMap = /* @__PURE__ */ new Map();
customListenersMap = /* @__PURE__ */ new Map();
ctxToListenersMap = /* @__PURE__ */ new Map();
currentFirstInvalidatedBy;
async notifyListeners(event, data) {
const cbs = this.customListenersMap.get(event);
cbs && await Promise.allSettled(cbs.map((cb) => cb(data)));
@@ -466,7 +470,7 @@ class HMRClient {
});
}
warnFailedUpdate(err, path) {
err.message.includes("fetch") || this.logger.error(err), this.logger.error(
(!(err instanceof Error) || !err.message.includes("fetch")) && this.logger.error(err), this.logger.error(
`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
);
}
@@ -485,7 +489,7 @@ class HMRClient {
}
}
async fetchUpdate(update) {
const { path, acceptedPath } = update, mod = this.hotModulesMap.get(path);
const { path, acceptedPath, firstInvalidatedBy } = update, mod = this.hotModulesMap.get(path);
if (!mod)
return;
let fetchedModule;
@@ -502,12 +506,19 @@ class HMRClient {
}
}
return () => {
for (const { deps, fn } of qualifiedCallbacks)
fn(
deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)
);
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
this.logger.debug(`hot updated: ${loggedPath}`);
try {
this.currentFirstInvalidatedBy = firstInvalidatedBy;
for (const { deps, fn } of qualifiedCallbacks)
fn(
deps.map(
(dep) => dep === acceptedPath ? fetchedModule : void 0
)
);
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
this.logger.debug(`hot updated: ${loggedPath}`);
} finally {
this.currentFirstInvalidatedBy = void 0;
}
};
}
}
@@ -722,67 +733,9 @@ const createInvokeableTransport = (transport) => {
debug: (...msg) => console.log("[vite]", ...msg),
error: (error) => console.log("[vite]", error)
};
function createHMRHandler(runner) {
function createHMRHandler(handler) {
const queue = new Queue();
return (payload) => queue.enqueue(() => handleHotPayload(runner, payload));
}
async function handleHotPayload(runner, payload) {
const hmrClient = runner.hmrClient;
if (!(!hmrClient || runner.isClosed()))
switch (payload.type) {
case "connected":
hmrClient.logger.debug("connected.");
break;
case "update":
await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(
payload.updates.map(async (update) => {
if (update.type === "js-update")
return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
hmrClient.logger.error("css hmr is not supported in runner mode.");
})
), await hmrClient.notifyListeners("vite:afterUpdate", payload);
break;
case "custom": {
await hmrClient.notifyListeners(payload.event, payload.data);
break;
}
case "full-reload": {
const { triggeredBy } = payload, clearEntrypointUrls = triggeredBy ? getModulesEntrypoints(
runner,
getModulesByFile(runner, slash(triggeredBy))
) : findAllEntrypoints(runner);
if (!clearEntrypointUrls.size) break;
hmrClient.logger.debug("program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runner.evaluatedModules.clear();
for (const url of clearEntrypointUrls)
try {
await runner.import(url);
} catch (err) {
err.code !== ERR_OUTDATED_OPTIMIZED_DEP && hmrClient.logger.error(
`An error happened during full reload
${err.message}
${err.stack}`
);
}
break;
}
case "prune":
await hmrClient.notifyListeners("vite:beforePrune", payload), await hmrClient.prunePaths(payload.paths);
break;
case "error": {
await hmrClient.notifyListeners("vite:error", payload);
const err = payload.err;
hmrClient.logger.error(
`Internal Server Error
${err.message}
${err.stack}`
);
break;
}
case "ping":
break;
default:
return payload;
}
return (payload) => queue.enqueue(() => handler(payload));
}
class Queue {
queue = [];
@@ -805,6 +758,66 @@ class Queue {
}), !0) : !1;
}
}
function createHMRHandlerForRunner(runner) {
return createHMRHandler(async (payload) => {
const hmrClient = runner.hmrClient;
if (!(!hmrClient || runner.isClosed()))
switch (payload.type) {
case "connected":
hmrClient.logger.debug("connected.");
break;
case "update":
await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(
payload.updates.map(async (update) => {
if (update.type === "js-update")
return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
hmrClient.logger.error("css hmr is not supported in runner mode.");
})
), await hmrClient.notifyListeners("vite:afterUpdate", payload);
break;
case "custom": {
await hmrClient.notifyListeners(payload.event, payload.data);
break;
}
case "full-reload": {
const { triggeredBy } = payload, clearEntrypointUrls = triggeredBy ? getModulesEntrypoints(
runner,
getModulesByFile(runner, slash(triggeredBy))
) : findAllEntrypoints(runner);
if (!clearEntrypointUrls.size) break;
hmrClient.logger.debug("program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runner.evaluatedModules.clear();
for (const url of clearEntrypointUrls)
try {
await runner.import(url);
} catch (err) {
err.code !== ERR_OUTDATED_OPTIMIZED_DEP && hmrClient.logger.error(
`An error happened during full reload
${err.message}
${err.stack}`
);
}
break;
}
case "prune":
await hmrClient.notifyListeners("vite:beforePrune", payload), await hmrClient.prunePaths(payload.paths);
break;
case "error": {
await hmrClient.notifyListeners("vite:error", payload);
const err = payload.err;
hmrClient.logger.error(
`Internal Server Error
${err.message}
${err.stack}`
);
break;
}
case "ping":
break;
default:
return payload;
}
});
}
function getModulesByFile(runner, file) {
const nodes = runner.evaluatedModules.getModulesByFile(file);
return nodes ? [...nodes].map((node) => node.id) : [];
@@ -1078,7 +1091,7 @@ class ModuleRunner {
throw new Error(
"HMR is not supported by this runner transport, but `hmr` option was set to true"
);
this.transport.connect(createHMRHandler(this));
this.transport.connect(createHMRHandlerForRunner(this));
} else
this.transport.connect?.();
options.sourcemapInterceptor !== !1 && (this.resetSourceMapSupport = enableSourceMapSupport(this));