Compare commits

...

1 commit

Author SHA1 Message Date
Matthew Phillips
6fd7aa710f testig... 2022-01-24 16:02:51 -05:00
85 changed files with 8842 additions and 16294 deletions

18
packages/astro/vendor/vite/dist/client/client.mjs vendored Executable file → Normal file
View file

@ -199,16 +199,6 @@ function warnFailedFetch(err, path) {
socket.addEventListener('message', async ({ data }) => {
handleMessage(JSON.parse(data));
});
/**
* This cleans up the query params and removes the `direct` param which is internal.
* Other query params are preserved.
*/
function cleanUrl(pathname) {
let url = new URL(pathname, location);
url.searchParams.delete('direct');
return url.pathname + url.search;
}
let isFirstUpdate = true;
async function handleMessage(payload) {
switch (payload.type) {
@ -240,13 +230,11 @@ async function handleMessage(payload) {
// css-update
// this is only sent when a css file referenced with <link> is updated
let { path, timestamp } = update;
let searchUrl = cleanUrl(path);
path = path.replace(/\?.*/, '');
// can't use querySelector with `[href*=]` here since the link may be
// using relative paths so we need to use link.href to grab the full
// URL for the include check.
const el = [].slice.call(document.querySelectorAll(`link`)).find((e) => {
return cleanUrl(e.href).includes(searchUrl)
});
const el = Array.from(document.querySelectorAll('link')).find((e) => e.href.includes(path));
if (el) {
const newPath = `${base}${path.slice(1)}${path.includes('?') ? '&' : '?'}t=${timestamp}`;
el.href = new URL(newPath, el.href).href;
@ -389,8 +377,6 @@ function removeStyle(id) {
const style = sheetsMap.get(id);
if (style) {
if (style instanceof CSSStyleSheet) {
// @ts-ignore
document.adoptedStyleSheets.indexOf(style);
// @ts-ignore
document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== style);
}

2
packages/astro/vendor/vite/dist/client/client.mjs.map vendored Executable file → Normal file

File diff suppressed because one or more lines are too long

0
packages/astro/vendor/vite/dist/client/env.mjs vendored Executable file → Normal file
View file

0
packages/astro/vendor/vite/dist/client/env.mjs.map vendored Executable file → Normal file
View file

View file

@ -0,0 +1,200 @@
import { InlineConfig, ResolvedConfig } from './config';
import { Plugin, RollupOptions, RollupWarning, WarningHandler, RollupOutput, WatcherOptions, RollupWatcher, ModuleFormat } from 'rollup';
import { Terser } from 'types/terser';
import { RollupCommonJSOptions } from 'types/commonjs';
import { RollupDynamicImportVarsOptions } from 'types/dynamicImportVars';
import { TransformOptions } from 'esbuild';
export interface BuildOptions {
/**
* Base public path when served in production.
* @deprecated `base` is now a root-level config option.
*/
base?: string;
/**
* Compatibility transform target. The transform is performed with esbuild
* and the lowest supported target is es2015/es6. Note this only handles
* syntax transformation and does not cover polyfills (except for dynamic
* import)
*
* Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules,
* transpile targeting browsers that natively support dynamic es module imports.
* https://caniuse.com/es6-module-dynamic-import
*
* Another special value is 'esnext' - which only performs minimal transpiling
* (for minification compat) and assumes native dynamic imports support.
*
* For custom targets, see https://esbuild.github.io/api/#target and
* https://esbuild.github.io/content-types/#javascript for more details.
*/
target?: 'modules' | TransformOptions['target'] | false;
/**
* whether to inject module preload polyfill.
* Note: does not apply to library mode.
* @default true
*/
polyfillModulePreload?: boolean;
/**
* whether to inject dynamic import polyfill.
* Note: does not apply to library mode.
* @default false
* @deprecated use plugin-legacy for browsers that don't support dynamic import
*/
polyfillDynamicImport?: boolean;
/**
* Directory relative from `root` where build output will be placed. If the
* directory exists, it will be removed before the build.
* @default 'dist'
*/
outDir?: string;
/**
* Directory relative from `outDir` where the built js/css/image assets will
* be placed.
* @default 'assets'
*/
assetsDir?: string;
/**
* Static asset files smaller than this number (in bytes) will be inlined as
* base64 strings. Default limit is `4096` (4kb). Set to `0` to disable.
* @default 4096
*/
assetsInlineLimit?: number;
/**
* Whether to code-split CSS. When enabled, CSS in async chunks will be
* inlined as strings in the chunk and inserted via dynamically created
* style tags when the chunk is loaded.
* @default true
*/
cssCodeSplit?: boolean;
/**
* An optional separate target for CSS minification.
* As esbuild only supports configuring targets to mainstream
* browsers, users may need this option when they are targeting
* a niche browser that comes with most modern JavaScript features
* but has poor CSS support, e.g. Android WeChat WebView, which
* doesn't support the #RGBA syntax.
*/
cssTarget?: TransformOptions['target'] | false;
/**
* If `true`, a separate sourcemap file will be created. If 'inline', the
* sourcemap will be appended to the resulting output file as data URI.
* 'hidden' works like `true` except that the corresponding sourcemap
* comments in the bundled files are suppressed.
* @default false
*/
sourcemap?: boolean | 'inline' | 'hidden';
/**
* Set to `false` to disable minification, or specify the minifier to use.
* Available options are 'terser' or 'esbuild'.
* @default 'esbuild'
*/
minify?: boolean | 'terser' | 'esbuild';
/**
* Options for terser
* https://terser.org/docs/api-reference#minify-options
*/
terserOptions?: Terser.MinifyOptions;
/**
* @deprecated Vite now uses esbuild for CSS minification.
*/
cleanCssOptions?: any;
/**
* Will be merged with internal rollup options.
* https://rollupjs.org/guide/en/#big-list-of-options
*/
rollupOptions?: RollupOptions;
/**
* Options to pass on to `@rollup/plugin-commonjs`
*/
commonjsOptions?: RollupCommonJSOptions;
/**
* Options to pass on to `@rollup/plugin-dynamic-import-vars`
*/
dynamicImportVarsOptions?: RollupDynamicImportVarsOptions;
/**
* Whether to write bundle to disk
* @default true
*/
write?: boolean;
/**
* Empty outDir on write.
* @default true when outDir is a sub directory of project root
*/
emptyOutDir?: boolean | null;
/**
* Whether to emit a manifest.json under assets dir to map hash-less filenames
* to their hashed versions. Useful when you want to generate your own HTML
* instead of using the one generated by Vite.
*
* Example:
*
* ```json
* {
* "main.js": {
* "file": "main.68fe3fad.js",
* "css": "main.e6b63442.css",
* "imports": [...],
* "dynamicImports": [...]
* }
* }
* ```
* @default false
*/
manifest?: boolean;
/**
* Build in library mode. The value should be the global name of the lib in
* UMD mode. This will produce esm + cjs + umd bundle formats with default
* configurations that are suitable for distributing libraries.
*/
lib?: LibraryOptions | false;
/**
* Produce SSR oriented build. Note this requires specifying SSR entry via
* `rollupOptions.input`.
*/
ssr?: boolean | string;
/**
* Generate SSR manifest for determining style links and asset preload
* directives in production.
*/
ssrManifest?: boolean;
/**
* Set to false to disable reporting compressed chunk sizes.
* Can slightly improve build speed.
*/
reportCompressedSize?: boolean;
/**
* Set to false to disable brotli compressed size reporting for build.
* Can slightly improve build speed.
* @deprecated use `build.reportCompressedSize` instead.
*/
brotliSize?: boolean;
/**
* Adjust chunk size warning limit (in kbs).
* @default 500
*/
chunkSizeWarningLimit?: number;
/**
* Rollup watch options
* https://rollupjs.org/guide/en/#watchoptions
*/
watch?: WatcherOptions | null;
}
export interface LibraryOptions {
entry: string;
name?: string;
formats?: LibraryFormats[];
fileName?: string | ((format: ModuleFormat) => string);
}
export declare type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife';
export declare type ResolvedBuildOptions = Required<Omit<BuildOptions, 'base' | 'cleanCssOptions' | 'polyfillDynamicImport' | 'brotliSize'>>;
export declare function resolveBuildOptions(root: string, raw?: BuildOptions, isBuild?: boolean): ResolvedBuildOptions;
export declare function resolveBuildPlugins(config: ResolvedConfig): {
pre: Plugin[];
post: Plugin[];
};
/**
* Bundles the app for production.
* Returns a Promise containing the build result.
*/
export declare function build(inlineConfig?: InlineConfig): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
export declare function resolveLibFilename(libOptions: LibraryOptions, format: ModuleFormat, root: string): string;
export declare function onRollupWarning(warning: RollupWarning, warn: WarningHandler, config: ResolvedConfig): void;

View file

@ -10,11 +10,11 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
function _mergeNamespaces(n, m) {
for (var i = 0; i < m.length; i++) {
var e = m[i];
for (var k in e) {
if (typeof e !== 'string' && !Array.isArray(e)) { for (var k in e) {
if (k !== 'default' && !(k in n)) {
n[k] = e[k];
}
}
} }
}
return n;
}
@ -743,4 +743,4 @@ var index = /*#__PURE__*/_mergeNamespaces({
}, [postcssImport]);
exports.index = index;
//# sourceMappingURL=dep-e39b05d6.js.map
//# sourceMappingURL=dep-2d8e2cb1.js.map

File diff suppressed because one or more lines are too long

View file

@ -1,15 +1,15 @@
'use strict';
var build = require('./dep-35df7f96.js');
var build = require('./dep-9ebc60a4.js');
function _mergeNamespaces(n, m) {
for (var i = 0; i < m.length; i++) {
var e = m[i];
for (var k in e) {
if (typeof e !== 'string' && !Array.isArray(e)) { for (var k in e) {
if (k !== 'default' && !(k in n)) {
n[k] = e[k];
}
}
} }
}
return n;
}
@ -376,12 +376,12 @@ function escapeHtml(string) {
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
html += str.slice(lastIndex, index);
}
lastIndex = index + 1;
html += escaped;
}
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
return lastIndex !== index ? html + str.slice(lastIndex, index) : html;
}
// https://www.w3.org/TR/html52/syntax.html#comments
const commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g;
@ -476,17 +476,6 @@ const replacer = (_key, val) => {
return val;
};
/**
* List of @babel/parser plugins that are used for template expression
* transforms and SFC script transforms. By default we enable proposals slated
* for ES2020. This will need to be updated as the spec moves forward.
* Full list at https://babeljs.io/docs/en/next/babel-parser#plugins
*/
const babelParserDefaultPlugins = [
'bigInt',
'optionalChaining',
'nullishCoalescingOperator'
];
const EMPTY_OBJ = (process.env.NODE_ENV !== 'production')
? Object.freeze({})
: {};
@ -603,7 +592,6 @@ var shared_esmBundler = {
NO: NO,
NOOP: NOOP,
PatchFlagNames: PatchFlagNames,
babelParserDefaultPlugins: babelParserDefaultPlugins,
camelize: camelize$1,
capitalize: capitalize,
def: def,
@ -1110,7 +1098,7 @@ const isMemberExpressionNode = NOOP
const isMemberExpression = isMemberExpressionBrowser
;
function getInnerRange(loc, offset, length) {
const source = loc.source.substr(offset, length);
const source = loc.source.slice(offset, offset + length);
const newLoc = {
source,
start: advancePositionWithClone(loc.start, loc.source, offset),
@ -1870,6 +1858,7 @@ function parseTag(context, type, parent) {
}
if (hasIf && hasFor) {
warnDeprecation("COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */, context, getSelection(context, start));
break;
}
}
}
@ -2027,10 +2016,10 @@ function parseAttribute(context, nameSet) {
isStatic = false;
if (!content.endsWith(']')) {
emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
content = content.substr(1);
content = content.slice(1);
}
else {
content = content.substr(1, content.length - 2);
content = content.slice(1, content.length - 1);
}
}
else if (isSlot) {
@ -2056,7 +2045,7 @@ function parseAttribute(context, nameSet) {
valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
valueLoc.source = valueLoc.source.slice(1, -1);
}
const modifiers = match[3] ? match[3].substr(1).split('.') : [];
const modifiers = match[3] ? match[3].slice(1).split('.') : [];
if (isPropShorthand)
modifiers.push('prop');
// 2.x compat v-bind:foo.sync -> v-model:foo
@ -2277,7 +2266,7 @@ function isEnd(context, mode, ancestors) {
}
function startsWithEndTagOpen(source, tag) {
return (startsWith(source, '</') &&
source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
/[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
}
@ -4865,7 +4854,7 @@ function stringifyDynamicPropNames(props) {
return propsNamesString + `]`;
}
function isComponentTag(tag) {
return tag[0].toLowerCase() + tag.slice(1) === 'component';
return tag === 'component' || tag === 'Component';
}
(process.env.NODE_ENV !== 'production')
@ -7933,7 +7922,7 @@ const decodeHtml = (rawText, asAttr) => {
maxCRNameLength = Object.keys(namedCharacterReferences).reduce((max, name) => Math.max(max, name.length), 0);
}
for (let length = maxCRNameLength; !value && length > 0; --length) {
name = rawText.substr(1, length);
name = rawText.slice(1, 1 + length);
value = namedCharacterReferences[name];
}
if (value) {
@ -8731,4 +8720,4 @@ var compilerDom_cjs$1 = /*#__PURE__*/_mergeNamespaces({
}, [compilerDom_cjs$2]);
exports.compilerDom_cjs = compilerDom_cjs$1;
//# sourceMappingURL=dep-a5b4350d.js.map
//# sourceMappingURL=dep-329f35e6.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,6 +1,6 @@
'use strict';
var build = require('./dep-35df7f96.js');
var build = require('./dep-9ebc60a4.js');
var require$$1 = require('crypto');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
@ -8,11 +8,11 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
function _mergeNamespaces(n, m) {
for (var i = 0; i < m.length; i++) {
var e = m[i];
for (var k in e) {
if (typeof e !== 'string' && !Array.isArray(e)) { for (var k in e) {
if (k !== 'default' && !(k in n)) {
n[k] = e[k];
}
}
} }
}
return n;
}
@ -29179,4 +29179,4 @@ var index = /*#__PURE__*/_mergeNamespaces({
}, [selfsigned]);
exports.index = index;
//# sourceMappingURL=dep-34d2edc0.js.map
//# sourceMappingURL=dep-4e8628d1.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

0
packages/astro/vendor/vite/dist/node/chunks/dep-ac1b4bf9.js vendored Executable file → Normal file
View file

0
packages/astro/vendor/vite/dist/node/chunks/dep-ac1b4bf9.js.map vendored Executable file → Normal file
View file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
export {};

67
packages/astro/vendor/vite/dist/node/cli.js vendored Executable file → Normal file
View file

@ -1,30 +1,31 @@
'use strict';
var require$$0 = require('events');
var build = require('./chunks/dep-35df7f96.js');
var build = require('./chunks/dep-9ebc60a4.js');
var perf_hooks = require('perf_hooks');
require('fs');
require('path');
require('util');
require('stream');
require('os');
require('url');
require('crypto');
require('module');
require('esbuild');
require('worker_threads');
require('assert');
require('child_process');
require('readline');
require('zlib');
require('resolve');
require('querystring');
require('tty');
require('util');
require('net');
require('url');
require('http');
require('buffer');
require('stream');
require('resolve');
require('module');
require('https');
require('zlib');
require('crypto');
require('tls');
require('assert');
require('buffer');
require('querystring');
require('esbuild');
require('child_process');
require('json5');
require('worker_threads');
require('readline');
function toArr(any) {
return any == null ? [] : Array.isArray(any) ? any : [any];
@ -373,7 +374,10 @@ class Command {
body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
});
}
const options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
if (!this.isGlobalCommand && !this.isDefaultCommand) {
options = options.filter((option) => option.name !== "version");
}
if (options.length > 0) {
const longestOptionName = findLongest(options.map((option) => option.rawName));
sections.push({
@ -550,7 +554,7 @@ class CAC extends require$$0.EventEmitter {
run = false;
this.unsetMatchedCommand();
}
if (this.options.version && this.showVersionOnExit) {
if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
this.outputVersion();
run = false;
this.unsetMatchedCommand();
@ -645,8 +649,6 @@ function cleanOptions(options) {
delete ret['--'];
delete ret.c;
delete ret.config;
delete ret.r;
delete ret.root;
delete ret.base;
delete ret.l;
delete ret.logLevel;
@ -661,7 +663,6 @@ function cleanOptions(options) {
}
cli
.option('-c, --config <file>', `[string] use specified config file`)
.option('-r, --root <path>', `[string] use specified root directory`)
.option('--base <path>', `[string] public base path (default: /)`)
.option('-l, --logLevel <level>', `[string] info | warn | error | silent`)
.option('--clearScreen', `[boolean] allow/disable clear screen when logging`)
@ -671,7 +672,8 @@ cli
// dev
cli
.command('[root]') // default command
.alias('serve')
.alias('serve') // the command is called 'serve' in Vite's API
.alias('dev') // alias to align with the script name
.option('--host [host]', `[string] specify hostname`)
.option('--port <port>', `[number] specify port`)
.option('--https', `[boolean] use TLS + HTTP/2`)
@ -682,7 +684,7 @@ cli
.action(async (root, options) => {
// output structure is preserved even after bundling so require()
// is ok here
const { createServer } = await Promise.resolve().then(function () { return require('./chunks/dep-35df7f96.js'); }).then(function (n) { return n.index$1; });
const { createServer } = await Promise.resolve().then(function () { return require('./chunks/dep-9ebc60a4.js'); }).then(function (n) { return n.index$1; });
try {
const server = await createServer({
root,
@ -731,7 +733,7 @@ cli
.option('--emptyOutDir', `[boolean] force empty outDir when it's outside of root`)
.option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
.action(async (root, options) => {
const { build: build$1 } = await Promise.resolve().then(function () { return require('./chunks/dep-35df7f96.js'); }).then(function (n) { return n.build$1; });
const { build: build$1 } = await Promise.resolve().then(function () { return require('./chunks/dep-9ebc60a4.js'); }).then(function (n) { return n.build$1; });
const buildOptions = cleanOptions(options);
try {
await build$1({
@ -754,7 +756,7 @@ cli
.command('optimize [root]')
.option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
.action(async (root, options) => {
const { optimizeDeps } = await Promise.resolve().then(function () { return require('./chunks/dep-35df7f96.js'); }).then(function (n) { return n.index; });
const { optimizeDeps } = await Promise.resolve().then(function () { return require('./chunks/dep-9ebc60a4.js'); }).then(function (n) { return n.index; });
try {
const config = await build.resolveConfig({
root,
@ -773,24 +775,25 @@ cli
.command('preview [root]')
.option('--host [host]', `[string] specify hostname`)
.option('--port <port>', `[number] specify port`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.option('--https', `[boolean] use TLS + HTTP/2`)
.option('--open [path]', `[boolean | string] open browser on startup`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.action(async (root, options) => {
try {
const config = await build.resolveConfig({
const server = await build.preview({
root,
base: options.base,
configFile: options.config,
logLevel: options.logLevel,
server: {
open: options.open,
preview: {
port: options.port,
strictPort: options.strictPort,
https: options.https
host: options.host,
https: options.https,
open: options.open
}
}, 'serve', 'production');
const server = await build.preview(config, cleanOptions(options));
build.printHttpServerUrls(server, config);
});
server.printUrls();
}
catch (e) {
build.createLogger(options.logLevel).error(build.source.red(`error when starting preview server:\n${e.stack}`), { error: e });

2
packages/astro/vendor/vite/dist/node/cli.js.map vendored Executable file → Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,202 @@
import { Plugin } from './plugin';
import { BuildOptions } from './build';
import { ResolvedServerOptions, ServerOptions } from './server';
import { ResolvedPreviewOptions, PreviewOptions } from './preview';
import { CSSOptions } from './plugins/css';
import { ESBuildOptions } from './plugins/esbuild';
import { Alias, AliasOptions } from 'types/alias';
import { InternalResolveOptions, ResolveOptions } from './plugins/resolve';
import { Logger, LogLevel } from './logger';
import { DepOptimizationOptions } from './optimizer';
import { ResolvedBuildOptions } from '.';
import { JsonOptions } from './plugins/json';
import { PackageCache } from './packages';
export interface ConfigEnv {
command: 'build' | 'serve';
mode: string;
}
export declare type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>;
export declare type UserConfigExport = UserConfig | Promise<UserConfig> | UserConfigFn;
/**
* Type helper to make it easier to use vite.config.ts
* accepts a direct {@link UserConfig} object, or a function that returns it.
* The function receives a {@link ConfigEnv} object that exposes two properties:
* `command` (either `'build'` or `'serve'`), and `mode`.
*/
export declare function defineConfig(config: UserConfigExport): UserConfigExport;
export declare type PluginOption = Plugin | false | null | undefined;
export interface UserConfig {
/**
* Project root directory. Can be an absolute path, or a path relative from
* the location of the config file itself.
* @default process.cwd()
*/
root?: string;
/**
* Base public path when served in development or production.
* @default '/'
*/
base?: string;
/**
* Directory to serve as plain static assets. Files in this directory are
* served and copied to build dist dir as-is without transform. The value
* can be either an absolute file system path or a path relative to <root>.
*
* Set to `false` or an empty string to disable copied static assets to build dist dir.
* @default 'public'
*/
publicDir?: string | false;
/**
* Directory to save cache files. Files in this directory are pre-bundled
* deps or some other cache files that generated by vite, which can improve
* the performance. You can use `--force` flag or manually delete the directory
* to regenerate the cache files. The value can be either an absolute file
* system path or a path relative to <root>.
* @default 'node_modules/.vite'
*/
cacheDir?: string;
/**
* Explicitly set a mode to run in. This will override the default mode for
* each command, and can be overridden by the command line --mode option.
*/
mode?: string;
/**
* Define global variable replacements.
* Entries will be defined on `window` during dev and replaced during build.
*/
define?: Record<string, any>;
/**
* Array of vite plugins to use.
*/
plugins?: (PluginOption | PluginOption[])[];
/**
* Configure resolver
*/
resolve?: ResolveOptions & {
alias?: AliasOptions;
};
/**
* CSS related options (preprocessors and CSS modules)
*/
css?: CSSOptions;
/**
* JSON loading options
*/
json?: JsonOptions;
/**
* Transform options to pass to esbuild.
* Or set to `false` to disable esbuild.
*/
esbuild?: ESBuildOptions | false;
/**
* Specify additional picomatch patterns to be treated as static assets.
*/
assetsInclude?: string | RegExp | (string | RegExp)[];
/**
* Server specific options, e.g. host, port, https...
*/
server?: ServerOptions;
/**
* Build specific options
*/
build?: BuildOptions;
/**
* Preview specific options, e.g. host, port, https...
*/
preview?: PreviewOptions;
/**
* Dep optimization options
*/
optimizeDeps?: DepOptimizationOptions;
/**
* SSR specific options
* @alpha
*/
ssr?: SSROptions;
/**
* Log level.
* Default: 'info'
*/
logLevel?: LogLevel;
/**
* Custom logger.
*/
customLogger?: Logger;
/**
* Default: true
*/
clearScreen?: boolean;
/**
* Environment files directory. Can be an absolute path, or a path relative from
* the location of the config file itself.
* @default root
*/
envDir?: string;
/**
* Env variables starts with `envPrefix` will be exposed to your client source code via import.meta.env.
* @default 'VITE_'
*/
envPrefix?: string | string[];
/**
* Import aliases
* @deprecated use `resolve.alias` instead
*/
alias?: AliasOptions;
/**
* Force Vite to always resolve listed dependencies to the same copy (from
* project root).
* @deprecated use `resolve.dedupe` instead
*/
dedupe?: string[];
}
export declare type SSRTarget = 'node' | 'webworker';
export interface SSROptions {
external?: string[];
noExternal?: string | RegExp | (string | RegExp)[] | true;
/**
* Define the target for the ssr build. The browser field in package.json
* is ignored for node but used if webworker is the target
* Default: 'node'
*/
target?: SSRTarget;
}
export interface InlineConfig extends UserConfig {
configFile?: string | false;
envFile?: false;
}
export declare type ResolvedConfig = Readonly<Omit<UserConfig, 'plugins' | 'alias' | 'dedupe' | 'assetsInclude' | 'optimizeDeps'> & {
configFile: string | undefined;
configFileDependencies: string[];
inlineConfig: InlineConfig;
root: string;
base: string;
publicDir: string;
command: 'build' | 'serve';
mode: string;
isProduction: boolean;
env: Record<string, any>;
resolve: ResolveOptions & {
alias: Alias[];
};
plugins: readonly Plugin[];
server: ResolvedServerOptions;
build: ResolvedBuildOptions;
preview: ResolvedPreviewOptions;
assetsInclude: (file: string) => boolean;
logger: Logger;
createResolver: (options?: Partial<InternalResolveOptions>) => ResolveFn;
optimizeDeps: Omit<DepOptimizationOptions, 'keepNames'>;
/** @internal */
packageCache: PackageCache;
}>;
export declare type ResolveFn = (id: string, importer?: string, aliasOnly?: boolean, ssr?: boolean) => Promise<string | undefined>;
export declare function resolveConfig(inlineConfig: InlineConfig, command: 'build' | 'serve', defaultMode?: string): Promise<ResolvedConfig>;
export declare function mergeConfig(a: Record<string, any>, b: Record<string, any>, isRoot?: boolean): Record<string, any>;
export declare function sortUserPlugins(plugins: (Plugin | Plugin[])[] | undefined): [Plugin[], Plugin[], Plugin[]];
export declare function loadConfigFromFile(configEnv: ConfigEnv, configFile?: string, configRoot?: string, logLevel?: LogLevel): Promise<{
path: string;
config: UserConfig;
dependencies: string[];
} | null>;
export declare function loadEnv(mode: string, envDir: string, prefixes?: string | string[]): Record<string, string>;
export declare function resolveEnvPrefix({ envPrefix }: UserConfig): string[];

View file

@ -0,0 +1,33 @@
export declare const DEFAULT_MAIN_FIELDS: string[];
export declare const DEFAULT_EXTENSIONS: string[];
export declare const JS_TYPES_RE: RegExp;
export declare const OPTIMIZABLE_ENTRY_RE: RegExp;
export declare const SPECIAL_QUERY_RE: RegExp;
/**
* Prefix for resolved fs paths, since windows paths may not be valid as URLs.
*/
export declare const FS_PREFIX = "/@fs/";
/**
* Prefix for resolved Ids that are not valid browser import specifiers
*/
export declare const VALID_ID_PREFIX = "/@id/";
/**
* Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
* module ID with `\0`, a convention from the rollup ecosystem.
* This prevents other plugins from trying to process the id (like node resolution),
* and core features like sourcemaps can use this info to differentiate between
* virtual modules and regular files.
* `\0` is not a permitted char in import URLs so we have to replace them during
* import analysis. The id will be decoded back before entering the plugins pipeline.
* These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
* modules in the browser end up encoded as `/@id/__x00__{id}`
*/
export declare const NULL_BYTE_PLACEHOLDER = "__x00__";
export declare const CLIENT_PUBLIC_PATH = "/@vite/client";
export declare const ENV_PUBLIC_PATH = "/@vite/env";
export declare const CLIENT_ENTRY: string;
export declare const ENV_ENTRY: string;
export declare const CLIENT_DIR: string;
export declare const KNOWN_ASSET_TYPES: string[];
export declare const DEFAULT_ASSETS_RE: RegExp;
export declare const DEP_VERSION_RE: RegExp;

View file

@ -0,0 +1,84 @@
/// <reference types="node" />
import { Server as HttpServer } from 'http';
import { ServerOptions as HttpsServerOptions } from 'https';
import { ProxyOptions } from './server/middlewares/proxy';
import { Connect } from 'types/connect';
import { Logger } from './logger';
export interface CommonServerOptions {
/**
* Specify server port. Note if the port is already being used, Vite will
* automatically try the next available port so this may not be the actual
* port the server ends up listening on.
*/
port?: number;
/**
* If enabled, vite will exit if specified port is already in use
*/
strictPort?: boolean;
/**
* Specify which IP addresses the server should listen on.
* Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.
*/
host?: string | boolean;
/**
* Enable TLS + HTTP/2.
* Note: this downgrades to TLS only when the proxy option is also used.
*/
https?: boolean | HttpsServerOptions;
/**
* Open browser window on startup
*/
open?: boolean | string;
/**
* Configure custom proxy rules for the dev server. Expects an object
* of `{ key: options }` pairs.
* Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).
* Full options [here](https://github.com/http-party/node-http-proxy#options).
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* proxy: {
* // string shorthand
* '/foo': 'http://localhost:4567/foo',
* // with options
* '/api': {
* target: 'http://jsonplaceholder.typicode.com',
* changeOrigin: true,
* rewrite: path => path.replace(/^\/api/, '')
* }
* }
* }
* ```
*/
proxy?: Record<string, string | ProxyOptions>;
/**
* Configure CORS for the dev server.
* Uses https://github.com/expressjs/cors.
* Set to `true` to allow all methods from any origin, or configure separately
* using an object.
*/
cors?: CorsOptions | boolean;
}
/**
* https://github.com/expressjs/cors#configuration-options
*/
export interface CorsOptions {
origin?: CorsOrigin | ((origin: string, cb: (err: Error, origins: CorsOrigin) => void) => void);
methods?: string | string[];
allowedHeaders?: string | string[];
exposedHeaders?: string | string[];
credentials?: boolean;
maxAge?: number;
preflightContinue?: boolean;
optionsSuccessStatus?: number;
}
export declare type CorsOrigin = boolean | string | RegExp | (string | RegExp)[];
export declare function resolveHttpServer({ proxy }: CommonServerOptions, app: Connect.Server, httpsOptions?: HttpsServerOptions): Promise<HttpServer>;
export declare function resolveHttpsConfig(https?: boolean | HttpsServerOptions, cacheDir?: string): Promise<HttpsServerOptions | undefined>;
export declare function httpServerStart(httpServer: HttpServer, serverOptions: {
port: number;
strictPort: boolean | undefined;
host: string | undefined;
logger: Logger;
}): Promise<number>;

View file

@ -0,0 +1,14 @@
export interface AssertOptions {
assert?: {
type: string;
};
}
export declare function transformImportGlob(source: string, pos: number, importer: string, importIndex: number, root: string, normalizeUrl?: (url: string, pos: number) => Promise<[string, string]>, preload?: boolean): Promise<{
importsString: string;
imports: string[];
exp: string;
endIndex: number;
isEager: boolean;
pattern: string;
base: string;
}>;

796
packages/astro/vendor/vite/dist/node/index.d.ts vendored Executable file → Normal file

File diff suppressed because it is too large Load diff

35
packages/astro/vendor/vite/dist/node/index.js vendored Executable file → Normal file
View file

@ -2,31 +2,32 @@
Object.defineProperty(exports, '__esModule', { value: true });
var build = require('./chunks/dep-35df7f96.js');
var build = require('./chunks/dep-9ebc60a4.js');
require('fs');
require('path');
require('events');
require('util');
require('stream');
require('os');
require('perf_hooks');
require('url');
require('crypto');
require('module');
require('esbuild');
require('worker_threads');
require('assert');
require('child_process');
require('readline');
require('zlib');
require('resolve');
require('querystring');
require('tty');
require('util');
require('net');
require('events');
require('url');
require('http');
require('buffer');
require('stream');
require('resolve');
require('module');
require('perf_hooks');
require('https');
require('zlib');
require('crypto');
require('tls');
require('assert');
require('buffer');
require('querystring');
require('esbuild');
require('child_process');
require('json5');
require('worker_threads');
require('readline');

2
packages/astro/vendor/vite/dist/node/index.js.map vendored Executable file → Normal file
View file

@ -1 +1 @@
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}

View file

@ -0,0 +1,35 @@
/// <reference types="node" />
import { Server } from 'net';
import { RollupError } from 'rollup';
import { ResolvedConfig } from '.';
import { CommonServerOptions } from './http';
export declare type LogType = 'error' | 'warn' | 'info';
export declare type LogLevel = LogType | 'silent';
export interface Logger {
info(msg: string, options?: LogOptions): void;
warn(msg: string, options?: LogOptions): void;
warnOnce(msg: string, options?: LogOptions): void;
error(msg: string, options?: LogErrorOptions): void;
clearScreen(type: LogType): void;
hasErrorLogged(error: Error | RollupError): boolean;
hasWarned: boolean;
}
export interface LogOptions {
clear?: boolean;
timestamp?: boolean;
}
export interface LogErrorOptions extends LogOptions {
error?: Error | RollupError | null;
}
export declare const LogLevels: Record<LogLevel, number>;
export interface LoggerOptions {
prefix?: string;
allowClearScreen?: boolean;
customLogger?: Logger;
}
export declare function createLogger(level?: LogLevel, options?: LoggerOptions): Logger;
/**
* @deprecated Use `server.printUrls()` instead
*/
export declare function printHttpServerUrls(server: Server, config: ResolvedConfig): void;
export declare function printCommonServerUrls(server: Server, options: CommonServerOptions, config: ResolvedConfig): void;

View file

@ -0,0 +1,4 @@
import { Plugin } from 'esbuild';
import { ResolvedConfig } from '..';
import { ExportsData } from '.';
export declare function esbuildDepPlugin(qualified: Record<string, string>, exportsData: Record<string, ExportsData>, config: ResolvedConfig, ssr?: boolean): Plugin;

View file

@ -0,0 +1,66 @@
import { BuildOptions as EsbuildBuildOptions } from 'esbuild';
import { ResolvedConfig } from '../config';
import { parse } from 'es-module-lexer';
export declare type ExportsData = ReturnType<typeof parse> & {
hasReExports?: true;
};
export interface DepOptimizationOptions {
/**
* By default, Vite will crawl your index.html to detect dependencies that
* need to be pre-bundled. If build.rollupOptions.input is specified, Vite
* will crawl those entry points instead.
*
* If neither of these fit your needs, you can specify custom entries using
* this option - the value should be a fast-glob pattern or array of patterns
* (https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from
* vite project root. This will overwrite default entries inference.
*/
entries?: string | string[];
/**
* Force optimize listed dependencies (must be resolvable import paths,
* cannot be globs).
*/
include?: string[];
/**
* Do not optimize these dependencies (must be resolvable import paths,
* cannot be globs).
*/
exclude?: string[];
/**
* Options to pass to esbuild during the dep scanning and optimization
*
* Certain options are omitted since changing them would not be compatible
* with Vite's dep optimization.
*
* - `external` is also omitted, use Vite's `optimizeDeps.exclude` option
* - `plugins` are merged with Vite's dep plugin
* - `keepNames` takes precedence over the deprecated `optimizeDeps.keepNames`
*
* https://esbuild.github.io/api
*/
esbuildOptions?: Omit<EsbuildBuildOptions, 'bundle' | 'entryPoints' | 'external' | 'write' | 'watch' | 'outdir' | 'outfile' | 'outbase' | 'outExtension' | 'metafile'>;
/**
* @deprecated use `esbuildOptions.keepNames`
*/
keepNames?: boolean;
}
export interface DepOptimizationMetadata {
/**
* The main hash is determined by user config and dependency lockfiles.
* This is checked on server startup to avoid unnecessary re-bundles.
*/
hash: string;
/**
* The browser hash is determined by the main hash plus additional dependencies
* discovered at runtime. This is used to invalidate browser requests to
* optimized deps.
*/
browserHash: string;
optimized: Record<string, {
file: string;
src: string;
needsInterop: boolean;
}>;
}
export declare function optimizeDeps(config: ResolvedConfig, force?: boolean | undefined, asCommand?: boolean, newDeps?: Record<string, string>, // missing imports encountered after server has started
ssr?: boolean): Promise<DepOptimizationMetadata | null>;

View file

@ -0,0 +1,2 @@
import { ViteDevServer } from '..';
export declare function createMissingImporterRegisterFn(server: ViteDevServer): (id: string, resolved: string, ssr?: boolean) => void;

View file

@ -0,0 +1,9 @@
import { ResolvedConfig } from '..';
export declare const importsRE: RegExp;
export declare function scanImports(config: ResolvedConfig): Promise<{
deps: Record<string, string>;
missing: Record<string, string>;
}>;
export declare const scriptRE: RegExp;
export declare const commentRE: RegExp;
export declare function shouldExternalizeDep(resolvedId: string, rawId: string): boolean;

View file

@ -0,0 +1,25 @@
import { ResolvedConfig } from './config';
import { Plugin } from './plugin';
/** Cache for package.json resolution and package.json contents */
export declare type PackageCache = Map<string, PackageData>;
export interface PackageData {
dir: string;
hasSideEffects: (id: string) => boolean | 'no-treeshake';
webResolvedImports: Record<string, string | undefined>;
nodeResolvedImports: Record<string, string | undefined>;
setResolvedCache: (key: string, entry: string, targetWeb: boolean) => void;
getResolvedCache: (key: string, targetWeb: boolean) => string | undefined;
data: {
[field: string]: any;
version: string;
main: string;
module: string;
browser: string | Record<string, string | false>;
exports: string | Record<string, any> | string[];
dependencies: Record<string, string>;
};
}
export declare function invalidatePackageData(packageCache: PackageCache, pkgPath: string): void;
export declare function resolvePackageData(id: string, basedir: string, preserveSymlinks?: boolean, packageCache?: PackageCache): PackageData | null;
export declare function loadPackageData(pkgPath: string, preserveSymlinks?: boolean, packageCache?: PackageCache): PackageData;
export declare function watchPackageDataPlugin(config: ResolvedConfig): Plugin;

View file

@ -0,0 +1,115 @@
import { UserConfig } from './config';
import { CustomPluginOptions, LoadResult, Plugin as RollupPlugin, PluginContext, ResolveIdResult, TransformPluginContext, TransformResult } from 'rollup';
import { ServerHook } from './server';
import { IndexHtmlTransform } from './plugins/html';
import { ModuleNode } from './server/moduleGraph';
import { ConfigEnv, ResolvedConfig } from './';
import { HmrContext } from './server/hmr';
/**
* Vite plugins extends the Rollup plugin interface with a few extra
* vite-specific options. A valid vite plugin is also a valid Rollup plugin.
* On the contrary, a Rollup plugin may or may NOT be a valid vite universal
* plugin, since some Rollup features do not make sense in an unbundled
* dev server context. That said, as long as a rollup plugin doesn't have strong
* coupling between its bundle phase and output phase hooks then it should
* just work (that means, most of them).
*
* By default, the plugins are run during both serve and build. When a plugin
* is applied during serve, it will only run **non output plugin hooks** (see
* rollup type definition of {@link rollup#PluginHooks}). You can think of the
* dev server as only running `const bundle = rollup.rollup()` but never calling
* `bundle.generate()`.
*
* A plugin that expects to have different behavior depending on serve/build can
* export a factory function that receives the command being run via options.
*
* If a plugin should be applied only for server or build, a function format
* config file can be used to conditional determine the plugins to use.
*/
export interface Plugin extends RollupPlugin {
/**
* Enforce plugin invocation tier similar to webpack loaders.
*
* Plugin invocation order:
* - alias resolution
* - `enforce: 'pre'` plugins
* - vite core plugins
* - normal plugins
* - vite build plugins
* - `enforce: 'post'` plugins
* - vite build post plugins
*/
enforce?: 'pre' | 'post';
/**
* Apply the plugin only for serve or build, or on certain conditions.
*/
apply?: 'serve' | 'build' | ((config: UserConfig, env: ConfigEnv) => boolean);
/**
* Modify vite config before it's resolved. The hook can either mutate the
* passed-in config directly, or return a partial config object that will be
* deeply merged into existing config.
*
* Note: User plugins are resolved before running this hook so injecting other
* plugins inside the `config` hook will have no effect.
*/
config?: (config: UserConfig, env: ConfigEnv) => UserConfig | null | void | Promise<UserConfig | null | void>;
/**
* Use this hook to read and store the final resolved vite config.
*/
configResolved?: (config: ResolvedConfig) => void | Promise<void>;
/**
* Configure the vite server. The hook receives the {@link ViteDevServer}
* instance. This can also be used to store a reference to the server
* for use in other hooks.
*
* The hooks will be called before internal middlewares are applied. A hook
* can return a post hook that will be called after internal middlewares
* are applied. Hook can be async functions and will be called in series.
*/
configureServer?: ServerHook;
/**
* Transform index.html.
* The hook receives the following arguments:
*
* - html: string
* - ctx?: vite.ServerContext (only present during serve)
* - bundle?: rollup.OutputBundle (only present during build)
*
* It can either return a transformed string, or a list of html tag
* descriptors that will be injected into the <head> or <body>.
*
* By default the transform is applied **after** vite's internal html
* transform. If you need to apply the transform before vite, use an object:
* `{ enforce: 'pre', transform: hook }`
*/
transformIndexHtml?: IndexHtmlTransform;
/**
* Perform custom handling of HMR updates.
* The handler receives a context containing changed filename, timestamp, a
* list of modules affected by the file change, and the dev server instance.
*
* - The hook can return a filtered list of modules to narrow down the update.
* e.g. for a Vue SFC, we can narrow down the part to update by comparing
* the descriptors.
*
* - The hook can also return an empty array and then perform custom updates
* by sending a custom hmr payload via server.ws.send().
*
* - If the hook doesn't return a value, the hmr update will be performed as
* normal.
*/
handleHotUpdate?(ctx: HmrContext): Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>;
/**
* extend hooks with ssr flag
*/
resolveId?(this: PluginContext, source: string, importer: string | undefined, options: {
custom?: CustomPluginOptions;
ssr?: boolean;
}): Promise<ResolveIdResult> | ResolveIdResult;
load?(this: PluginContext, id: string, options?: {
ssr?: boolean;
}): Promise<LoadResult> | LoadResult;
transform?(this: TransformPluginContext, code: string, id: string, options?: {
ssr?: boolean;
}): Promise<TransformResult> | TransformResult;
}

View file

@ -0,0 +1,40 @@
/// <reference types="node" />
import { Plugin } from '../plugin';
import { ResolvedConfig } from '../config';
import { OutputOptions, PluginContext, RenderedChunk } from 'rollup';
export declare const assetUrlRE: RegExp;
export declare const chunkToEmittedAssetsMap: WeakMap<RenderedChunk, Set<string>>;
/**
* Also supports loading plain strings with import text from './foo.txt?raw'
*/
export declare function assetPlugin(config: ResolvedConfig): Plugin;
export declare function registerAssetToChunk(chunk: RenderedChunk, file: string): void;
export declare function checkPublicFile(url: string, { publicDir }: ResolvedConfig): string | undefined;
export declare function fileToUrl(id: string, config: ResolvedConfig, ctx: PluginContext): string | Promise<string>;
export declare function getAssetFilename(hash: string, config: ResolvedConfig): string | undefined;
/**
* converts the source filepath of the asset to the output filename based on the assetFileNames option. \
* this function imitates the behavior of rollup.js. \
* https://rollupjs.org/guide/en/#outputassetfilenames
*
* @example
* ```ts
* const content = Buffer.from('text');
* const fileName = assetFileNamesToFileName(
* 'assets/[name].[hash][extname]',
* '/path/to/file.txt',
* getAssetHash(content),
* content
* )
* // fileName: 'assets/file.982d9e3e.txt'
* ```
*
* @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'`
* @param file filepath of the asset
* @param contentHash hash of the asset. used for `'[hash]'` placeholder
* @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function
* @returns output filename
*/
export declare function assetFileNamesToFileName(assetFileNames: Exclude<OutputOptions['assetFileNames'], undefined>, file: string, contentHash: string, content: string | Buffer): string;
export declare function getAssetHash(content: Buffer): string;
export declare function urlToBuiltUrl(url: string, importer: string, config: ResolvedConfig, pluginContext: PluginContext): Promise<string>;

View file

@ -0,0 +1,13 @@
import { Plugin } from '../plugin';
import { ResolvedConfig } from '../config';
/**
* Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL
*
* Supports template string with dynamic segments:
* ```
* new URL(`./dir/${name}.png`, import.meta.url)
* // transformed to
* import.meta.globEager('./dir/**.png')[`./dir/${name}.png`].default
* ```
*/
export declare function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin;

View file

@ -0,0 +1,7 @@
import { Plugin } from '../plugin';
import { ResolvedConfig } from '../config';
/**
* some values used by the client needs to be dynamically injected by the server
* @server-only
*/
export declare function clientInjectionsPlugin(config: ResolvedConfig): Plugin;

View file

@ -0,0 +1,72 @@
import { Plugin } from '../plugin';
import { ResolvedConfig } from '../config';
import { RenderedChunk, RollupError } from 'rollup';
import { ResolveFn } from '../';
import * as Postcss from 'postcss';
import { Alias } from 'types/alias';
export interface CSSOptions {
/**
* https://github.com/css-modules/postcss-modules
*/
modules?: CSSModulesOptions | false;
preprocessorOptions?: Record<string, any>;
postcss?: string | (Postcss.ProcessOptions & {
plugins?: Postcss.Plugin[];
});
}
export interface CSSModulesOptions {
getJSON?: (cssFileName: string, json: Record<string, string>, outputFileName: string) => void;
scopeBehaviour?: 'global' | 'local';
globalModulePaths?: RegExp[];
generateScopedName?: string | ((name: string, filename: string, css: string) => string);
hashPrefix?: string;
/**
* default: null
*/
localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | null;
}
export declare const isCSSRequest: (request: string) => boolean;
export declare const isDirectCSSRequest: (request: string) => boolean;
export declare const isDirectRequest: (request: string) => boolean;
export declare const chunkToEmittedCssFileMap: WeakMap<RenderedChunk, Set<string>>;
export declare const removedPureCssFilesCache: WeakMap<Readonly<Omit<import("../config").UserConfig, "plugins" | "alias" | "dedupe" | "assetsInclude" | "optimizeDeps"> & {
configFile: string | undefined;
configFileDependencies: string[];
inlineConfig: import("../config").InlineConfig;
root: string;
base: string;
publicDir: string;
command: "build" | "serve";
mode: string;
isProduction: boolean;
env: Record<string, any>;
resolve: import("./resolve").ResolveOptions & {
alias: Alias[];
};
plugins: readonly Plugin[];
server: import("../server").ResolvedServerOptions;
build: Required<Omit<import("../build").BuildOptions, "base" | "cleanCssOptions" | "polyfillDynamicImport" | "brotliSize">>;
preview: import("../preview").ResolvedPreviewOptions;
assetsInclude: (file: string) => boolean; /**
* Plugin applied after user plugins
*/
logger: import("../logger").Logger;
createResolver: (options?: Partial<import("./resolve").InternalResolveOptions> | undefined) => ResolveFn;
optimizeDeps: Omit<import("../optimizer").DepOptimizationOptions, "keepNames">;
packageCache: import("../packages").PackageCache;
}>, Map<string, RenderedChunk>>;
/**
* Plugin applied before user plugins
*/
export declare function cssPlugin(config: ResolvedConfig): Plugin;
/**
* Plugin applied after user plugins
*/
export declare function cssPostPlugin(config: ResolvedConfig): Plugin;
export declare const cssUrlRE: RegExp;
export interface StylePreprocessorResults {
code: string;
map?: object;
errors: RollupError[];
deps: string[];
}

View file

@ -0,0 +1,5 @@
import { Plugin } from '../plugin';
/**
* Build only, since importing from a data URI works natively.
*/
export declare function dataURIPlugin(): Plugin;

View file

@ -0,0 +1,3 @@
import { ResolvedConfig } from '../config';
import { Plugin } from '../plugin';
export declare function definePlugin(config: ResolvedConfig): Plugin;

View file

@ -0,0 +1,15 @@
import { Plugin } from '../plugin';
import { TransformOptions, TransformResult } from 'esbuild';
import { SourceMap } from 'rollup';
import { ResolvedConfig } from '..';
export interface ESBuildOptions extends TransformOptions {
include?: string | RegExp | string[] | RegExp[];
exclude?: string | RegExp | string[] | RegExp[];
jsxInject?: string;
}
export declare type ESBuildTransformResult = Omit<TransformResult, 'map'> & {
map: SourceMap;
};
export declare function transformWithEsbuild(code: string, filename: string, options?: TransformOptions, inMap?: object): Promise<ESBuildTransformResult>;
export declare function esbuildPlugin(options?: ESBuildOptions): Plugin;
export declare const buildEsbuildPlugin: (config: ResolvedConfig) => Plugin;

View file

@ -0,0 +1,102 @@
import { Plugin } from '../plugin';
import { ViteDevServer } from '../server';
import { OutputBundle, OutputChunk } from 'rollup';
import { ResolvedConfig } from '../config';
import { AttributeNode, NodeTransform, ElementNode } from '@vue/compiler-dom';
export declare const isHTMLProxy: (id: string) => boolean;
export declare const htmlProxyMap: WeakMap<Readonly<Omit<import("../config").UserConfig, "plugins" | "alias" | "dedupe" | "assetsInclude" | "optimizeDeps"> & {
configFile: string | undefined;
configFileDependencies: string[];
inlineConfig: import("../config").InlineConfig;
root: string;
base: string;
publicDir: string;
command: "build" | "serve";
mode: string;
isProduction: boolean;
env: Record<string, any>;
resolve: import("./resolve").ResolveOptions & {
alias: import("types/alias").Alias[];
};
plugins: readonly Plugin[];
server: import("../server").ResolvedServerOptions;
build: Required<Omit<import("..").BuildOptions, "base" | "cleanCssOptions" | "polyfillDynamicImport" | "brotliSize">>;
preview: import("..").ResolvedPreviewOptions;
assetsInclude: (file: string) => boolean;
logger: import("..").Logger;
createResolver: (options?: Partial<import("./resolve").InternalResolveOptions> | undefined) => import("../config").ResolveFn;
optimizeDeps: Omit<import("..").DepOptimizationOptions, "keepNames">;
packageCache: import("..").PackageCache;
}>, Map<string, string[]>>;
export declare function htmlInlineScriptProxyPlugin(config: ResolvedConfig): Plugin;
/** Add script to cache */
export declare function addToHTMLProxyCache(config: ResolvedConfig, filePath: string, index: number, code: string): void;
export declare const assetAttrsConfig: Record<string, string[]>;
export declare const isAsyncScriptMap: WeakMap<Readonly<Omit<import("../config").UserConfig, "plugins" | "alias" | "dedupe" | "assetsInclude" | "optimizeDeps"> & {
configFile: string | undefined;
configFileDependencies: string[];
inlineConfig: import("../config").InlineConfig;
root: string;
base: string;
publicDir: string;
command: "build" | "serve";
mode: string;
isProduction: boolean;
env: Record<string, any>;
resolve: import("./resolve").ResolveOptions & {
alias: import("types/alias").Alias[];
};
plugins: readonly Plugin[];
server: import("../server").ResolvedServerOptions;
build: Required<Omit<import("..").BuildOptions, "base" | "cleanCssOptions" | "polyfillDynamicImport" | "brotliSize">>;
preview: import("..").ResolvedPreviewOptions;
assetsInclude: (file: string) => boolean;
logger: import("..").Logger;
createResolver: (options?: Partial<import("./resolve").InternalResolveOptions> | undefined) => import("../config").ResolveFn;
optimizeDeps: Omit<import("..").DepOptimizationOptions, "keepNames">;
packageCache: import("..").PackageCache;
}>, Map<string, boolean>>;
export declare function traverseHtml(html: string, filePath: string, visitor: NodeTransform): Promise<void>;
export declare function getScriptInfo(node: ElementNode): {
src: AttributeNode | undefined;
isModule: boolean;
isAsync: boolean;
};
/**
* Compiles index.html into an entry js module
*/
export declare function buildHtmlPlugin(config: ResolvedConfig): Plugin;
export interface HtmlTagDescriptor {
tag: string;
attrs?: Record<string, string | boolean | undefined>;
children?: string | HtmlTagDescriptor[];
/**
* default: 'head-prepend'
*/
injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend';
}
export declare type IndexHtmlTransformResult = string | HtmlTagDescriptor[] | {
html: string;
tags: HtmlTagDescriptor[];
};
export interface IndexHtmlTransformContext {
/**
* public path when served
*/
path: string;
/**
* filename on disk
*/
filename: string;
server?: ViteDevServer;
bundle?: OutputBundle;
chunk?: OutputChunk;
originalUrl?: string;
}
export declare type IndexHtmlTransformHook = (html: string, ctx: IndexHtmlTransformContext) => IndexHtmlTransformResult | void | Promise<IndexHtmlTransformResult | void>;
export declare type IndexHtmlTransform = IndexHtmlTransformHook | {
enforce?: 'pre' | 'post';
transform: IndexHtmlTransformHook;
};
export declare function resolveHtmlTransforms(plugins: readonly Plugin[]): [IndexHtmlTransformHook[], IndexHtmlTransformHook[]];
export declare function applyHtmlTransforms(html: string, hooks: IndexHtmlTransformHook[], ctx: IndexHtmlTransformContext): Promise<string>;

View file

@ -0,0 +1,46 @@
import { Plugin } from '../plugin';
import { ResolvedConfig } from '../config';
/**
* Server-only plugin that lexes, resolves, rewrites and analyzes url imports.
*
* - Imports are resolved to ensure they exist on disk
*
* - Lexes HMR accept calls and updates import relationships in the module graph
*
* - Bare module imports are resolved (by @rollup-plugin/node-resolve) to
* absolute file paths, e.g.
*
* ```js
* import 'foo'
* ```
* is rewritten to
* ```js
* import '/@fs//project/node_modules/foo/dist/foo.js'
* ```
*
* - CSS imports are appended with `.js` since both the js module and the actual
* css (referenced via <link>) may go through the transform pipeline:
*
* ```js
* import './style.css'
* ```
* is rewritten to
* ```js
* import './style.css.js'
* ```
*/
export declare function importAnalysisPlugin(config: ResolvedConfig): Plugin;
/**
* Detect import statements to a known optimized CJS dependency and provide
* ES named imports interop. We do this by rewriting named imports to a variable
* assignment to the corresponding property on the `module.exports` of the cjs
* module. Note this doesn't support dynamic re-assignments from within the cjs
* module.
*
* Note that es-module-lexer treats `export * from '...'` as an import as well,
* so, we may encounter ExportAllDeclaration here, in which case `undefined`
* will be returned.
*
* Credits \@csr632 via #837
*/
export declare function transformCjsImport(importExp: string, url: string, rawUrl: string, importIndex: number): string | undefined;

View file

@ -0,0 +1,15 @@
import { ResolvedConfig } from '../config';
import { Plugin } from '../plugin';
/**
* A flag for injected helpers. This flag will be set to `false` if the output
* target is not native es - so that injected helper logic can be conditionally
* dropped.
*/
export declare const isModernFlag = "__VITE_IS_MODERN__";
export declare const preloadMethod = "__vitePreload";
export declare const preloadMarker = "__VITE_PRELOAD__";
export declare const preloadBaseMarker = "__VITE_PRELOAD_BASE__";
/**
* Build only. During serve this is performed as part of ./importAnalysis.
*/
export declare function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin;

View file

@ -0,0 +1,3 @@
import { ResolvedConfig } from '../config';
import { Plugin } from '../plugin';
export declare function resolvePlugins(config: ResolvedConfig, prePlugins: Plugin[], normalPlugins: Plugin[], postPlugins: Plugin[]): Promise<Plugin[]>;

View file

@ -0,0 +1,22 @@
/**
* https://github.com/rollup/plugins/blob/master/packages/json/src/index.js
*
* This source code is licensed under the MIT license found in the
* LICENSE file at
* https://github.com/rollup/plugins/blob/master/LICENSE
*/
import { Plugin } from 'rollup';
export interface JsonOptions {
/**
* Generate a named export for every property of the JSON object
* @default true
*/
namedExports?: boolean;
/**
* Generate performant output as JSON.parse("stringified").
* Enabling this will disable namedExports.
* @default false
*/
stringify?: boolean;
}
export declare function jsonPlugin(options: JsonOptions | undefined, isBuild: boolean): Plugin;

View file

@ -0,0 +1,5 @@
import { Plugin } from '..';
/**
* A plugin to provide build load fallback for arbitrary request with queries.
*/
export declare function loadFallbackPlugin(): Plugin;

View file

@ -0,0 +1,14 @@
import { ResolvedConfig } from '..';
import { Plugin } from '../plugin';
export declare type Manifest = Record<string, ManifestChunk>;
export interface ManifestChunk {
src?: string;
file: string;
css?: string[];
assets?: string[];
isEntry?: boolean;
isDynamicEntry?: boolean;
imports?: string[];
dynamicImports?: string[];
}
export declare function manifestPlugin(config: ResolvedConfig): Plugin;

View file

@ -0,0 +1,4 @@
import { ResolvedConfig } from '..';
import { Plugin } from '../plugin';
export declare const modulePreloadPolyfillId = "vite/modulepreload-polyfill";
export declare function modulePreloadPolyfillPlugin(config: ResolvedConfig): Plugin;

View file

@ -0,0 +1,5 @@
import { Plugin } from '../plugin';
/**
* A plugin to avoid an aliased AND optimized dep from being aliased in src
*/
export declare function preAliasPlugin(): Plugin;

View file

@ -0,0 +1,3 @@
import { Plugin } from 'rollup';
import { ResolvedConfig } from '../config';
export declare function buildReporterPlugin(config: ResolvedConfig): Plugin;

View file

@ -0,0 +1,38 @@
import { Plugin } from '../plugin';
import { ViteDevServer, SSROptions } from '..';
import { PartialResolvedId } from 'rollup';
import { PackageCache, PackageData } from '../packages';
export declare const browserExternalId = "__vite-browser-external";
export interface ResolveOptions {
mainFields?: string[];
conditions?: string[];
extensions?: string[];
dedupe?: string[];
preserveSymlinks?: boolean;
}
export interface InternalResolveOptions extends ResolveOptions {
root: string;
isBuild: boolean;
isProduction: boolean;
ssrConfig?: SSROptions;
packageCache?: PackageCache;
/**
* src code mode also attempts the following:
* - resolving /xxx as URLs
* - resolving bare imports from optimized deps
*/
asSrc?: boolean;
tryIndex?: boolean;
tryPrefix?: string;
skipPackageJson?: boolean;
preferRelative?: boolean;
preserveSymlinks?: boolean;
isRequire?: boolean;
isFromTsImporter?: boolean;
tryEsmOnly?: boolean;
}
export declare function resolvePlugin(baseOptions: InternalResolveOptions): Plugin;
export declare const idToPkgMap: Map<string, PackageData>;
export declare function tryNodeResolve(id: string, importer: string | null | undefined, options: InternalResolveOptions, targetWeb: boolean, server?: ViteDevServer, ssr?: boolean): PartialResolvedId | undefined;
export declare function tryOptimizedResolve(id: string, server: ViteDevServer, importer?: string): string | undefined;
export declare function resolvePackageEntry(id: string, { dir, data, setResolvedCache, getResolvedCache }: PackageData, targetWeb: boolean, options: InternalResolveOptions): string | undefined;

View file

@ -0,0 +1,12 @@
/// <reference types="node" />
import { ResolvedConfig } from '..';
import { Plugin } from '../plugin';
/**
* This plugin hooks into Node's module resolution algorithm at runtime,
* so that SSR builds can benefit from `resolve.dedupe` like they do
* in development.
*/
export declare function ssrRequireHookPlugin(config: ResolvedConfig): Plugin | null;
declare type NodeResolveFilename = (request: string, parent: NodeModule, isMain: boolean, options?: Record<string, any>) => string;
export declare function hookNodeResolve(getResolver: (resolveFilename: NodeResolveFilename) => NodeResolveFilename): () => void;
export {};

View file

@ -0,0 +1,3 @@
import { Plugin } from '../plugin';
import { ResolvedConfig } from '..';
export declare function terserPlugin(config: ResolvedConfig): Plugin;

View file

@ -0,0 +1,3 @@
import { ResolvedConfig } from '../config';
import { Plugin } from '../plugin';
export declare const wasmPlugin: (config: ResolvedConfig) => Plugin;

View file

@ -0,0 +1,3 @@
import { ResolvedConfig } from '../config';
import { Plugin } from '../plugin';
export declare function webWorkerPlugin(config: ResolvedConfig): Plugin;

View file

@ -0,0 +1,31 @@
/// <reference types="node" />
import { Server } from 'http';
import { InlineConfig, ResolvedConfig } from '.';
import { ResolvedServerOptions } from './server';
import { CommonServerOptions } from './http';
export interface PreviewOptions extends CommonServerOptions {
}
export interface ResolvedPreviewOptions extends PreviewOptions {
}
export declare function resolvePreviewOptions(preview: PreviewOptions | undefined, server: ResolvedServerOptions): ResolvedPreviewOptions;
export interface PreviewServer {
/**
* The resolved vite config object
*/
config: ResolvedConfig;
/**
* native Node http server instance
*/
httpServer: Server;
/**
* Print server urls
*/
printUrls: () => void;
}
/**
* Starts the Vite server in preview mode, to simulate a production deployment
* @param config - the resolved Vite config
* @param serverOptions - what host and port to use
* @experimental
*/
export declare function preview(inlineConfig: InlineConfig): Promise<PreviewServer>;

View file

@ -0,0 +1,37 @@
/// <reference types="node" />
import { ViteDevServer } from '..';
import { ModuleNode } from './moduleGraph';
import { Server } from 'http';
export declare const debugHmr: (...args: any[]) => any;
export interface HmrOptions {
protocol?: string;
host?: string;
port?: number;
clientPort?: number;
path?: string;
timeout?: number;
overlay?: boolean;
server?: Server;
}
export interface HmrContext {
file: string;
timestamp: number;
modules: Array<ModuleNode>;
read: () => string | Promise<string>;
server: ViteDevServer;
}
export declare function handleHMRUpdate(file: string, server: ViteDevServer): Promise<any>;
export declare function handleFileAddUnlink(file: string, server: ViteDevServer, isUnlink?: boolean): Promise<void>;
export declare function handlePrunedModules(mods: Set<ModuleNode>, { ws }: ViteDevServer): void;
/**
* Lex import.meta.hot.accept() for accepted deps.
* Since hot.accept() can only accept string literals or array of string
* literals, we don't really need a heavy @babel/parse call on the entire source.
*
* @returns selfAccepts
*/
export declare function lexAcceptedHmrDeps(code: string, start: number, urls: Set<{
url: string;
start: number;
end: number;
}>): boolean;

View file

@ -0,0 +1,214 @@
/// <reference types="node" />
import * as http from 'http';
import { CommonServerOptions } from '../http';
import { InlineConfig, ResolvedConfig } from '../config';
import { PluginContainer } from './pluginContainer';
import { FSWatcher, WatchOptions } from 'types/chokidar';
import { WebSocketServer } from './ws';
import { ModuleGraph, ModuleNode } from './moduleGraph';
import { Connect } from 'types/connect';
import { HmrOptions } from './hmr';
import { TransformOptions, TransformResult } from './transformRequest';
import { ESBuildTransformResult } from '../plugins/esbuild';
import { TransformOptions as EsbuildTransformOptions } from 'esbuild';
import { DepOptimizationMetadata } from '../optimizer';
import { SourceMap } from 'rollup';
export { searchForWorkspaceRoot } from './searchRoot';
export interface ServerOptions extends CommonServerOptions {
/**
* Force dep pre-optimization regardless of whether deps have changed.
*/
force?: boolean;
/**
* Configure HMR-specific options (port, host, path & protocol)
*/
hmr?: HmrOptions | boolean;
/**
* chokidar watch options
* https://github.com/paulmillr/chokidar#api
*/
watch?: WatchOptions;
/**
* Create Vite dev server to be used as a middleware in an existing server
*/
middlewareMode?: boolean | 'html' | 'ssr';
/**
* Prepend this folder to http requests, for use when proxying vite as a subfolder
* Should start and end with the `/` character
*/
base?: string;
/**
* Options for files served via '/\@fs/'.
*/
fs?: FileSystemServeOptions;
/**
* Origin for the generated asset URLs.
*/
origin?: string;
}
export interface ResolvedServerOptions extends ServerOptions {
fs: Required<FileSystemServeOptions>;
}
export interface FileSystemServeOptions {
/**
* Strictly restrict file accessing outside of allowing paths.
*
* Set to `false` to disable the warning
*
* @default true
*/
strict?: boolean;
/**
* Restrict accessing files outside the allowed directories.
*
* Accepts absolute path or a path relative to project root.
* Will try to search up for workspace root by default.
*/
allow?: string[];
/**
* Restrict accessing files that matches the patterns.
*
* This will have higher priority than `allow`.
* Glob patterns are supported.
*
* @default ['.env', '.env.*', '*.crt', '*.pem']
*
* @experimental
*/
deny?: string[];
}
export declare type ServerHook = (server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>;
export interface ViteDevServer {
/**
* The resolved vite config object
*/
config: ResolvedConfig;
/**
* A connect app instance.
* - Can be used to attach custom middlewares to the dev server.
* - Can also be used as the handler function of a custom http server
* or as a middleware in any connect-style Node.js frameworks
*
* https://github.com/senchalabs/connect#use-middleware
*/
middlewares: Connect.Server;
/**
* @deprecated use `server.middlewares` instead
*/
app: Connect.Server;
/**
* native Node http server instance
* will be null in middleware mode
*/
httpServer: http.Server | null;
/**
* chokidar watcher instance
* https://github.com/paulmillr/chokidar#api
*/
watcher: FSWatcher;
/**
* web socket server with `send(payload)` method
*/
ws: WebSocketServer;
/**
* Rollup plugin container that can run plugin hooks on a given file
*/
pluginContainer: PluginContainer;
/**
* Module graph that tracks the import relationships, url to file mapping
* and hmr state.
*/
moduleGraph: ModuleGraph;
/**
* Programmatically resolve, load and transform a URL and get the result
* without going through the http request pipeline.
*/
transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null>;
/**
* Apply vite built-in HTML transforms and any plugin HTML transforms.
*/
transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string>;
/**
* Util for transforming a file with esbuild.
* Can be useful for certain plugins.
*
* @deprecated import `transformWithEsbuild` from `vite` instead
*/
transformWithEsbuild(code: string, filename: string, options?: EsbuildTransformOptions, inMap?: object): Promise<ESBuildTransformResult>;
/**
* Transform module code into SSR format.
* @experimental
*/
ssrTransform(code: string, inMap: SourceMap | null, url: string): Promise<TransformResult | null>;
/**
* Load a given URL as an instantiated module for SSR.
*/
ssrLoadModule(url: string): Promise<Record<string, any>>;
/**
* Fix ssr error stacktrace
*/
ssrFixStacktrace(e: Error): void;
/**
* Start the server.
*/
listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>;
/**
* Stop the server.
*/
close(): Promise<void>;
/**
* Print server urls
*/
printUrls(): void;
/**
* Restart the server.
*
* @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
*/
restart(forceOptimize?: boolean): Promise<void>;
/**
* @internal
*/
_optimizeDepsMetadata: DepOptimizationMetadata | null;
/**
* Deps that are externalized
* @internal
*/
_ssrExternals: string[] | null;
/**
* @internal
*/
_globImporters: Record<string, {
module: ModuleNode;
importGlobs: {
base: string;
pattern: string;
}[];
}>;
/**
* @internal
*/
_restartPromise: Promise<void> | null;
/**
* @internal
*/
_forceOptimizeOnRestart: boolean;
/**
* @internal
*/
_isRunningOptimizer: boolean;
/**
* @internal
*/
_registerMissingImport: ((id: string, resolved: string, ssr: boolean | undefined) => void) | null;
/**
* @internal
*/
_pendingReload: Promise<void> | null;
/**
* @internal
*/
_pendingRequests: Map<string, Promise<TransformResult | null>>;
}
export declare function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>;
export declare function resolveServerOptions(root: string, raw?: ServerOptions): ResolvedServerOptions;

View file

@ -0,0 +1,3 @@
import { ViteDevServer } from '..';
import { Connect } from 'types/connect';
export declare function baseMiddleware({ config }: ViteDevServer): Connect.NextHandleFunction;

View file

@ -0,0 +1,8 @@
import { RollupError } from 'rollup';
import { ViteDevServer } from '../..';
import { Connect } from 'types/connect';
import { ErrorPayload } from 'types/hmrPayload';
export declare function prepareError(err: Error | RollupError): ErrorPayload['err'];
export declare function buildErrorMessage(err: RollupError, args?: string[], includeStack?: boolean): string;
export declare function logError(server: ViteDevServer, err: RollupError): void;
export declare function errorMiddleware(server: ViteDevServer, allowNext?: boolean): Connect.ErrorHandleFunction;

View file

@ -0,0 +1,4 @@
import { Connect } from 'types/connect';
import { ViteDevServer } from '../..';
export declare function createDevHtmlTransformFn(server: ViteDevServer): (url: string, html: string, originalUrl: string) => Promise<string>;
export declare function indexHtmlMiddleware(server: ViteDevServer): Connect.NextHandleFunction;

View file

@ -0,0 +1,20 @@
/// <reference types="node" />
import * as http from 'http';
import { Connect } from 'types/connect';
import { HttpProxy } from 'types/http-proxy';
import { ResolvedConfig } from '../..';
export interface ProxyOptions extends HttpProxy.ServerOptions {
/**
* rewrite path
*/
rewrite?: (path: string) => string;
/**
* configure the proxy server (e.g. listen to events)
*/
configure?: (proxy: HttpProxy.Server, options: ProxyOptions) => void;
/**
* webpack-dev-server style bypass function
*/
bypass?: (req: http.IncomingMessage, res: http.ServerResponse, options: ProxyOptions) => void | null | undefined | false | string;
}
export declare function proxyMiddleware(httpServer: http.Server | null, config: ResolvedConfig): Connect.NextHandleFunction;

View file

@ -0,0 +1,2 @@
import { Connect } from 'types/connect';
export declare function spaFallbackMiddleware(root: string): Connect.NextHandleFunction;

View file

@ -0,0 +1,6 @@
import { Connect } from 'types/connect';
import { ViteDevServer } from '../..';
export declare function servePublicMiddleware(dir: string): Connect.NextHandleFunction;
export declare function serveStaticMiddleware(dir: string, server: ViteDevServer): Connect.NextHandleFunction;
export declare function serveRawFsMiddleware(server: ViteDevServer): Connect.NextHandleFunction;
export declare function isFileServingAllowed(url: string, server: ViteDevServer): boolean;

View file

@ -0,0 +1,2 @@
import { Connect } from 'types/connect';
export declare function timeMiddleware(root: string): Connect.NextHandleFunction;

View file

@ -0,0 +1,3 @@
import { ViteDevServer } from '..';
import { Connect } from 'types/connect';
export declare function transformMiddleware(server: ViteDevServer): Connect.NextHandleFunction;

View file

@ -0,0 +1,53 @@
import { ModuleInfo, PartialResolvedId } from 'rollup';
import { TransformResult } from './transformRequest';
export declare class ModuleNode {
/**
* Public served url path, starts with /
*/
url: string;
/**
* Resolved file system path + query
*/
id: string | null;
file: string | null;
type: 'js' | 'css';
info?: ModuleInfo;
meta?: Record<string, any>;
importers: Set<ModuleNode>;
importedModules: Set<ModuleNode>;
acceptedHmrDeps: Set<ModuleNode>;
isSelfAccepting: boolean;
transformResult: TransformResult | null;
ssrTransformResult: TransformResult | null;
ssrModule: Record<string, any> | null;
lastHMRTimestamp: number;
constructor(url: string);
}
export declare type ResolvedUrl = [
url: string,
resolvedId: string,
meta: object | null | undefined
];
export declare class ModuleGraph {
private resolveId;
urlToModuleMap: Map<string, ModuleNode>;
idToModuleMap: Map<string, ModuleNode>;
fileToModulesMap: Map<string, Set<ModuleNode>>;
safeModulesPath: Set<string>;
constructor(resolveId: (url: string) => Promise<PartialResolvedId | null>);
getModuleByUrl(rawUrl: string): Promise<ModuleNode | undefined>;
getModuleById(id: string): ModuleNode | undefined;
getModulesByFile(file: string): Set<ModuleNode> | undefined;
onFileChange(file: string): void;
invalidateModule(mod: ModuleNode, seen?: Set<ModuleNode>): void;
invalidateAll(): void;
/**
* Update the module graph based on a module's updated imports information
* If there are dependencies that no longer have any importers, they are
* returned as a Set.
*/
updateModuleInfo(mod: ModuleNode, importedModules: Set<string | ModuleNode>, acceptedModules: Set<string | ModuleNode>, isSelfAccepting: boolean): Promise<Set<ModuleNode> | undefined>;
ensureEntryFromUrl(rawUrl: string): Promise<ModuleNode>;
createFileOnlyEntry(file: string): ModuleNode;
resolveUrl(url: string): Promise<ResolvedUrl>;
}

View file

@ -0,0 +1,15 @@
/**
* The following is modified based on source found in
* https://github.com/facebook/create-react-app
*
* MIT Licensed
* Copyright (c) 2015-present, Facebook, Inc.
* https://github.com/facebook/create-react-app/blob/master/LICENSE
*
*/
import { Logger } from '../logger';
/**
* Reads the BROWSER environment variable and decides what to do with it.
* Returns true if it opened a browser or ran a node.js script, otherwise false.
*/
export declare function openBrowser(url: string, opt: string | true, logger: Logger): boolean;

View file

@ -0,0 +1,37 @@
/**
* This file is refactored into TypeScript based on
* https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
*/
import { Plugin } from '../plugin';
import { InputOptions, OutputOptions, ModuleInfo, PartialResolvedId, LoadResult, SourceDescription } from 'rollup';
import * as acorn from 'acorn';
import { FSWatcher } from 'chokidar';
import { ResolvedConfig } from '../config';
import { ModuleGraph } from './moduleGraph';
export interface PluginContainerOptions {
cwd?: string;
output?: OutputOptions;
modules?: Map<string, {
info: ModuleInfo;
}>;
writeFile?: (name: string, source: string | Uint8Array) => void;
}
export interface PluginContainer {
options: InputOptions;
getModuleInfo(id: string): ModuleInfo | null;
buildStart(options: InputOptions): Promise<void>;
resolveId(id: string, importer?: string, options?: {
skip?: Set<Plugin>;
ssr?: boolean;
}): Promise<PartialResolvedId | null>;
transform(code: string, id: string, options?: {
inMap?: SourceDescription['map'];
ssr?: boolean;
}): Promise<SourceDescription | null>;
load(id: string, options?: {
ssr?: boolean;
}): Promise<LoadResult | null>;
close(): Promise<void>;
}
export declare let parser: typeof acorn.Parser;
export declare function createPluginContainer({ plugins, logger, root, build: { rollupOptions } }: ResolvedConfig, moduleGraph?: ModuleGraph, watcher?: FSWatcher): Promise<PluginContainer>;

View file

@ -0,0 +1,8 @@
/**
* Search up for the nearest `package.json`
*/
export declare function searchForPackageRoot(current: string, root?: string): string;
/**
* Search up for the nearest workspace root
*/
export declare function searchForWorkspaceRoot(current: string, root?: string): string;

View file

@ -0,0 +1,4 @@
/// <reference types="node" />
import { IncomingMessage, ServerResponse } from 'http';
import { SourceMap } from 'rollup';
export declare function send(req: IncomingMessage, res: ServerResponse, content: string | Buffer, type: string, etag?: string, cacheControl?: string, map?: SourceMap | null): void;

View file

@ -0,0 +1,8 @@
import { Logger } from '../logger';
interface SourceMapLike {
sources: string[];
sourcesContent?: (string | null)[];
sourceRoot?: string;
}
export declare function injectSourcesContent(map: SourceMapLike, file: string, logger: Logger): Promise<void>;
export {};

View file

@ -0,0 +1,14 @@
import { SourceMap } from 'rollup';
import { ViteDevServer } from '..';
export interface TransformResult {
code: string;
map: SourceMap | null;
etag?: string;
deps?: string[];
dynamicDeps?: string[];
}
export interface TransformOptions {
ssr?: boolean;
html?: boolean;
}
export declare function transformRequest(url: string, server: ViteDevServer, options?: TransformOptions): Promise<TransformResult | null>;

View file

@ -0,0 +1,14 @@
/// <reference types="node" />
import { Server } from 'http';
import { ServerOptions as HttpsServerOptions } from 'https';
import { WebSocket as WebSocketTypes } from 'types/ws';
import { HMRPayload } from 'types/hmrPayload';
import { ResolvedConfig } from '..';
export declare const HMR_HEADER = "vite-hmr";
export interface WebSocketServer {
on: WebSocketTypes.Server['on'];
off: WebSocketTypes.Server['off'];
send(payload: HMRPayload): void;
close(): Promise<void>;
}
export declare function createWebSocketServer(server: Server | null, config: ResolvedConfig, httpsOptions?: HttpsServerOptions): WebSocketServer;

View file

@ -0,0 +1,7 @@
import { ResolvedConfig } from '..';
/**
* Heuristics for determining whether a dependency should be externalized for
* server-side rendering.
*/
export declare function resolveSSRExternal(config: ResolvedConfig, knownImports: string[]): string[];
export declare function shouldExternalizeForSSR(id: string, externals: string[]): boolean;

View file

@ -0,0 +1,3 @@
import { ResolvedConfig } from '..';
import { Plugin } from '../plugin';
export declare function ssrManifestPlugin(config: ResolvedConfig): Plugin;

View file

@ -0,0 +1,7 @@
import { ViteDevServer } from '../server';
interface SSRContext {
global: typeof globalThis;
}
declare type SSRModule = Record<string, any>;
export declare function ssrLoadModule(url: string, server: ViteDevServer, context?: SSRContext, urlStack?: string[]): Promise<SSRModule>;
export {};

View file

@ -0,0 +1,3 @@
import { ModuleGraph } from '../server/moduleGraph';
export declare function ssrRewriteStacktrace(stack: string, moduleGraph: ModuleGraph): string;
export declare function rebindErrorStacktrace(e: Error, stacktrace: string): void;

View file

@ -0,0 +1,8 @@
import { SourceMap } from 'rollup';
import { TransformResult } from '../server/transformRequest';
export declare const ssrModuleExportsKey = "__vite_ssr_exports__";
export declare const ssrImportKey = "__vite_ssr_import__";
export declare const ssrDynamicImportKey = "__vite_ssr_dynamic_import__";
export declare const ssrExportAllKey = "__vite_ssr_exportAll__";
export declare const ssrImportMetaKey = "__vite_ssr_import_meta__";
export declare function ssrTransform(code: string, inMap: SourceMap | null, url: string): Promise<TransformResult | null>;

240
packages/astro/vendor/vite/dist/node/terser.js vendored Executable file → Normal file
View file

@ -4613,7 +4613,7 @@ function parse($TEXT, options) {
}
if (S.token.value == "import" && !is_token(peek(), "punc", "(") && !is_token(peek(), "punc", ".")) {
next();
var node = import_();
var node = import_statement();
semicolon();
return node;
}
@ -4765,7 +4765,7 @@ function parse($TEXT, options) {
case "export":
if (!is_token(peek(), "punc", "(")) {
next();
var node = export_();
var node = export_statement();
if (is("punc", ";")) semicolon();
return node;
}
@ -5942,7 +5942,7 @@ function parse($TEXT, options) {
};
const is_not_method_start = () =>
!is("punc", "(") && !is("punc", ",") && !is("punc", "}") && !is("operator", "=");
!is("punc", "(") && !is("punc", ",") && !is("punc", "}") && !is("punc", ";") && !is("operator", "=");
var is_async = false;
var is_static = false;
@ -6057,7 +6057,15 @@ function parse($TEXT, options) {
}
}
function import_() {
function maybe_import_assertion() {
if (is("name", "assert") && !has_newline_before(S.token)) {
next();
return object_or_destructuring_();
}
return null;
}
function import_statement() {
var start = prev();
var imported_name;
@ -6080,16 +6088,20 @@ function parse($TEXT, options) {
unexpected();
}
next();
const assert_clause = maybe_import_assertion();
return new AST_Import({
start: start,
imported_name: imported_name,
imported_names: imported_names,
start,
imported_name,
imported_names,
module_name: new AST_String({
start: mod_str,
value: mod_str.value,
quote: mod_str.quote,
end: mod_str,
}),
assert_clause,
end: S.token,
});
}
@ -6197,7 +6209,7 @@ function parse($TEXT, options) {
return names;
}
function export_() {
function export_statement() {
var start = S.token;
var is_default;
var exported_names;
@ -6215,6 +6227,8 @@ function parse($TEXT, options) {
}
next();
const assert_clause = maybe_import_assertion();
return new AST_Export({
start: start,
is_default: is_default,
@ -6226,6 +6240,7 @@ function parse($TEXT, options) {
end: mod_str,
}),
end: prev(),
assert_clause
});
} else {
return new AST_Export({
@ -6271,6 +6286,7 @@ function parse($TEXT, options) {
exported_value: exported_value,
exported_definition: exported_definition,
end: prev(),
assert_clause: null
});
}
@ -7604,12 +7620,13 @@ var AST_NameMapping = DEFNODE("NameMapping", "foreign_name name", {
},
});
var AST_Import = DEFNODE("Import", "imported_name imported_names module_name", {
var AST_Import = DEFNODE("Import", "imported_name imported_names module_name assert_clause", {
$documentation: "An `import` statement",
$propdoc: {
imported_name: "[AST_SymbolImport] The name of the variable holding the module's default export.",
imported_names: "[AST_NameMapping*] The names of non-default imported variables",
module_name: "[AST_String] String literal describing where this module came from",
assert_clause: "[AST_Object?] The import assertion"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
@ -7638,14 +7655,15 @@ var AST_ImportMeta = DEFNODE("ImportMeta", null, {
$documentation: "A reference to import.meta",
});
var AST_Export = DEFNODE("Export", "exported_definition exported_value is_default exported_names module_name", {
var AST_Export = DEFNODE("Export", "exported_definition exported_value is_default exported_names module_name assert_clause", {
$documentation: "An `export` statement",
$propdoc: {
exported_definition: "[AST_Defun|AST_Definitions|AST_DefClass?] An exported definition",
exported_value: "[AST_Node?] An exported value",
exported_names: "[AST_NameMapping*?] List of exported names",
module_name: "[AST_String?] Name of the file to load exports from",
is_default: "[Boolean] Whether this is the default exported value of this module"
is_default: "[Boolean] Whether this is the default exported value of this module",
assert_clause: "[AST_Object?] The import assertion"
},
_walk: function (visitor) {
return visitor._visit(this, function () {
@ -8898,6 +8916,24 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
return body;
};
const assert_clause_from_moz = (assertions) => {
if (assertions && assertions.length > 0) {
return new AST_Object({
start: my_start_token(assertions),
end: my_end_token(assertions),
properties: assertions.map((assertion_kv) =>
new AST_ObjectKeyVal({
start: my_start_token(assertion_kv),
end: my_end_token(assertion_kv),
key: assertion_kv.key.name || assertion_kv.key.value,
value: from_moz(assertion_kv.value)
})
)
});
}
return null;
};
var MOZ_TO_ME = {
Program: function(M) {
return new AST_Toplevel({
@ -9218,7 +9254,8 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
end : my_end_token(M),
imported_name: imported_name,
imported_names : imported_names,
module_name : from_moz(M.source)
module_name : from_moz(M.source),
assert_clause: assert_clause_from_moz(M.assertions)
});
},
ExportAllDeclaration: function(M) {
@ -9231,7 +9268,8 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
foreign_name: new AST_SymbolExportForeign({ name: "*" })
})
],
module_name: from_moz(M.source)
module_name: from_moz(M.source),
assert_clause: assert_clause_from_moz(M.assertions)
});
},
ExportNamedDeclaration: function(M) {
@ -9245,7 +9283,8 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
name: from_moz(specifier.local)
});
}) : null,
module_name: from_moz(M.source)
module_name: from_moz(M.source),
assert_clause: assert_clause_from_moz(M.assertions)
});
},
ExportDefaultDeclaration: function(M) {
@ -9537,12 +9576,30 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
};
});
const assert_clause_to_moz = assert_clause => {
const assertions = [];
if (assert_clause) {
for (const { key, value } of assert_clause.properties) {
const key_moz = is_basic_identifier_string(key)
? { type: "Identifier", name: key }
: { type: "Literal", value: key, raw: JSON.stringify(key) };
assertions.push({
type: "ImportAttribute",
key: key_moz,
value: to_moz(value)
});
}
}
return assertions;
};
def_to_moz(AST_Export, function To_Moz_ExportDeclaration(M) {
if (M.exported_names) {
if (M.exported_names[0].name.name === "*") {
return {
type: "ExportAllDeclaration",
source: to_moz(M.module_name)
source: to_moz(M.module_name),
assertions: assert_clause_to_moz(M.assert_clause)
};
}
return {
@ -9555,7 +9612,8 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
};
}),
declaration: to_moz(M.exported_definition),
source: to_moz(M.module_name)
source: to_moz(M.module_name),
assertions: assert_clause_to_moz(M.assert_clause)
};
}
return {
@ -9589,7 +9647,8 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
return {
type: "ImportDeclaration",
specifiers: specifiers,
source: to_moz(M.module_name)
source: to_moz(M.module_name),
assertions: assert_clause_to_moz(M.assert_clause)
};
});
@ -10146,6 +10205,48 @@ function is_some_comments(comment) {
);
}
class Rope {
constructor() {
this.committed = "";
this.current = "";
}
append(str) {
this.current += str;
}
insertAt(char, index) {
const { committed, current } = this;
if (index < committed.length) {
this.committed = committed.slice(0, index) + char + committed.slice(index);
} else if (index === committed.length) {
this.committed += char;
} else {
index -= committed.length;
this.committed += current.slice(0, index) + char;
this.current = current.slice(index);
}
}
charAt(index) {
const { committed } = this;
if (index < committed.length) return committed[index];
return this.current[index - committed.length];
}
curLength() {
return this.current.length;
}
length() {
return this.committed.length + this.current.length;
}
toString() {
return this.committed + this.current;
}
}
function OutputStream(options) {
var readonly = !options;
@ -10210,7 +10311,7 @@ function OutputStream(options) {
var current_col = 0;
var current_line = 1;
var current_pos = 0;
var OUTPUT = "";
var OUTPUT = new Rope();
let printed_comments = new Set();
var to_utf8 = options.ascii_only ? function(str, identifier) {
@ -10341,19 +10442,18 @@ function OutputStream(options) {
var ensure_line_len = options.max_line_len ? function() {
if (current_col > options.max_line_len) {
if (might_add_newline) {
var left = OUTPUT.slice(0, might_add_newline);
var right = OUTPUT.slice(might_add_newline);
OUTPUT.insertAt("\n", might_add_newline);
const curLength = OUTPUT.curLength();
if (mappings) {
var delta = right.length - current_col;
var delta = curLength - current_col;
mappings.forEach(function(mapping) {
mapping.line++;
mapping.col += delta;
});
}
OUTPUT = left + "\n" + right;
current_line++;
current_pos++;
current_col = right.length;
current_col = curLength;
}
}
if (might_add_newline) {
@ -10387,13 +10487,13 @@ function OutputStream(options) {
if (prev === ":" && ch === "}" || (!ch || !";}".includes(ch)) && prev !== ";") {
if (options.semicolons || requireSemicolonChars.has(ch)) {
OUTPUT += ";";
OUTPUT.append(";");
current_col++;
current_pos++;
} else {
ensure_line_len();
if (current_col > 0) {
OUTPUT += "\n";
OUTPUT.append("\n");
current_pos++;
current_line++;
current_col = 0;
@ -10417,7 +10517,7 @@ function OutputStream(options) {
|| (ch == "/" && ch == prev)
|| ((ch == "+" || ch == "-") && ch == last)
) {
OUTPUT += " ";
OUTPUT.append(" ");
current_col++;
current_pos++;
}
@ -10435,7 +10535,7 @@ function OutputStream(options) {
if (!might_add_newline) do_add_mapping();
}
OUTPUT += str;
OUTPUT.append(str);
has_parens = str[str.length - 1] == "(";
current_pos += str.length;
var a = str.split(/\r?\n/), n = a.length - 1;
@ -10475,15 +10575,15 @@ function OutputStream(options) {
var newline = options.beautify ? function() {
if (newline_insert < 0) return print("\n");
if (OUTPUT[newline_insert] != "\n") {
OUTPUT = OUTPUT.slice(0, newline_insert) + "\n" + OUTPUT.slice(newline_insert);
if (OUTPUT.charAt(newline_insert) != "\n") {
OUTPUT.insertAt("\n", newline_insert);
current_pos++;
current_line++;
}
newline_insert++;
} : options.max_line_len ? function() {
ensure_line_len();
might_add_newline = OUTPUT.length;
might_add_newline = OUTPUT.length();
} : noop;
var semicolon = options.beautify ? function() {
@ -10549,13 +10649,14 @@ function OutputStream(options) {
if (might_add_newline) {
ensure_line_len();
}
return OUTPUT;
return OUTPUT.toString();
}
function has_nlb() {
let n = OUTPUT.length - 1;
const output = OUTPUT.toString();
let n = output.length - 1;
while (n >= 0) {
const code = OUTPUT.charCodeAt(n);
const code = output.charCodeAt(n);
if (code === CODE_LINE_BREAK) {
return true;
}
@ -10692,7 +10793,7 @@ function OutputStream(options) {
!/comment[134]/.test(c.type)
))) return;
printed_comments.add(comments);
var insert = OUTPUT.length;
var insert = OUTPUT.length();
comments.filter(comment_filter, node).forEach(function(c, i) {
if (printed_comments.has(c)) return;
printed_comments.add(c);
@ -10721,7 +10822,7 @@ function OutputStream(options) {
need_space = true;
}
});
if (OUTPUT.length > insert) newline_insert = insert;
if (OUTPUT.length() > insert) newline_insert = insert;
}
var stack = [];
@ -10751,7 +10852,7 @@ function OutputStream(options) {
var encoded = encode_string(str, quote);
if (escape_directive === true && !encoded.includes("\\")) {
// Insert semicolons to break directive prologue
if (!EXPECT_DIRECTIVE.test(OUTPUT)) {
if (!EXPECT_DIRECTIVE.test(OUTPUT.toString())) {
force_semicolon();
}
force_semicolon();
@ -11607,6 +11708,10 @@ function OutputStream(options) {
output.space();
}
self.module_name.print(output);
if (self.assert_clause) {
output.print("assert");
self.assert_clause.print(output);
}
output.semicolon();
});
DEFPRINT(AST_ImportMeta, function(self, output) {
@ -11672,6 +11777,10 @@ function OutputStream(options) {
output.space();
self.module_name.print(output);
}
if (self.assert_clause) {
output.print("assert");
self.assert_clause.print(output);
}
if (self.exported_value
&& !(self.exported_value instanceof AST_Defun ||
self.exported_value instanceof AST_Function ||
@ -13222,6 +13331,8 @@ AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
}
const mangled_names = this.mangled_names = new Set();
unmangleable_names = new Set();
if (options.cache) {
this.globals.forEach(collect);
if (options.cache.props) {
@ -13274,7 +13385,6 @@ AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
this.walk(tw);
if (options.keep_fnames || options.keep_classnames) {
unmangleable_names = new Set();
// Collect a set of short names which are unmangleable,
// for use in avoiding collisions in next_mangled.
to_mangle.forEach(def => {
@ -13290,9 +13400,9 @@ AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
unmangleable_names = null;
function collect(symbol) {
const should_mangle = !options.reserved.has(symbol.name)
&& !(symbol.export & MASK_EXPORT_DONT_MANGLE);
if (should_mangle) {
if (symbol.export & MASK_EXPORT_DONT_MANGLE) {
unmangleable_names.add(symbol.name);
} else if (!options.reserved.has(symbol.name)) {
to_mangle.push(symbol);
}
}
@ -14330,6 +14440,7 @@ const is_pure_native_fn = make_nested_lookup({
"isExtensible",
"isFrozen",
"isSealed",
"hasOwn",
"keys",
],
String: [
@ -19357,7 +19468,7 @@ def_optimize(AST_Switch, function(self, compressor) {
// that way the next micro-optimization will merge them.
// ** bail micro-optimization if not a simple switch case with breaks
if (body.every((branch, i) =>
(branch === default_or_exact || !branch.expression.has_side_effects(compressor))
(branch === default_or_exact || branch.expression instanceof AST_Constant)
&& (branch.body.length === 0 || aborts(branch) || body.length - 1 === i))
) {
for (let i = 0; i < body.length; i++) {
@ -19445,12 +19556,16 @@ def_optimize(AST_Switch, function(self, compressor) {
// Prune side-effect free branches that fall into default.
if (default_or_exact) {
DEFAULT: if (default_or_exact) {
let default_index = body.indexOf(default_or_exact);
let default_body_index = default_index;
for (; default_body_index < body.length - 1; default_body_index++) {
if (!is_inert_body(body[default_body_index])) break;
}
if (default_body_index < body.length - 1) {
break DEFAULT;
}
let side_effect_index = body.length - 1;
for (; side_effect_index >= 0; side_effect_index--) {
let branch = body[side_effect_index];
@ -20497,16 +20612,16 @@ def_optimize(AST_UnaryPostfix, function(self, compressor) {
def_optimize(AST_UnaryPrefix, function(self, compressor) {
var e = self.expression;
if (self.operator == "delete"
&& !(e instanceof AST_SymbolRef
|| e instanceof AST_PropAccess
|| is_identifier_atom(e))) {
if (e instanceof AST_Sequence) {
const exprs = e.expressions.slice();
exprs.push(make_node(AST_True, self));
return make_sequence(self, exprs).optimize(compressor);
}
return make_sequence(self, [ e, make_node(AST_True, self) ]).optimize(compressor);
if (
self.operator == "delete" &&
!(
e instanceof AST_SymbolRef ||
e instanceof AST_PropAccess ||
e instanceof AST_Chain ||
is_identifier_atom(e)
)
) {
return make_sequence(self, [e, make_node(AST_True, self)]).optimize(compressor);
}
var seq = self.lift_sequences(compressor);
if (seq !== self) {
@ -21338,7 +21453,15 @@ function is_reachable(self, defs) {
if (node instanceof AST_Scope && node !== self) {
var parent = info.parent();
if (parent instanceof AST_Call && parent.expression === node) return;
if (
parent instanceof AST_Call
&& parent.expression === node
// Async/Generators aren't guaranteed to sync evaluate all of
// their body steps, so it's possible they close over the variable.
&& !(node.async || node.is_generator)
) {
return;
}
if (walk(node, find_ref)) return walk_abort;
@ -21990,7 +22113,16 @@ def_optimize(AST_Sub, function(self, compressor) {
});
def_optimize(AST_Chain, function (self, compressor) {
if (is_nullish(self.expression, compressor)) return make_node(AST_Undefined, self);
if (is_nullish(self.expression, compressor)) {
let parent = compressor.parent();
// It's valid to delete a nullish optional chain, but if we optimized
// this to `delete undefined` then it would appear to be a syntax error
// when we try to optimize the delete. Thankfully, `delete 0` is fine.
if (parent instanceof AST_UnaryPrefix && parent.operator === "delete") {
return make_node_from_constant(0, self);
}
return make_node(AST_Undefined, self);
}
return self;
});

View file

@ -0,0 +1,114 @@
import debug from 'debug';
import { FSWatcher } from 'chokidar';
import { DecodedSourceMap, RawSourceMap } from '@ampproject/remapping/dist/types/types';
export declare function slash(p: string): string;
export declare function unwrapId(id: string): string;
export declare const flattenId: (id: string) => string;
export declare const normalizeId: (id: string) => string;
export declare function isBuiltin(id: string): boolean;
export declare function moduleListContains(moduleList: string[] | undefined, id: string): boolean | undefined;
export declare const bareImportRE: RegExp;
export declare const deepImportRE: RegExp;
export declare let isRunningWithYarnPnp: boolean;
export declare function resolveFrom(id: string, basedir: string, preserveSymlinks?: boolean, ssr?: boolean): string;
/**
* like `resolveFrom` but supports resolving `>` path in `id`,
* for example: `foo > bar > baz`
*/
export declare function nestedResolveFrom(id: string, basedir: string, preserveSymlinks?: boolean): string;
interface DebuggerOptions {
onlyWhenFocused?: boolean | string;
}
export declare type ViteDebugScope = `vite:${string}`;
export declare function createDebugger(namespace: ViteDebugScope, options?: DebuggerOptions): debug.Debugger['log'];
export declare const isWindows: boolean;
export declare function normalizePath(id: string): string;
export declare function fsPathFromId(id: string): string;
export declare function ensureVolumeInPath(file: string): string;
export declare const queryRE: RegExp;
export declare const hashRE: RegExp;
export declare const cleanUrl: (url: string) => string;
export declare const externalRE: RegExp;
export declare const isExternalUrl: (url: string) => boolean;
export declare const dataUrlRE: RegExp;
export declare const isDataUrl: (url: string) => boolean;
export declare const virtualModuleRE: RegExp;
export declare const virtualModulePrefix = "virtual-module:";
export declare const isJSRequest: (url: string) => boolean;
export declare const isTsRequest: (url: string) => boolean;
export declare const isPossibleTsOutput: (url: string) => boolean;
export declare const getTsSrcPath: (filename: string) => string;
export declare const isImportRequest: (url: string) => boolean;
export declare const isInternalRequest: (url: string) => boolean;
export declare function removeImportQuery(url: string): string;
export declare function injectQuery(url: string, queryToInject: string): string;
export declare function removeTimestampQuery(url: string): string;
export declare function asyncReplace(input: string, re: RegExp, replacer: (match: RegExpExecArray) => string | Promise<string>): Promise<string>;
export declare function timeFrom(start: number, subtract?: number): string;
/**
* pretty url for logging.
*/
export declare function prettifyUrl(url: string, root: string): string;
export declare function isObject(value: unknown): value is Record<string, any>;
export declare function isDefined<T>(value: T | undefined | null): value is T;
export declare function lookupFile(dir: string, formats: string[], pathOnly?: boolean): string | undefined;
export declare function pad(source: string, n?: number): string;
export declare function posToNumber(source: string, pos: number | {
line: number;
column: number;
}): number;
export declare function numberToPos(source: string, offset: number | {
line: number;
column: number;
}): {
line: number;
column: number;
};
export declare function generateCodeFrame(source: string, start?: number | {
line: number;
column: number;
}, end?: number): string;
export declare function writeFile(filename: string, content: string | Uint8Array): void;
/**
* Use instead of fs.existsSync(filename)
* #2051 if we don't have read permission on a directory, existsSync() still
* works and will result in massively slow subsequent checks (which are
* unnecessary in the first place)
*/
export declare function isFileReadable(filename: string): boolean;
/**
* Delete every file and subdirectory. **The given directory must exist.**
* Pass an optional `skip` array to preserve files in the root directory.
*/
export declare function emptyDir(dir: string, skip?: string[]): void;
export declare function copyDir(srcDir: string, destDir: string): void;
export declare function ensureLeadingSlash(path: string): string;
export declare function ensureWatchedFile(watcher: FSWatcher, file: string | null, root: string): void;
interface ImageCandidate {
url: string;
descriptor: string;
}
export declare function processSrcSet(srcs: string, replacer: (arg: ImageCandidate) => Promise<string>): Promise<string>;
export declare function combineSourcemaps(filename: string, sourcemapList: Array<DecodedSourceMap | RawSourceMap>): RawSourceMap;
export declare function unique<T>(arr: T[]): T[];
export interface Hostname {
host: string | undefined;
name: string;
}
export declare function resolveHostname(optionsHost: string | boolean | undefined): Hostname;
export declare function arraify<T>(target: T | T[]): T[];
export declare function toUpperCaseDriveLetter(pathName: string): string;
export declare const multilineCommentsRE: RegExp;
export declare const singlelineCommentsRE: RegExp;
export declare const usingDynamicImport: boolean;
/**
* Dynamically import files. It will make sure it's not being compiled away by TS/Rollup.
*
* As a temporary workaround for Jest's lack of stable ESM support, we fallback to require
* if we're in a Jest environment.
* See https://github.com/vitejs/vite/pull/5197#issuecomment-938054077
*
* @param file File path to import.
*/
export declare const dynamicImport: Function;
export {};