before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
import { defineConfig } from 'vite' const timeout = (ms) => new Promise((r) => setTimeout(r, ms)) export default defineConfig({ server: { port: 9606, proxy: { '/nonExistentApp': { target: 'http://localhost:9607', bypass: () => { return false }, }, '/proxyE...
```suggestion target: 'http://foo.invalid', ``` @copilot
import { defineConfig } from 'vite' const timeout = (ms) => new Promise((r) => setTimeout(r, ms)) export default defineConfig({ server: { port: 9606, proxy: { '/nonExistentApp': { target: 'http://localhost:9607', bypass: () => { return false }, }, '/proxyE...
@@ -12,6 +12,9 @@ export default defineConfig({ return false }, }, + '/proxyError': { + target: 'http://localhost:9608',
playground/proxy-bypass/vite.config.js
16
JavaScript
0.857
suggestion
65
41
41
false
fix(dev): return "502 Bad Gateway" on proxy failures instead of 500
21,652
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { describe, expect, test } from 'vitest' import type { InternalModuleFormat } from 'rolldown' import MagicString from 'magic-string' import { resolveConfig } from '../../config' import type { InlineConfig } from '../../config' import ...
Instead of a unit test here, would you add a test to `playground/backend-integration`? Also it would be nice to have tests for non-public assets.
import path from 'node:path' import { describe, expect, test } from 'vitest' import type { InternalModuleFormat } from 'rolldown' import MagicString from 'magic-string' import { resolveConfig } from '../../config' import type { InlineConfig } from '../../config' import { convertTargets, cssPlugin, cssUrlRE, get...
packages/vite/src/node/__tests__/plugins/css.spec.ts
1
TypeScript
0.714
suggestion
147
26
26
false
fix(css): apply `server.origin` to public file URLs in CSS (fix #18457)
21,697
vitejs/vite
78,557
TypeScript
sapphi-red
SalvatoreT
test('Respect exports to take precedence over mainFields', async () => { expect(await page.textContent('.exports-with-module')).toMatch('[success]') }) test('implicit dir/index.js', async () => { expect(await page.textContent('.index')).toMatch('[success]') }) test('implicit dir/index.js vs explicit file', async ...
No issues found.
test('Respect exports to take precedence over mainFields', async () => { expect(await page.textContent('.exports-with-module')).toMatch('[success]') }) test('implicit dir/index.js', async () => { expect(await page.textContent('.index')).toMatch('[success]') }) test('implicit dir/index.js vs explicit file', async ...
@@ -158,3 +158,23 @@ test('resolve package that contains # in path', async () => { '[success]', ) }) + +test('Resolving top level with imports field', async () => { + expect(await page.textContent('.imports-top-level')).toMatch('[success]') +}) + +test('Resolving nested path with imports field', async () => {...
playground/resolve/__tests__/resolve.spec.ts
0
TypeScript
1
none
16
51
51
true
feat: support ESM subpath imports
7,770
vitejs/vite
78,557
TypeScript
fi3ework
export function readManifest(base = ''): Manifest { return JSON.parse( fs.readFileSync( path.join(testDir, 'dist', base, '.vite/manifest.json'), 'utf-8', ), ) } export function readDepOptimizationMetadata(): DepOptimizationMetadata { return JSON.parse( fs.readFileSync( path.join(tes...
No issues found.
export function readManifest(base = ''): Manifest { return JSON.parse( fs.readFileSync( path.join(testDir, 'dist', base, '.vite/manifest.json'), 'utf-8', ), ) } export function readDepOptimizationMetadata(): DepOptimizationMetadata { return JSON.parse( fs.readFileSync( path.join(tes...
@@ -35,9 +35,11 @@ export const ports = { 'ssr-noexternal': 9603, 'ssr-pug': 9604, 'ssr-webworker': 9605, - 'proxy-hmr': 9606, // not imported but used in `proxy-hmr/vite.config.js` - 'proxy-hmr/other-app': 9607, // not imported but used in `proxy-hmr/other-app/vite.config.js` - 'ssr-conditions': 9608, + '...
playground/test-utils.ts
0
TypeScript
1
none
16
51
51
true
test: fix proxy-bypass and proxy-hmr ports
15,716
vitejs/vite
78,557
TypeScript
patak-cat
) } export function loadPackageData(pkgPath: string): PackageData { const data = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) const pkgDir = normalizePath(path.dirname(pkgPath)) const { sideEffects } = data let hasSideEffects: (id: string) => boolean | null if (typeof sideEffects === 'boolean') { hasS...
No issues found.
) } export function loadPackageData(pkgPath: string): PackageData { const data = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) const pkgDir = normalizePath(path.dirname(pkgPath)) const { sideEffects } = data let hasSideEffects: (id: string) => boolean | null if (typeof sideEffects === 'boolean') { hasS...
@@ -240,6 +240,21 @@ function getResolveCacheKey( ].join('|') } +export function findNearestNodeModules(basedir: string): string | null { + while (basedir) { + const pkgPath = path.join(basedir, 'node_modules') + if (tryStatSync(pkgPath)?.isDirectory()) { + return pkgPath + } + + const nextBased...
packages/vite/src/node/packages.ts
0
TypeScript
1
none
16
51
51
true
fix(config): write temporary vite config to node_modules
18,509
vitejs/vite
78,557
TypeScript
bluwy
import { fileURLToPath } from 'node:url' import type { OutputAsset, RollupOutput } from 'rollup' import { expect, test } from 'vitest' import { build } from '../../build' test('markdown', async () => { const result = (await build({ root: fileURLToPath(new URL('./fixtures/license', import.meta.url)), logLevel...
No issues found.
import { fileURLToPath } from 'node:url' import type { OutputAsset, RollupOutput } from 'rollup' import { expect, test } from 'vitest' import { build } from '../../build' test('markdown', async () => { const result = (await build({ root: fileURLToPath(new URL('./fixtures/license', import.meta.url)), logLevel...
@@ -0,0 +1,38 @@ +import { fileURLToPath } from 'node:url' +import type { OutputAsset, RollupOutput } from 'rollup' +import { expect, test } from 'vitest' +import { build } from '../../build' + +test('markdown', async () => { + const result = (await build({ + root: fileURLToPath(new URL('./fixtures/license', import...
packages/vite/src/node/__tests__/plugins/license.spec.ts
0
TypeScript
1
none
16
39
39
true
feat(build): emit license
18,546
vitejs/vite
78,557
TypeScript
bluwy
const environment = server.environments[options?.ssr ? 'ssr' : 'client'] await transformRequest(environment, url, options) } catch (e) { if ( e?.code === ERR_OUTDATED_OPTIMIZED_DEP || e?.code === ERR_CLOSED_SERVER ) { // these are expected errors ...
No issues found.
const environment = server.environments[options?.ssr ? 'ssr' : 'client'] await transformRequest(environment, url, options) } catch (e) { if ( e?.code === ERR_OUTDATED_OPTIMIZED_DEP || e?.code === ERR_CLOSED_SERVER ) { // these are expected errors ...
@@ -23,7 +23,7 @@ import { setClientErrorHandler, } from '../http' import type { InlineConfig, ResolvedConfig } from '../config' -import { resolveConfig } from '../config' +import { isResolvedConfig, resolveConfig } from '../config' import { diffDnsOrderChange, getServerUrlByHost, @@ -101,6 +101,8 @@ import...
packages/vite/src/node/server/index.ts
0
TypeScript
1
none
16
51
51
true
feat: allow passing down resolved config to vite's `createServer`
19,894
vitejs/vite
78,557
TypeScript
sheremet-va
import { describe, expect, it, vi } from 'vitest' import { resolveServerOptions } from '../index' describe('resolveServerOptions', () => { const root = '/test' const logger = { warn: vi.fn(), } as any it('should use a default hostname when no host is provided', async () => { const resolvedOptions = aw...
No issues found.
import { describe, expect, it, vi } from 'vitest' import { resolveServerOptions } from '../index' describe('resolveServerOptions', () => { const root = '/test' const logger = { warn: vi.fn(), } as any it('should use a default hostname when no host is provided', async () => { const resolvedOptions = aw...
@@ -0,0 +1,30 @@ +import { describe, expect, it, vi } from 'vitest' +import { resolveServerOptions } from '../index' + +describe('resolveServerOptions', () => { + const root = '/test' + const logger = { + warn: vi.fn(), + } as any + + it('should use a default hostname when no host is provided', async () => { + ...
packages/vite/src/node/server/__tests__/resolveServerOptions.spec.ts
0
TypeScript
1
none
16
31
31
true
feat: resolve server URLs before calling other listeners
19,981
vitejs/vite
78,557
TypeScript
sirdiego
// FIXME // await expectWithRetry(() => // page.textContent('.dep-with-optional-peer-dep-cjs-error'), // ).toMatch(`[success]`) }) test('dep with css import', async () => { await expectWithRetry(() => getColor('.dep-linked-include')).toBe('red') }) test('CJS dep with css import', async () => { await exp...
No issues found.
// FIXME // await expectWithRetry(() => // page.textContent('.dep-with-optional-peer-dep-cjs-error'), // ).toMatch(`[success]`) }) test('dep with css import', async () => { await expectWithRetry(() => getColor('.dep-linked-include')).toBe('red') }) test('CJS dep with css import', async () => { await exp...
@@ -142,26 +142,28 @@ test('dep with optional peer dep', async () => { await expectWithRetry(() => page.textContent('.dep-with-optional-peer-dep'), ).toMatch(`[success]`) - if (isServe) { - expect(browserErrors.map((error) => error.message)).toEqual( - expect.arrayContaining([ - 'Could not re...
playground/optimize-deps/__tests__/optimize-deps.spec.ts
0
TypeScript
1
none
16
51
51
true
fix: importing an optional peer dep should throw an runtime error
20,029
vitejs/vite
78,557
TypeScript
sapphi-red
function foo() { return 'foo' } foo.bar = 'bar' export const bar = 'bar' export default foo
No issues found.
function foo() { return 'foo' } foo.bar = 'bar' export const bar = 'bar' export default foo
@@ -0,0 +1,9 @@ +function foo() { + return 'foo' +} + +foo.bar = 'bar' + +export const bar = 'bar' + +export default foo
playground/optimize-deps/dep-esm-dummy-node-builtin/index.js
0
JavaScript
1
none
16
10
10
true
fix(optimizer): non object module.exports for Node builtin modules in CJS external facade
20,048
vitejs/vite
78,557
TypeScript
jamesopstad
expect(await getBg(urlStartsWithVariable)).toMatch( isBuild ? /ok-[-\w]+\.png/ : `${viteTestUrl}/ok.png`, ) expect(await getBg(urlStartsWithVariableInterpolation1)).toMatch( isBuild ? /ok-[-\w]+\.png/ : `${viteTestUrl}/ok.png`, ) expect(await getBg(urlStartsWithVariableInterpolation2)).t...
No issues found.
expect(await getBg(urlStartsWithVariable)).toMatch( isBuild ? /ok-[-\w]+\.png/ : `${viteTestUrl}/ok.png`, ) expect(await getBg(urlStartsWithVariableInterpolation1)).toMatch( isBuild ? /ok-[-\w]+\.png/ : `${viteTestUrl}/ok.png`, ) expect(await getBg(urlStartsWithVariableInterpolation2)).t...
@@ -15,6 +15,15 @@ export const sassTest = () => { const atImport = await page.$('.sass-at-import') const atImportAlias = await page.$('.sass-at-import-alias') const urlStartsWithVariable = await page.$('.sass-url-starts-with-variable') + const urlStartsWithVariableInterpolation1 = await page.$( + ...
playground/css/__tests__/sass-tests.ts
0
TypeScript
1
none
16
51
51
true
fix(css): should not wrap with double quote when the url rebase feature bailed out
20,068
vitejs/vite
78,557
TypeScript
sapphi-red
* * when using, the consumer should check if it's an instance generated from the same class or factory function */ previousInstance?: DevEnvironment }): Promise<void> { if (this._initiated) { return } this._initiated = true this._pluginContainer = await createEnvironmentPlugin...
No issues found.
* * when using, the consumer should check if it's an instance generated from the same class or factory function */ previousInstance?: DevEnvironment }): Promise<void> { if (this._initiated) { return } this._initiated = true this._pluginContainer = await createEnvironmentPlugin...
@@ -1,10 +1,7 @@ import type { FetchFunctionOptions, FetchResult } from 'vite/module-runner' import type { FSWatcher } from 'dep-types/chokidar' import colors from 'picocolors' -import { - BaseEnvironment, - getDefaultResolvedEnvironmentOptions, -} from '../baseEnvironment' +import { BaseEnvironment } from '../bas...
packages/vite/src/node/server/environment.ts
0
TypeScript
1
none
16
51
51
true
feat: resolve environments plugins at config time
20,120
vitejs/vite
78,557
TypeScript
patak-cat
import type { Plugin } from 'vite' const svgVirtualModuleId = 'virtual:foo.svg' const resolvedSvgVirtualModuleId = '\0' + svgVirtualModuleId export default function svgVirtualModulePlugin(): Plugin { return { name: 'svg-virtual-module', resolveId(id) { if (id === svgVirtualModuleId) { return re...
No issues found.
import type { Plugin } from 'vite' const svgVirtualModuleId = 'virtual:foo.svg' const resolvedSvgVirtualModuleId = '\0' + svgVirtualModuleId export default function svgVirtualModulePlugin(): Plugin { return { name: 'svg-virtual-module', resolveId(id) { if (id === svgVirtualModuleId) { return re...
@@ -0,0 +1,20 @@ +import type { Plugin } from 'vite' +const svgVirtualModuleId = 'virtual:foo.svg' +const resolvedSvgVirtualModuleId = '\0' + svgVirtualModuleId + +export default function svgVirtualModulePlugin(): Plugin { + return { + name: 'svg-virtual-module', + resolveId(id) { + if (id === svgVirtualMod...
playground/fs-serve/root/svgVirtualModulePlugin.ts
0
TypeScript
1
none
16
21
21
true
fix: virtual svg module
20,144
vitejs/vite
78,557
TypeScript
patak-cat
start + arg2.start, logger, ) } const globsResolved = await Promise.all( globs.map((glob) => toAbsoluteGlob(glob, root, importer, resolveId, options.base), ), ) const isRelative = globs.every((i) => '.!'.includes(i[0])) const sliceCode = cleanCode.slice(0, ...
No issues found.
start + arg2.start, logger, ) } const globsResolved = await Promise.all( globs.map((glob) => toAbsoluteGlob(glob, root, importer, resolveId, options.base), ), ) const isRelative = globs.every((i) => '.!'.includes(i[0])) const sliceCode = cleanCode.slice(0, ...
@@ -120,6 +120,7 @@ const knownOptions = { import: ['string'], exhaustive: ['boolean'], query: ['object', 'string'], + base: ['string'], } const forceDefaultAs = ['raw', 'url'] @@ -165,6 +166,21 @@ function parseGlobOptions( } } + if (opts.base) { + if (opts.base[0] === '!') { + throw e...
packages/vite/src/node/plugins/importMetaGlob.ts
0
TypeScript
1
none
16
51
51
true
feat: add base option to import.meta.glob
20,163
vitejs/vite
78,557
TypeScript
patak-cat
import { posixDirname, posixPathToFileHref, toWindowsPath } from './utils' const envProxy = new Proxy({} as any, { get(_, p) { throw new Error( `[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`, ) }, }) export function createD...
No issues found.
import { posixDirname, posixPathToFileHref, toWindowsPath } from './utils' const envProxy = new Proxy({} as any, { get(_, p) { throw new Error( `[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`, ) }, }) export function createD...
@@ -0,0 +1,62 @@ +import { isWindows } from '../shared/utils' +import { + type ImportMetaResolver, + createImportMetaResolver, +} from './importMetaResolver' +import type { ModuleRunnerImportMeta } from './types' +import { posixDirname, posixPathToFileHref, toWindowsPath } from './utils' + +const envProxy = new Proxy...
packages/vite/src/module-runner/createImportMeta.ts
0
TypeScript
1
none
16
51
51
true
feat(ssr): support `import.meta.resolve` in module runner
20,260
vitejs/vite
78,557
TypeScript
sapphi-red
return terserPath } export function terserPlugin(config: ResolvedConfig): Plugin { const { maxWorkers, ...terserOptions } = config.build.terserOptions const makeWorker = () => new WorkerWithFallback( () => async ( terserPath: string, code: string, options: TerserM...
No issues found.
return terserPath } export function terserPlugin(config: ResolvedConfig): Plugin { const { maxWorkers, ...terserOptions } = config.build.terserOptions const makeWorker = () => new WorkerWithFallback( () => async ( terserPath: string, code: string, options: TerserM...
@@ -1,10 +1,13 @@ -import type { Terser } from 'dep-types/terser' +import type { + TerserMinifyOptions, + TerserMinifyOutput, +} from 'types/internal/terserOptions' import { WorkerWithFallback } from 'artichokie' import type { Plugin } from '../plugin' import type { ResolvedConfig } from '..' import { requireReso...
packages/vite/src/node/plugins/terser.ts
0
TypeScript
1
none
16
51
51
true
feat(types): use terser types from terser package
20,274
vitejs/vite
78,557
TypeScript
sapphi-red
}) test('url() with svg in .css?url', async () => { const bg = await getBg('.css-url-svg-in-url') expect(bg).toMatch(/data:image\/svg\+xml,.+/) expect(bg).toContain('blue') expect(bg).not.toContain('red') if (isServe) { editFile('nested/fragment-bg-hmr2.svg', (code) => code.repla...
No issues found.
}) test('url() with svg in .css?url', async () => { const bg = await getBg('.css-url-svg-in-url') expect(bg).toMatch(/data:image\/svg\+xml,.+/) expect(bg).toContain('blue') expect(bg).not.toContain('red') if (isServe) { editFile('nested/fragment-bg-hmr2.svg', (code) => code.repla...
@@ -463,6 +463,20 @@ test('Unknown extension assets import', async () => { test('?raw import', async () => { expect(await page.textContent('.raw')).toMatch('SVG') + expect(await page.textContent('.raw-html')).toBe('<div>partial</div>\n') + + if (isBuild) return + editFile('nested/partial.html', (code) => + ...
playground/assets/__tests__/assets.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(hmr): register css deps as `type: asset`
20,391
vitejs/vite
78,557
TypeScript
sapphi-red
// for .js, also try .tsx if ( fileExt === '.js' && (res = tryResolveRealFile(fileName + '.tsx', preserveSymlinks)) ) return res } if ( (res = tryResolveRealFileWithExtensions( file, extensions, preserveSymlinks, ...
No issues found.
// for .js, also try .tsx if ( fileExt === '.js' && (res = tryResolveRealFile(fileName + '.tsx', preserveSymlinks)) ) return res } if ( (res = tryResolveRealFileWithExtensions( file, extensions, preserveSymlinks, ...
@@ -755,7 +755,7 @@ export function tryNodeResolve( const resolveId = deepMatch ? resolveDeepImport : resolvePackageEntry const unresolvedId = deepMatch ? '.' + id.slice(pkgId.length) : id - let resolved = resolveId(unresolvedId, pkg, options) + let resolved = resolveId(unresolvedId, pkg, options, externalize...
packages/vite/src/node/plugins/resolve.ts
0
TypeScript
1
none
16
51
51
true
feat(ssr): resolve externalized packages with `resolve.externalConditions` and add `module-sync` to default external condition
20,409
vitejs/vite
78,557
TypeScript
sapphi-red
) } if (!isLegacyChunk(chunk, opts)) { if ( options.modernPolyfills && !Array.isArray(options.modernPolyfills) && genModern ) { // analyze and record modern polyfills await detectPolyfills( raw, modernTargets,...
No issues found.
) } if (!isLegacyChunk(chunk, opts)) { if ( options.modernPolyfills && !Array.isArray(options.modernPolyfills) && genModern ) { // analyze and record modern polyfills await detectPolyfills( raw, modernTargets,...
@@ -3,6 +3,7 @@ import crypto from 'node:crypto' import { createRequire } from 'node:module' import { fileURLToPath } from 'node:url' import { build, normalizePath } from 'vite' +import * as vite from 'vite' import MagicString from 'magic-string' import type { BuildOptions, @@ -125,6 +126,13 @@ const nonLeading...
packages/plugin-legacy/src/index.ts
0
TypeScript
1
none
16
51
51
true
feat(legacy): add rolldown-vite support
20,417
vitejs/vite
78,557
TypeScript
sapphi-red
'Plugin hook `handleHotUpdate()` is replaced with `hotUpdate()`.', removeServerModuleGraph: 'The `server.moduleGraph` is replaced with `this.environment.moduleGraph`.', removeServerHot: 'The `server.hot` is replaced with `this.environment.hot`.', removeServerTransformRequest: 'The `server.transformRe...
No issues found.
'Plugin hook `handleHotUpdate()` is replaced with `hotUpdate()`.', removeServerModuleGraph: 'The `server.moduleGraph` is replaced with `this.environment.moduleGraph`.', removeServerHot: 'The `server.hot` is replaced with `this.environment.hot`.', removeServerTransformRequest: 'The `server.transformRe...
@@ -10,6 +10,7 @@ const deprecationCode = { removeServerModuleGraph: 'changes/per-environment-apis', removeServerHot: 'changes/per-environment-apis', removeServerTransformRequest: 'changes/per-environment-apis', + removeServerWarmupRequest: 'changes/per-environment-apis', removeSsrLoadModule: 'changes/ss...
packages/vite/src/node/deprecations.ts
0
TypeScript
1
none
16
51
51
true
feat: add `server.warmupRequest` to future deprecation
20,431
vitejs/vite
78,557
TypeScript
sapphi-red
import 'tinyglobby'
No issues found.
import 'tinyglobby'
@@ -0,0 +1 @@ +import 'tinyglobby' \ No newline at end of file
packages/vite/src/node/ssr/runtime/__tests__/fixtures/import-external.ts
0
TypeScript
1
none
16
1
1
true
fix(module-runner): normalize file:// on windows
20,449
vitejs/vite
78,557
TypeScript
sheremet-va
proxyModuleUrl = joinUrlSegments(decodedBase, proxyModuleUrl) const s = new MagicString(html) let inlineModuleIndex = -1 // The key to the proxyHtml cache is decoded, as it will be compared // against decoded URLs by the HTML plugins. const proxyCacheUrl = decodeURI( cleanUrl(proxyModulePath).replace(n...
No issues found.
proxyModuleUrl = joinUrlSegments(decodedBase, proxyModuleUrl) const s = new MagicString(html) let inlineModuleIndex = -1 // The key to the proxyHtml cache is decoded, as it will be compared // against decoded URLs by the HTML plugins. const proxyCacheUrl = decodeURI( cleanUrl(proxyModulePath).replace(n...
@@ -269,7 +269,7 @@ const devHtmlHook: IndexHtmlTransformHook = async ( preTransformRequest(server!, modulePath, decodedBase) } - await traverseHtml(html, filename, (node) => { + await traverseHtml(html, filename, config.logger.warn, (node) => { if (!nodeIsElement(node)) { return }
packages/vite/src/node/server/middlewares/indexHtml.ts
0
TypeScript
1
none
16
51
51
true
fix(html): allow control character in input stream
20,483
vitejs/vite
78,557
TypeScript
btea
import * as vue from 'vue' export default vue
No issues found.
import * as vue from 'vue' export default vue
@@ -0,0 +1,3 @@ +import * as vue from 'vue' + +export default vue
packages/vite/src/node/__tests__/fixtures/scan-jsx-runtime/entry-no-jsx.js
0
JavaScript
1
none
16
4
4
true
fix(optimizer): discover correct jsx runtime during scan
20,495
vitejs/vite
78,557
TypeScript
hi-ogawa
Promise.resolve(3), Promise.resolve([4, 5, 6]), ]) expect(arr).toEqual([1, 2, 3, 4, 5, 6]) }) test('2x nested promise array', async () => { const arr = await asyncFlatten([ 1, 2, Promise.resolve(3), Promise.resolve([4, 5, Promise.resolve(6), Promise.resolve([7, 8, 9]...
No issues found.
Promise.resolve(3), Promise.resolve([4, 5, 6]), ]) expect(arr).toEqual([1, 2, 3, 4, 5, 6]) }) test('2x nested promise array', async () => { const arr = await asyncFlatten([ 1, 2, Promise.resolve(3), Promise.resolve([4, 5, Promise.resolve(6), Promise.resolve([7, 8, 9]...
@@ -288,6 +288,9 @@ foo() // 2 // 3 `.trim() + const veryLongSource = Array.from({ length: 2000 }, (_, i) => `// ${i}`).join( + '\n', + ) const expectSnapshot = (value: string) => { try { @@ -340,6 +343,10 @@ foo() test('invalid start > end', () => { expectSnapshot(generateCodeFrame(source, 2,...
packages/vite/src/node/__tests__/utils.spec.ts
0
TypeScript
1
none
16
51
51
true
feat: support files with more than 1000 lines by `generateCodeFrame`
20,508
vitejs/vite
78,557
TypeScript
sapphi-red
// user config may provide an alternative mode. But --mode has a higher priority mode = inlineConfig.mode || config.mode || mode configEnv.mode = mode const filterPlugin = (p: Plugin | FalsyPlugin): p is Plugin => { if (!p) { return false } else if (!p.apply) { return true } else if (t...
No issues found.
// user config may provide an alternative mode. But --mode has a higher priority mode = inlineConfig.mode || config.mode || mode configEnv.mode = mode const filterPlugin = (p: Plugin | FalsyPlugin): p is Plugin => { if (!p) { return false } else if (!p.apply) { return true } else if (t...
@@ -1941,6 +1941,7 @@ async function bundleConfigFile( 'import.meta.url': importMetaUrlVarName, 'import.meta.dirname': dirnameVarName, 'import.meta.filename': filenameVarName, + 'import.meta.main': 'false', }, plugins: [ {
packages/vite/src/node/config.ts
0
TypeScript
1
none
16
51
51
true
feat: add `import.meta.main` support in config (bundle config loader)
20,516
vitejs/vite
78,557
TypeScript
Copilot
export async function render(url, rootDir) { const pathname = url.replace(/#[^#]*$/, '').replace(/\?[^?]*$/, '') const renderer = pathRenderers[pathname] if (renderer) { return await renderer(rootDir) } return '404' } async function renderRoot(rootDir) { const paths = Object.keys(pathRenderers).filter(...
No issues found.
export async function render(url, rootDir) { const pathname = url.replace(/#[^#]*$/, '').replace(/\?[^?]*$/, '') const renderer = pathRenderers[pathname] if (renderer) { return await renderer(rootDir) } return '404' } async function renderRoot(rootDir) { const paths = Object.keys(pathRenderers).filter(...
@@ -65,8 +65,10 @@ async function renderForkedDeadlockDynamicImports(rootDir) { async function renderImportMeta(rootDir) { const metaUrl = import.meta.url const resolveResult = import.meta.resolve('./app.js') + const metaMain = import.meta.main return ( `<div class="import-meta-url">${escapeHtml(metaUrl...
playground/ssr/src/app.js
0
JavaScript
1
none
16
51
51
true
feat(ssr): add `import.meta.main` support for Node.js module runner
20,517
vitejs/vite
78,557
TypeScript
Copilot
) fs.writeFileSync(filename, modified) } export function addFile(filename: string, content: string): void { const resolvedFilename = path.resolve(testDir, filename) fs.mkdirSync(path.dirname(resolvedFilename), { recursive: true }) fs.writeFileSync(resolvedFilename, content) } export function removeFile(file...
No issues found.
) fs.writeFileSync(filename, modified) } export function addFile(filename: string, content: string): void { const resolvedFilename = path.resolve(testDir, filename) fs.mkdirSync(path.dirname(resolvedFilename), { recursive: true }) fs.writeFileSync(resolvedFilename, content) } export function removeFile(file...
@@ -189,14 +189,14 @@ export function findAssetFile( base = '', assets = 'assets', matchAll = false, -): string { +): string | undefined { const assetsDir = path.join(testDir, 'dist', base, assets) let files: string[] try { files = fs.readdirSync(assetsDir) } catch (e) { if (e.code === 'E...
playground/test-utils.ts
0
TypeScript
1
none
16
51
51
true
fix(css): empty CSS entry points should generate CSS files, not JS files
20,518
vitejs/vite
78,557
TypeScript
Copilot
const { build } = await import('vite') await build({ root: rootDir, logLevel: 'silent', configFile: path.resolve(__dirname, '../vite.config.js'), }) await build({ root: rootDir, logLevel: 'warn', // output esbuild warns configFile: path.resolve(__dirname, '../vite.dy...
No issues found.
const { build } = await import('vite') await build({ root: rootDir, logLevel: 'silent', configFile: path.resolve(__dirname, '../vite.config.js'), }) await build({ root: rootDir, logLevel: 'warn', // output esbuild warns configFile: path.resolve(__dirname, '../vite.dy...
@@ -108,6 +108,12 @@ export async function serve(): Promise<{ close(): Promise<void> }> { configFile: path.resolve(__dirname, '../vite.css-code-split.config.js'), }) + await build({ + root: rootDir, + logLevel: 'warn', // output esbuild warns + configFile: path.resolve(__dirname, '../vit...
playground/lib/__tests__/serve.ts
0
TypeScript
1
none
16
51
51
true
feat(lib): enable minification but keep pure annotations for es output with terser
20,522
vitejs/vite
78,557
TypeScript
Copilot
} }) test('image-set() with svg', async () => { expect(await getBg('.css-image-set-svg')).toMatch(/data:image\/svg\+xml,.+/) }) test('url() with svg in .css?url', async () => { const bg = await getBg('.css-url-svg-in-url') expect(bg).toMatch(/data:image\/svg\+xml,.+/) expect(bg).toContain(...
No issues found.
} }) test('image-set() with svg', async () => { expect(await getBg('.css-image-set-svg')).toMatch(/data:image\/svg\+xml,.+/) }) test('url() with svg in .css?url', async () => { const bg = await getBg('.css-url-svg-in-url') expect(bg).toMatch(/data:image\/svg\+xml,.+/) expect(bg).toContain(...
@@ -40,6 +40,17 @@ test('should have no 404s', () => { }) }) +test.runIf(isBuild)( + 'should not warn about VITE_ASSET tokens in image-set', + async () => { + expect(serverLogs).toStrictEqual( + expect.not.arrayContaining([ + expect.stringMatching(/VITE_ASSET__.*?didn't resolve at build time/), +...
playground/assets/__tests__/assets.spec.ts
0
TypeScript
1
none
16
51
51
true
test(css): add test for #20520
20,541
vitejs/vite
78,557
TypeScript
Copilot
if (opts == null) { return {} } if (typeof opts !== 'object') { throw err( `Expected worker options to be an object, got ${typeof opts}`, optsStartIndex, ) } return opts } async function getWorkerType( raw: string, clean: string, i: number, ): Promise<WorkerType> { const co...
No issues found.
if (opts == null) { return {} } if (typeof opts !== 'object') { throw err( `Expected worker options to be an object, got ${typeof opts}`, optsStartIndex, ) } return opts } async function getWorkerType( raw: string, clean: string, i: number, ): Promise<WorkerType> { const co...
@@ -204,12 +204,6 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin { return environment.config.consumer === 'client' }, - shouldTransformCachedModule({ code }) { - if (isBuild && config.build.watch && workerImportMetaUrlRE.test(code)) { - return true - } - ...
packages/vite/src/node/plugins/workerImportMetaUrl.ts
0
TypeScript
1
none
16
51
51
true
perf(worker): rebuild only when affected
20,559
vitejs/vite
78,557
TypeScript
sapphi-red
describe('getHash', () => { test('8-digit hex', () => { const hash = getHash(Buffer.alloc(0)) expect(hash).toMatch(/^[\da-f]{8}$/) }) }) describe('asyncFlatten', () => { test('plain array', async () => { const arr = await asyncFlatten([1, 2, 3]) expect(arr).toEqual([1, 2, 3]) }) test('neste...
No issues found.
describe('getHash', () => { test('8-digit hex', () => { const hash = getHash(Buffer.alloc(0)) expect(hash).toMatch(/^[\da-f]{8}$/) }) }) describe('asyncFlatten', () => { test('plain array', async () => { const arr = await asyncFlatten([1, 2, 3]) expect(arr).toEqual([1, 2, 3]) }) test('neste...
@@ -347,6 +347,72 @@ foo() test('supports more than 1000 lines', () => { expectSnapshot(generateCodeFrame(veryLongSource, { line: 1200, column: 0 })) }) + + test('long line (start)', () => { + const longLine = 'a'.repeat(60) + 'b'.repeat(60) + 'c'.repeat(60) + const src = `${longLine}\nshort line\n${l...
packages/vite/src/node/__tests__/utils.spec.ts
0
TypeScript
1
none
16
51
51
true
feat: support long lines in `generateCodeFrame`
20,640
vitejs/vite
78,557
TypeScript
sapphi-red
const pureUrl = hasQueryDelimiter ? rawUrl.slice(0, queryDelimiterIndex) + '`' : rawUrl const queryString = hasQueryDelimiter ? rawUrl.slice(queryDelimiterIndex, -1) : '' const ast = this.parse(pureUrl) const templat...
No issues found.
const pureUrl = hasQueryDelimiter ? rawUrl.slice(0, queryDelimiterIndex) + '`' : rawUrl const queryString = hasQueryDelimiter ? rawUrl.slice(queryDelimiterIndex, -1) : '' const ast = this.parse(pureUrl) const templat...
@@ -56,7 +56,7 @@ export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin { id: { exclude: [exactRegex(preloadHelperId), exactRegex(CLIENT_ENTRY)], }, - code: /new\s+URL.+import\.meta\.url/, + code: /new\s+URL.+import\.meta\.url/s, }, async handl...
packages/vite/src/node/plugins/assetImportMetaUrl.ts
0
TypeScript
1
none
16
51
51
true
fix: support multiline new URL(..., import.meta.url) expressions
20,644
vitejs/vite
78,557
TypeScript
Copilot
test('successfully scaffolds a project based on vue starter template', () => { const { stdout } = run( [ projectName, '--interactive', '--no-immediate', '--template', 'vue', '--no-rolldown', ], { cwd: __dirname, }, ) const generatedFiles = fs.readdirSync(...
No issues found.
test('successfully scaffolds a project based on vue starter template', () => { const { stdout } = run( [ projectName, '--interactive', '--no-immediate', '--template', 'vue', '--no-rolldown', ], { cwd: __dirname, }, ) const generatedFiles = fs.readdirSync(...
@@ -151,6 +151,27 @@ test('successfully scaffolds a project with subfolder based on react starter tem expect(templateFilesReact).toEqual(generatedFiles) }) +test('successfully scaffolds a project based on react-compiler-ts starter template', () => { + const { stdout } = run([projectName, '--template', 'react-com...
packages/create-vite/__tests__/cli.spec.ts
0
TypeScript
1
none
16
51
51
true
feat(create-vite): support React Compiler
20,704
vitejs/vite
78,557
TypeScript
ArnaudBarre
test('prompts for the framework on supplying an invalid template', () => { const { stdout } = run([ projectName, '--interactive', '--template', 'unknown', ]) expect(stdout).toContain( `"unknown" isn't a valid template. Please choose from below:`, ) }) test('asks to overwrite non-empty targe...
No issues found.
test('prompts for the framework on supplying an invalid template', () => { const { stdout } = run([ projectName, '--interactive', '--template', 'unknown', ]) expect(stdout).toContain( `"unknown" isn't a valid template. Please choose from below:`, ) }) test('asks to overwrite non-empty targe...
@@ -110,9 +110,12 @@ test('asks to overwrite non-empty current directory', () => { }) test('successfully scaffolds a project based on vue starter template', () => { - const { stdout } = run([projectName, '--interactive', '--template', 'vue'], { - cwd: __dirname, - }) + const { stdout } = run( + [projectNam...
packages/create-vite/__tests__/cli.spec.ts
0
TypeScript
1
none
16
51
51
true
feat(create-vite): scaffold with rolldown-vite
20,739
vitejs/vite
78,557
TypeScript
sapphi-red
minifyWhitespace: true, }, }), 'es', ) expect(options).toEqual({ charset: 'utf8', loader: 'js', target: undefined, format: 'esm', keepNames: true, minify: false, minifyIdentifiers: true, minifySyntax: true, minifyWhitespace: fal...
No issues found.
minifyWhitespace: true, }, }), 'es', ) expect(options).toEqual({ charset: 'utf8', loader: 'js', target: undefined, format: 'esm', keepNames: true, minify: false, minifyIdentifiers: true, minifySyntax: true, minifyWhitespace: fal...
@@ -2,6 +2,7 @@ import path from 'node:path' import { describe, expect, test } from 'vitest' import type { ResolvedConfig, UserConfig } from '../../config' import { + injectEsbuildHelpers, resolveEsbuildTranspileOptions, transformWithEsbuild, } from '../../plugins/esbuild' @@ -397,6 +398,33 @@ describe('tran...
packages/vite/src/node/__tests__/plugins/esbuild.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(esbuild): inject esbuild helper functions with minified `$` variables correctly
20,761
vitejs/vite
78,557
TypeScript
james-od
const defaultFile = `${testDir}/${defaultFileName}` const depFileName = 'dep.ts' const depFile = `${testDir}/${depFileName}` const a = 'A0' let dep = 'dep0' beforeAll(async () => { await untilBrowserLogAfter( () => page.goto(`${viteTestUrl}/${testDir}/`), ...
No issues found.
const defaultFile = `${testDir}/${defaultFileName}` const depFileName = 'dep.ts' const depFile = `${testDir}/${depFileName}` const a = 'A0' let dep = 'dep0' beforeAll(async () => { await untilBrowserLogAfter( () => page.goto(`${viteTestUrl}/${testDir}/`), ...
@@ -997,6 +997,17 @@ if (!isBuild) { .toMatch('parent:child') }) + test('deleting import from non-self-accepting module can trigger prune event', async () => { + await page.goto(viteTestUrl) + await expect.poll(() => page.textContent('.prune')).toMatch('prune-init') + editFile('prune/dep1.js', (co...
playground/hmr/__tests__/hmr.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(hmr): trigger prune event when import is removed from non hmr module
20,768
vitejs/vite
78,557
TypeScript
hi-ogawa
resolveLibFilename( libOptions, 'es', entryAlias, resolve(__dirname, 'packages/name'), ), ) expect(fileName1).toBe('custom-filename.mjs') expect(fileName2).toBe('custom-filename.mjs') }) }) describe('resolveBuildOutputs', () => { test('default format: one en...
No issues found.
resolveLibFilename( libOptions, 'es', entryAlias, resolve(__dirname, 'packages/name'), ), ) expect(fileName1).toBe('custom-filename.mjs') expect(fileName2).toBe('custom-filename.mjs') }) }) describe('resolveBuildOutputs', () => { test('default format: one en...
@@ -865,6 +865,73 @@ test.for([true, false])( }, ) +test('sharedConfigBuild and emitAssets', async () => { + const root = resolve(__dirname, 'fixtures/shared-config-build/emitAssets') + const builder = await createBuilder({ + root, + logLevel: 'warn', + configFile: false, + environments: { + cl...
packages/vite/src/node/__tests__/build.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(build): fix ssr environment `emitAssets: true` when `sharedConfigBuild: true`
20,787
vitejs/vite
78,557
TypeScript
hi-ogawa
fs.mkdirSync(genPath, { recursive: true }) const { stdout } = run(['.', '--interactive'], { cwd: genPath }) expect(stdout).toContain('Select a framework:') }) test('prompts for the framework if none supplied', () => { const { stdout } = run([projectName, '--interactive']) expect(stdout).toContain('Select a f...
No issues found.
fs.mkdirSync(genPath, { recursive: true }) const { stdout } = run(['.', '--interactive'], { cwd: genPath }) expect(stdout).toContain('Select a framework:') }) test('prompts for the framework if none supplied', () => { const { stdout } = run([projectName, '--interactive']) expect(stdout).toContain('Select a f...
@@ -55,55 +55,62 @@ beforeAll(() => clearAnyPreviousFolders()) afterEach(() => clearAnyPreviousFolders()) test('prompts for the project name if none supplied', () => { - const { stdout } = run([]) + const { stdout } = run(['--interactive']) expect(stdout).toContain('Project name:') }) test('prompts for the...
packages/create-vite/__tests__/cli.spec.ts
0
TypeScript
1
none
16
51
51
true
feat(create-vite): add `--interactive` / `--no-interactive`
20,797
vitejs/vite
78,557
TypeScript
sapphi-red
}) export const namedEagerWithObjectKeys = Object.keys( import.meta.glob<string>('./modules/*.ts', { eager: true, import: 'name', }), ) export const namedEagerWithObjectValues = Object.values( import.meta.glob<string>('./modules/*.ts', { eager: true, import: 'name', }), ) export const namedDefa...
No issues found.
}) export const namedEagerWithObjectKeys = Object.keys( import.meta.glob<string>('./modules/*.ts', { eager: true, import: 'name', }), ) export const namedEagerWithObjectValues = Object.values( import.meta.glob<string>('./modules/*.ts', { eager: true, import: 'name', }), ) export const namedDefa...
@@ -120,3 +120,5 @@ export const customRootBase = import.meta.glob('./**/*.ts', { export const customBaseParent = import.meta.glob('/fixture-b/**/*.ts', { base: '/fixture-a', }) + +export const dotFolder = import.meta.glob('./.foo/*.ts', { eager: true })
packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts
0
TypeScript
1
none
16
51
51
true
fix(glob): handle glob imports from folders starting with dot
20,800
vitejs/vite
78,557
TypeScript
Copilot
resolveId(id) { if (id === virtualFile) { return virtualId } }, load(id) { if (id === virtualId) { return `export const msg = "[success] from conventional virtual file"` } }, }, { name: 'virtual-module-9036', resolveId(id) {...
No issues found.
resolveId(id) { if (id === virtualFile) { return virtualId } }, load(id) { if (id === virtualId) { return `export const msg = "[success] from conventional virtual file"` } }, }, { name: 'virtual-module-9036', resolveId(id) {...
@@ -10,6 +10,9 @@ const virtualId9036 = '\0' + virtualFile9036 const customVirtualFile = '@custom-virtual-file' +const virtualFileWithScheme = 'virtual-with-scheme' +const virtualIdWithScheme = '\0https://example.com/virtual.js' + const generatedContentVirtualFile = '@generated-content-virtual-file' const genera...
playground/resolve/vite.config.js
0
JavaScript
1
none
16
51
51
true
fix: keep ids for virtual modules as-is
20,808
vitejs/vite
78,557
TypeScript
sapphi-red
import { type Connect, defineConfig } from 'vite' export default defineConfig({ base: './', build: { outDir: 'dist/nested', rollupOptions: { preserveEntrySignatures: 'strict', input: { plugin: path.resolve(import.meta.dirname, './index.ts'), }, output: { format: 'amd...
No issues found.
import { type Connect, defineConfig } from 'vite' export default defineConfig({ base: './', build: { outDir: 'dist/nested', rollupOptions: { preserveEntrySignatures: 'strict', input: { plugin: path.resolve(import.meta.dirname, './index.ts'), }, output: { format: 'amd...
@@ -0,0 +1,53 @@ +import fs from 'node:fs/promises' +import path from 'node:path' +import { type Connect, defineConfig } from 'vite' + +export default defineConfig({ + base: './', + build: { + outDir: 'dist/nested', + rollupOptions: { + preserveEntrySignatures: 'strict', + input: { + plugin: pa...
playground/amd/vite.config.ts
0
TypeScript
1
none
16
51
51
true
fix(build): ensure amd bundles request `require` to be injected
20,861
vitejs/vite
78,557
TypeScript
dschmidt
const kw = await page.$('html:last-child') expect(await kw.innerHTML()).toMatch(`<!-- this is appended to body -->`) }) }) describe('Unicode path', () => { test('direct access', async () => { await page.goto( viteTestUrl + '/unicode-path/中文-にほんご-한글-🌕🌖🌗/index.html', ) expect(await page...
No issues found.
const kw = await page.$('html:last-child') expect(await kw.innerHTML()).toMatch(`<!-- this is appended to body -->`) }) }) describe('Unicode path', () => { test('direct access', async () => { await page.goto( viteTestUrl + '/unicode-path/中文-にほんご-한글-🌕🌖🌗/index.html', ) expect(await page...
@@ -273,6 +273,16 @@ describe('link with props', () => { }) }) +describe.runIf(isServe)('SPA fallback', () => { + test('should serve index.html via page navigation even when path matches file basename', async () => { + const response = await page.goto(viteTestUrl + '/test') + expect(response.status()).toBe...
playground/html/__tests__/html.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(dev): skip JS responses for document requests
20,866
vitejs/vite
78,557
TypeScript
sapphi-red
import isModuleSyncConditionEnabled from '#module-sync-enabled' import { configDefaults } from './config' import { tryNodeResolve } from './plugins/resolve' import { nodeLikeBuiltins } from './utils' export interface NodeResolveWithViteOptions { root: string isRequire?: boolean } /** * Resolve like Node.js using...
No issues found.
import isModuleSyncConditionEnabled from '#module-sync-enabled' import { configDefaults } from './config' import { tryNodeResolve } from './plugins/resolve' import { nodeLikeBuiltins } from './utils' export interface NodeResolveWithViteOptions { root: string isRequire?: boolean } /** * Resolve like Node.js using...
@@ -0,0 +1,41 @@ +import isModuleSyncConditionEnabled from '#module-sync-enabled' +import { configDefaults } from './config' +import { tryNodeResolve } from './plugins/resolve' +import { nodeLikeBuiltins } from './utils' + +export interface NodeResolveWithViteOptions { + root: string + isRequire?: boolean +} + +/** +...
packages/vite/src/node/nodeResolve.ts
0
TypeScript
1
none
16
42
42
true
fix: use esm entrypoint for css preprocessors and terser
20,918
vitejs/vite
78,557
TypeScript
bluwy
locals: [], } } if (node.type === 'ExportAllDeclaration') { if (!node.source) return undefined return { id: node.source.value, bindings: ['*'], locals: [] } } } function getAllImportBindings(ast: Program): ImportBindings[] { return ast.body.flatMap((node) => getImportBindings(node) ?? []) } ...
No issues found.
locals: [], } } if (node.type === 'ExportAllDeclaration') { if (!node.source) return undefined return { id: node.source.value, bindings: ['*'], locals: [] } } } function getAllImportBindings(ast: Program): ImportBindings[] { return ast.body.flatMap((node) => getImportBindings(node) ?? []) } ...
@@ -1,5 +1,4 @@ import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' import { builtinModules } from 'node:module' import { defineConfig } from 'rolldown' import type { @@ -20,15 +19,15 @@ import type { Statement, } from '@oxc-project/types' -const depTypesDir = new URL('./src/types...
packages/vite/rolldown.dts.config.ts
0
TypeScript
1
none
16
51
51
true
refactor: use subpath imports for types module reference
20,921
vitejs/vite
78,557
TypeScript
bluwy
const windowsDriveRE = /^[A-Z]:/ const replaceWindowsDriveRE = /^([A-Z]):\// const linuxAbsolutePathRE = /^\/[^/]/ function escapeToLinuxLikePath(path: string) { if (windowsDriveRE.test(path)) { return path.replace(replaceWindowsDriveRE, '/windows/$1/') } if (linuxAbsolutePathRE.test(path)) { return `/lin...
No issues found.
const windowsDriveRE = /^[A-Z]:/ const replaceWindowsDriveRE = /^([A-Z]):\// const linuxAbsolutePathRE = /^\/[^/]/ function escapeToLinuxLikePath(path: string) { if (windowsDriveRE.test(path)) { return path.replace(replaceWindowsDriveRE, '/windows/$1/') } if (linuxAbsolutePathRE.test(path)) { return `/lin...
@@ -30,6 +30,7 @@ import { withTrailingSlash, } from '../shared/utils' import { VALID_ID_PREFIX } from '../shared/constants' +import { createIsBuiltin } from '../shared/builtin' import { CLIENT_ENTRY, CLIENT_PUBLIC_PATH, @@ -117,20 +118,6 @@ export function isBuiltin(builtins: (string | RegExp)[], id: strin...
packages/vite/src/node/utils.ts
0
TypeScript
1
none
16
51
51
true
perf(module-runner): add client-side builtin module check
20,924
vitejs/vite
78,557
TypeScript
jiji-hoon96
(source[start] === '"' || source[start] === "'" || source[start] === '`') ) { needPreloadHelper = true const { declaration, names } = dynamicImports[expEnd] || {} if (names) { /* transform `const {foo} = await import('fo...
No issues found.
(source[start] === '"' || source[start] === "'" || source[start] === '`') ) { needPreloadHelper = true const { declaration, names } = dynamicImports[expEnd] || {} if (names) { /* transform `const {foo} = await import('fo...
@@ -711,11 +711,15 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin { source: chunk.fileName, hires: 'boundary', }) + const originalFile = chunk.map.file const map = combineSourcemaps(chunk.fileName, [ ...
packages/vite/src/node/plugins/importAnalysisBuild.ts
0
TypeScript
1
none
16
51
51
true
fix: preserve original sourcemap file field when combining sourcemaps
20,926
vitejs/vite
78,557
TypeScript
jiji-hoon96
'firefox104', 'safari16', ] export const DEFAULT_CONFIG_FILES: string[] = [ 'vite.config.js', 'vite.config.mjs', 'vite.config.ts', 'vite.config.cjs', 'vite.config.mts', 'vite.config.cts', ] export const JS_TYPES_RE: RegExp = /\.(?:j|t)sx?$|\.mjs$/ export const CSS_LANGS_RE: RegExp = /\.(css|less|sa...
No issues found.
'firefox104', 'safari16', ] export const DEFAULT_CONFIG_FILES: string[] = [ 'vite.config.js', 'vite.config.mjs', 'vite.config.ts', 'vite.config.cjs', 'vite.config.mts', 'vite.config.cts', ] export const JS_TYPES_RE: RegExp = /\.(?:j|t)sx?$|\.mjs$/ export const CSS_LANGS_RE: RegExp = /\.(css|less|sa...
@@ -7,7 +7,7 @@ const { version } = JSON.parse( readFileSync(new URL('../../package.json', import.meta.url)).toString(), ) -export const ROLLUP_HOOKS = [ +export const ROLLUP_HOOKS: RollupPluginHooks[] = [ 'options', 'buildStart', 'buildEnd', @@ -35,7 +35,7 @@ export const ROLLUP_HOOKS = [ 'shouldTran...
packages/vite/src/node/constants.ts
0
TypeScript
1
none
16
51
51
true
build: use isolated declarations
20,928
vitejs/vite
78,557
TypeScript
bluwy
import 'node:path' export default function testStack() { innerTestStack() } import 'node:util' function innerTestStack() { throw new Error('__TEST_STACK_TRANSPILED_INLINE__') } //# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidHJhbnNwaWxlZC1pbmxpbmUudHMiXSwKICAic291cmNlc...
No issues found.
import 'node:path' export default function testStack() { innerTestStack() } import 'node:util' function innerTestStack() { throw new Error('__TEST_STACK_TRANSPILED_INLINE__') } //# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidHJhbnNwaWxlZC1pbmxpbmUudHMiXSwKICAic291cmNlc...
@@ -0,0 +1,9 @@ +import 'node:path' +export default function testStack() { + innerTestStack() +} +import 'node:util' +function innerTestStack() { + throw new Error('__TEST_STACK_TRANSPILED_INLINE__') +} +//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidHJhbnNwaWxlZC1pbmxp...
packages/vite/src/node/ssr/runtime/__tests__/fixtures/pre-source-mapped-file.js
0
JavaScript
1
none
16
10
10
true
fix(module-runner): resolve `resolvedSources` correctly
20,959
vitejs/vite
78,557
TypeScript
sheremet-va
plugins: [keepScreenMergePlugin()], clearScreen: true, } const results1 = await resolveConfig(config1, 'build') const results2 = await resolveConfig(config2, 'build') expect(results1.clearScreen).toBe(false) expect(results2.clearScreen).toBe(false) }) test('plugin overrides `clear...
No issues found.
plugins: [keepScreenMergePlugin()], clearScreen: true, } const results1 = await resolveConfig(config1, 'build') const results2 = await resolveConfig(config2, 'build') expect(results1.clearScreen).toBe(false) expect(results2.clearScreen).toBe(false) }) test('plugin overrides `clear...
@@ -839,7 +839,7 @@ describe('loadConfigFromFile', () => { `) }) - test('import.meta.main is correctly set', async () => { + test('import.meta properties are supported', async () => { const { config } = (await loadConfigFromFile( {} as any, path.resolve(fixtures, './import-meta/vite.con...
packages/vite/src/node/__tests__/config.spec.ts
0
TypeScript
1
none
16
51
51
true
feat: add `import.meta.resolve` support for ESM config (bundle config loader)
20,962
vitejs/vite
78,557
TypeScript
sapphi-red
handler(value.data, client) } } handlerToWorkerListener.set(handler, listener) worker.on('message', listener) }, off: (event, handler: HotChannelListener) => { if (event === 'vite:client:connect') return if (event === 'vite:client:disconnect') { const list...
No issues found.
handler(value.data, client) } } handlerToWorkerListener.set(handler, listener) worker.on('message', listener) }, off: (event, handler: HotChannelListener) => { if (event === 'vite:client:connect') return if (event === 'vite:client:disconnect') { const list...
@@ -4,35 +4,53 @@ import type { HotChannel, HotChannelListener, HotPayload } from 'vite' import { DevEnvironment } from '../../..' import { createServer } from '../../../server' -const createWorkerTransport = (w: Worker): HotChannel => { +const createWorkerTransport = (worker: Worker): HotChannel => { const hand...
packages/vite/src/node/ssr/runtime/__tests__/server-worker-runner.spec.ts
0
TypeScript
1
none
16
51
51
true
feat: add vite client connect events
20,978
vitejs/vite
78,557
TypeScript
sapphi-red
* Opt-in this plugin into per-environment buildStart and buildEnd during dev. * For backward-compatibility, the buildStart hook is called only once during * dev, for the client environment. Plugins can opt-in to be called * per-environment, aligning with the build hook behavior. * @experimental */ p...
No issues found.
* Opt-in this plugin into per-environment buildStart and buildEnd during dev. * For backward-compatibility, the buildStart hook is called only once during * dev, for the client environment. Plugins can opt-in to be called * per-environment, aligning with the build hook behavior. * @experimental */ p...
@@ -176,6 +176,14 @@ export interface Plugin<A = any> extends RollupPlugin<A> { * @experimental */ perEnvironmentStartEndDuringDev?: boolean + /** + * Opt-in this plugin into per-environment watchChange during dev. + * For backward-compatibility, the watchChange hook is called only once during + * dev...
packages/vite/src/node/plugin.ts
0
TypeScript
1
none
16
51
51
true
feat: add `perEnvironmentWatchChangeDuringDev`
20,996
vitejs/vite
78,557
TypeScript
sapphi-red
beforeAll(async () => { await untilBrowserLogAfter( () => page.goto(`${viteTestUrl}/${testDir}/`), [CONNECTED, />>>>>>/], (logs) => { expect(logs).toContain(`<<< named: ${a} ; ${dep}`) expect(logs).toContain(`<<< default: def0`) expect(log...
No issues found.
beforeAll(async () => { await untilBrowserLogAfter( () => page.goto(`${viteTestUrl}/${testDir}/`), [CONNECTED, />>>>>>/], (logs) => { expect(logs).toContain(`<<< named: ${a} ; ${dep}`) expect(logs).toContain(`<<< default: def0`) expect(log...
@@ -1022,9 +1022,17 @@ if (!isBuild) { editFile('prune/dep1.js', (code) => code.replace(`import './dep2.js'`, `// import './dep2.js'`), ) + // Prune is triggered when there are other dependencies. await expect .poll(() => page.textContent('.prune')) .toMatch('prune-init|dep2-dispo...
playground/hmr/__tests__/hmr.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(hmr): trigger prune event when last import is removed (#20781)
21,093
vitejs/vite
78,557
TypeScript
almadoro
const buffer = await response.arrayBuffer() return WebAssembly.instantiate(buffer, opts) } } const instantiateFromUrlCode = instantiateFromUrl.toString() const instantiateFromFile = async ( fileUrlString: string, opts?: WebAssembly.Imports, ) => { const { readFile } = await import('node:fs/promises') ...
No issues found.
const buffer = await response.arrayBuffer() return WebAssembly.instantiate(buffer, opts) } } const instantiateFromUrlCode = instantiateFromUrl.toString() const instantiateFromFile = async ( fileUrlString: string, opts?: WebAssembly.Imports, ) => { const { readFile } = await import('node:fs/promises') ...
@@ -1,11 +1,17 @@ +import MagicString from 'magic-string' import { exactRegex } from 'rolldown/filter' -import type { Plugin } from '../plugin' -import { fileToUrl } from './asset' +import type { BindingMagicString } from 'rolldown' +import { createToImportMetaURLBasedRelativeRuntime } from '../build' +import { type P...
packages/vite/src/node/plugins/wasm.ts
0
TypeScript
1
none
16
51
51
true
feat(wasm): add SSR support for `.wasm?init`
21,102
vitejs/vite
78,557
TypeScript
upsuper
): Promise<PreviewServer> { const config = await resolveConfig( inlineConfig, 'serve', 'production', 'production', true, ) const clientOutDir = config.environments.client.build.outDir const distDir = path.resolve(config.root, clientOutDir) if ( !fs.existsSync(distDir) && // error ...
No issues found.
): Promise<PreviewServer> { const config = await resolveConfig( inlineConfig, 'serve', 'production', 'production', true, ) const clientOutDir = config.environments.client.build.outDir const distDir = path.resolve(config.root, clientOutDir) if ( !fs.existsSync(distDir) && // error ...
@@ -1,5 +1,6 @@ import fs from 'node:fs' import path from 'node:path' +import type readline from 'node:readline' import sirv from 'sirv' import compression from '@polka/compression' import connect from 'connect' @@ -107,6 +108,14 @@ export interface PreviewServer { * Bind CLI shortcuts */ bindCLIShortcu...
packages/vite/src/node/preview.ts
0
TypeScript
1
none
16
51
51
true
fix: allow multiple `bindCLIShortcuts` calls with shortcut merging
21,103
vitejs/vite
78,557
TypeScript
edmundhung
const results2 = await resolveConfig(config2, 'build') expect(results1.clearScreen).toBe(false) expect(results2.clearScreen).toBe(false) }) test('plugin overrides `clearScreen` option', async () => { const config1: InlineConfig = { plugins: [keepScreenOverridePlugin()] } const config2: InlineC...
No issues found.
const results2 = await resolveConfig(config2, 'build') expect(results1.clearScreen).toBe(false) expect(results2.clearScreen).toBe(false) }) test('plugin overrides `clearScreen` option', async () => { const config1: InlineConfig = { plugins: [keepScreenOverridePlugin()] } const config2: InlineC...
@@ -854,6 +854,17 @@ describe('loadConfigFromFile', () => { expect(c.resolved).toBe(c.url) }) + test('shebang is preserved at the top of the file', async () => { + const { config } = (await loadConfigFromFile( + {} as any, + path.resolve(fixtures, './shebang/vite.config.ts'), + path.resolve...
packages/vite/src/node/__tests__/config.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(config): handle shebang properly
21,158
vitejs/vite
78,557
TypeScript
sapphi-red
import { fileURLToPath } from 'node:url' import { expect, test } from 'vitest' import { createServer } from '../../server' const root = fileURLToPath(new URL('./', import.meta.url)) async function createDevServer() { const server = await createServer({ configFile: false, root, logLevel: 'silent', op...
No issues found.
import { fileURLToPath } from 'node:url' import { expect, test } from 'vitest' import { createServer } from '../../server' const root = fileURLToPath(new URL('./', import.meta.url)) async function createDevServer() { const server = await createServer({ configFile: false, root, logLevel: 'silent', op...
@@ -1,5 +1,5 @@ import { fileURLToPath } from 'node:url' -import { test } from 'vitest' +import { expect, test } from 'vitest' import { createServer } from '../../server' const root = fileURLToPath(new URL('./', import.meta.url)) @@ -22,8 +22,26 @@ test('call rewriteStacktrace twice', async () => { for (let i =...
packages/vite/src/node/ssr/__tests__/ssrStacktrace.spec.ts
0
TypeScript
1
none
16
48
48
true
feat(ssr): avoid errors when rewriting already rewritten stacktrace
21,269
vitejs/vite
78,557
TypeScript
sapphi-red
if (opts == null) { return {} } if (typeof opts !== 'object') { throw err( `Expected worker options to be an object, got ${typeof opts}`, optsStartIndex, ) } return opts } async function getWorkerType( raw: string, clean: string, i: number, ): Promise<WorkerType> { const com...
No issues found.
if (opts == null) { return {} } if (typeof opts !== 'object') { throw err( `Expected worker options to be an object, got ${typeof opts}`, optsStartIndex, ) } return opts } async function getWorkerType( raw: string, clean: string, i: number, ): Promise<WorkerType> { const com...
@@ -209,7 +209,7 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin { let s: MagicString | undefined const cleanString = stripLiteral(code) const workerImportMetaUrlRE = - /\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*...
packages/vite/src/node/plugins/workerImportMetaUrl.ts
0
TypeScript
1
none
16
51
51
true
fix(worker): handle `new Worker(..., new URL(import.meta.url))` with trailing comma
21,325
vitejs/vite
78,557
TypeScript
Copilot
import { getCompatibleVersions } from 'baseline-browser-mapping' // Update on each major release const targetDate = '2026-01-01' // https://esbuild.github.io/api/#target const baselineToEsbuildTargetMap: Record<string, string> = { chrome: 'chrome', edge: 'edge', firefox: 'firefox', safari: 'safari', safari_...
No issues found.
import { getCompatibleVersions } from 'baseline-browser-mapping' // Update on each major release const targetDate = '2026-01-01' // https://esbuild.github.io/api/#target const baselineToEsbuildTargetMap: Record<string, string> = { chrome: 'chrome', edge: 'edge', firefox: 'firefox', safari: 'safari', safari_...
@@ -4,18 +4,33 @@ import { getCompatibleVersions } from 'baseline-browser-mapping' const targetDate = '2026-01-01' // https://esbuild.github.io/api/#target +const baselineToEsbuildTargetMap: Record<string, string> = { + chrome: 'chrome', + edge: 'edge', + firefox: 'firefox', + safari: 'safari', + safari_ios: '...
packages/vite/scripts/generateTarget.ts
0
TypeScript
1
none
16
38
38
true
feat: add ios to default esbuild targets
21,342
vitejs/vite
78,557
TypeScript
illusionaries
return ( SYMBOL_RESOLVED_CONFIG in inlineConfig && inlineConfig[SYMBOL_RESOLVED_CONFIG] ) } export async function resolveConfig( inlineConfig: InlineConfig, command: 'build' | 'serve', defaultMode = 'development', defaultNodeEnv = 'development', isPreview = false, /** @internal */ patchConfig...
No issues found.
return ( SYMBOL_RESOLVED_CONFIG in inlineConfig && inlineConfig[SYMBOL_RESOLVED_CONFIG] ) } export async function resolveConfig( inlineConfig: InlineConfig, command: 'build' | 'serve', defaultMode = 'development', defaultNodeEnv = 'development', isPreview = false, /** @internal */ patchConfig...
@@ -829,6 +829,8 @@ const configDefaults = Object.freeze({ // entries /** @experimental */ force: false, + /** @experimental */ + ignoreOutdatedRequests: false, }, ssr: ssrConfigDefaults, environments: {},
packages/vite/src/node/config.ts
0
TypeScript
1
none
16
51
51
true
feat: add `ignoreOutdatedRequests` option to `optimizeDeps`
21,364
vitejs/vite
78,557
TypeScript
jamesopstad
const envProxy = new Proxy({} as any, { get(_, p) { throw new Error( `[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`, ) }, }) export function createDefaultImportMeta( modulePath: string, ): ModuleRunnerImportMeta { const...
No issues found.
const envProxy = new Proxy({} as any, { get(_, p) { throw new Error( `[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`, ) }, }) export function createDefaultImportMeta( modulePath: string, ): ModuleRunnerImportMeta { const...
@@ -1,8 +1,5 @@ import { isWindows } from '../shared/utils' -import { - type ImportMetaResolver, - createImportMetaResolver, -} from './importMetaResolver' +import { createImportMetaResolver } from './importMetaResolver' import type { ModuleRunnerImportMeta } from './types' import { posixDirname, posixPathToFileHr...
packages/vite/src/module-runner/createImportMeta.ts
0
TypeScript
1
none
16
51
51
true
fix(module-runner): use `process.getBuiltinModule` instead of `import('node:module')`
21,402
vitejs/vite
78,557
TypeScript
sheremet-va
const icon = new URL('./icons/search.svg', import.meta.url) const worker = new URL('./worker.js', import.meta.url) const wasm = new URL('./module.wasm', import.meta.url) ` expect(await transform(code, '/root/node_modules/my-lib/dist/index.js')) .toMatchInlineSnapshot(` " ...
No issues found.
const icon = new URL('./icons/search.svg', import.meta.url) const worker = new URL('./worker.js', import.meta.url) const wasm = new URL('./module.wasm', import.meta.url) ` expect(await transform(code, '/root/node_modules/my-lib/dist/index.js')) .toMatchInlineSnapshot(` " ...
@@ -0,0 +1,132 @@ +import { describe, expect, test } from 'vitest' +import { rolldownDepPlugin } from '../../optimizer/rolldownDepPlugin' +import { normalizePath } from '../../utils' + +async function createRolldownDepPluginTransform(cacheDir: string) { + const baseConfig = { + cacheDir: normalizePath(cacheDir), + ...
packages/vite/src/node/__tests__/optimizer/rolldownDepPlugin.spec.ts
0
TypeScript
1
none
16
51
51
true
fix(optimizer): map relative `new URL` paths to correct relative file location
21,434
vitejs/vite
78,557
TypeScript
guyco3
import { h } from 'vue' import TwoslashFloatingVue from '@shikijs/vitepress-twoslash/client' import '@shikijs/vitepress-twoslash/style.css' import 'virtual:group-icons.css' import Theme from '@voidzero-dev/vitepress-theme/src/vite' import './styles.css' // components import SvgImage from './components/SvgImage.vue' im...
No issues found.
import { h } from 'vue' import TwoslashFloatingVue from '@shikijs/vitepress-twoslash/client' import '@shikijs/vitepress-twoslash/style.css' import 'virtual:group-icons.css' import Theme from '@voidzero-dev/vitepress-theme/src/vite' import './styles.css' // components import SvgImage from './components/SvgImage.vue' im...
@@ -10,6 +10,7 @@ import SvgImage from './components/SvgImage.vue' import YouTubeVideo from './components/YouTubeVideo.vue' import NonInheritBadge from './components/NonInheritBadge.vue' import AsideSponsors from './components/AsideSponsors.vue' +import ScrimbaLink from './components/ScrimbaLink.vue' export defau...
docs/.vitepress/theme/index.ts
0
TypeScript
1
none
16
33
33
true
docs: add Scrimba tutorial links across documentation
21,467
vitejs/vite
78,557
TypeScript
perborgen
minify: false, }, plugins: [ testVue(), notjs(), virtualModulePlugin(), { name: 'test-astro', transform(code, id) { if (id.endsWith('.astro')) { code = `export default {}` return { code } } }, }, ], }) // Handles Test.vue in dep-linke...
No issues found.
minify: false, }, plugins: [ testVue(), notjs(), virtualModulePlugin(), { name: 'test-astro', transform(code, id) { if (id.endsWith('.astro')) { code = `export default {}` return { code } } }, }, ], }) // Handles Test.vue in dep-linke...
@@ -57,22 +57,6 @@ export default defineConfig({ testVue(), notjs(), virtualModulePlugin(), - // for axios request test - { - name: 'mock', - configureServer({ middlewares }) { - middlewares.use('/ping', (_, res) => { - res.statusCode = 200 - res.end('pong') - ...
playground/optimize-deps/vite.config.js
0
JavaScript
1
none
16
51
51
true
test(optimize-deps): replace `axios` dependency with local package
21,490
vitejs/vite
78,557
TypeScript
Copilot
url, ), } const contents = sourceMap.map?.map.sourcesContent // Load all sources stored inline with the source map into the file cache // to pretend like they are already loaded. They may not exist on disk. if (sourceMap.map && contents) { sourceMap.map.resolvedS...
No issues found.
url, ), } const contents = sourceMap.map?.map.sourcesContent // Load all sources stored inline with the source map into the file cache // to pretend like they are already loaded. They may not exist on disk. if (sourceMap.map && contents) { sourceMap.map.resolvedS...
@@ -358,8 +358,8 @@ function wrapCallSite(frame: CallSite, state: State) { // from getScriptNameOrSourceURL() instead const source = frame.getFileName() || frame.getScriptNameOrSourceURL() if (source) { - const line = frame.getLineNumber() as number - const column = (frame.getColumnNumber() as number) - ...
packages/vite/src/module-runner/sourcemap/interceptor.ts
0
TypeScript
1
none
16
51
51
true
fix(module-runner): prevent crash on negative column in stacktrace
21,585
vitejs/vite
78,557
TypeScript
AriPerkkio
function writeTypesPlugin(): Plugin { return { name: 'write-types', async writeBundle() { if (this.meta.watchMode) { writeFileSync( 'dist/node/index.d.ts', "export * from '../../src/node/index.ts'", ) writeFileSync( 'dist/node/module-runner.d.ts', ...
No issues found.
function writeTypesPlugin(): Plugin { return { name: 'write-types', async writeBundle() { if (this.meta.watchMode) { writeFileSync( 'dist/node/index.d.ts', "export * from '../../src/node/index.ts'", ) writeFileSync( 'dist/node/module-runner.d.ts', ...
@@ -81,12 +81,12 @@ const nodeConfig = defineConfig({ 'fsevents', /^rolldown\//, /^tsx\//, + /^@vitejs\/devtools\//, /^#/, 'sugarss', // postcss-import -> sugarss 'supports-color', 'utf-8-validate', // ws 'bufferutil', // ws - '@vitejs/devtools/cli-commands', ...Object...
packages/vite/rolldown.config.ts
0
TypeScript
1
none
16
51
51
true
refactor: use internal devtools config
21,609
vitejs/vite
78,557
TypeScript
webfansplz
import { expect, test, vi } from 'vitest' import { browserLogs, isServe, page, serverLogs, viteTestUrl } from '~utils' test('proxy-bypass', async () => { await vi.waitFor(() => { expect(browserLogs.join('\n')).toContain('status of 404 (Not Found)') }) }) test('async-proxy-bypass', async () => { const conten...
No issues found.
import { expect, test, vi } from 'vitest' import { browserLogs, isServe, page, serverLogs, viteTestUrl } from '~utils' test('proxy-bypass', async () => { await vi.waitFor(() => { expect(browserLogs.join('\n')).toContain('status of 404 (Not Found)') }) }) test('async-proxy-bypass', async () => { const conten...
@@ -1,5 +1,5 @@ import { expect, test, vi } from 'vitest' -import { browserLogs, page, serverLogs } from '~utils' +import { browserLogs, isServe, page, serverLogs, viteTestUrl } from '~utils' test('proxy-bypass', async () => { await vi.waitFor(() => { @@ -17,3 +17,8 @@ test('async-proxy-bypass-with-error', async...
playground/proxy-bypass/__tests__/proxy-bypass.spec.ts
0
TypeScript
1
none
16
25
25
true
fix(dev): return "502 Bad Gateway" on proxy failures instead of 500
21,652
vitejs/vite
78,557
TypeScript
Copilot
fs.writeFileSync(filename, modified) } export function addFile(filename: string, content: string): void { const resolvedFilename = path.resolve(testDir, filename) fs.mkdirSync(path.dirname(resolvedFilename), { recursive: true }) fs.writeFileSync(resolvedFilename, content) } export function removeFile(filename...
No issues found.
fs.writeFileSync(filename, modified) } export function addFile(filename: string, content: string): void { const resolvedFilename = path.resolve(testDir, filename) fs.mkdirSync(path.dirname(resolvedFilename), { recursive: true }) fs.writeFileSync(resolvedFilename, content) } export function removeFile(filename...
@@ -121,6 +121,25 @@ export async function getBg( return el.evaluate((el) => getComputedStyle(el as Element).backgroundImage) } +/** + * Unlike `getBg`, this function returns the raw value of the `background-image` CSS property. + * + * `getBg` returns the resolved value, which has the hostname and port prepended...
playground/test-utils.ts
0
TypeScript
1
none
16
51
51
true
fix(css): apply `server.origin` to public file URLs in CSS (fix #18457)
21,697
vitejs/vite
78,557
TypeScript
SalvatoreT
autoscaler := &Autoscaler{metricsClient: metricsClient} return &KpaAutoscaler{ Autoscaler: autoscaler, panicTime: panicTime, maxPanicPods: int32(readyPodsCount), delayWindow: delayWindow, deciderSpec: spec, }, nil } // Scale implements Scaler interface in KpaAutoscaler. // Refer to knative-serving...
Should we create a separate autoscaler for APA?
// accumulate enough data to make conscious decisions. var panicTime time.Time if readyPodsCount > 1 { panicTime = time.Now() } else { panicTime = time.Time{} // Zero value for time if not in panic mode } // TODO missing MetricClient metricsClient := metrics.NewKPAMetricsClient() autoscaler := &Autoscale...
@@ -171,9 +181,41 @@ func NewKpaAutoscaler(readyPodsCount int, spec *DeciderKpaSpec) (*KpaAutoscaler, }, nil } +// APA_Scale references and enhances the algorithm in the following paper:. +// +// Huo, Qizheng, et al. "High Concurrency Response Strategy based on Kubernetes Horizontal Pod Autoscaler." +// Journal ...
pkg/controller/podautoscaler/scaler/kpa.go
26
Go
0.143
question
47
51
51
false
Add AIBrix Custom Autoscaling Algorithm APA
223
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
// For more details, check Reconcile and its Result here: // - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.17.3/pkg/reconcile func (r *PodAutoscalerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { // Implement a timeout for the reconciliation process. ctx, cancel := context...
Let's have some discussion here. I think we should create a new autoscaler. I understand some common parts have been implemented. We just need to figure out the long term plan. It looks good to me for short term
// For more details, check Reconcile and its Result here: // - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.17.3/pkg/reconcile func (r *PodAutoscalerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { // Implement a timeout for the reconciliation process. ctx, cancel := context...
@@ -144,10 +144,8 @@ func (r *PodAutoscalerReconciler) Reconcile(ctx context.Context, req ctrl.Reques switch pa.Spec.ScalingStrategy { case autoscalingv1alpha1.HPA: return r.reconcileHPA(ctx, pa) - case autoscalingv1alpha1.KPA: + case autoscalingv1alpha1.KPA, autoscalingv1alpha1.APA: return r.reconcileKPA(ctx...
pkg/controller/podautoscaler/podautoscaler_controller.go
26
Go
0.5
suggestion
211
51
51
false
Add AIBrix Custom Autoscaling Algorithm APA
223
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
# Update job's status to job manager job_id = self._due_jobs_list[i][0] self._inactive_jobs.add(job_id) print("======> ", job_id, "expired.") self._due_jobs_list = self._due_jobs_list[idx:] else: print("Unsupported schedulin...
Seems this is how to use to use the job scheduler Should it be examples like a comments? or testing files? why do we list here as prod codes?
print("Number of expired jobs is ", idx) for i in range(idx): # Update job's status to job manager job_id = self._due_jobs_list[i][0] self._inactive_jobs.add(job_id) print("======> ", job_id, "expired.") self._due_jobs_l...
@@ -0,0 +1,137 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software ...
python/aibrix/aibrix/batch/scheduler.py
26
Python
0.429
question
144
43
26
false
[batch] job FIFO scheduler as baseline
231
vllm-project/aibrix
2,572
Go
Jeffwan
xinchen384
""" self._jobs_queue are all the jobs. self._due_jobs_list stores all potential jobs that can be marked as expired jobs. self._inactive_jobs are jobs that are already invalid. """ self.interval = EXPIRE_INTERVAL self._jobs_queue = queue.Queue() sel...
sorting logic looks good to me
""" self._jobs_queue are all the jobs. self._due_jobs_list stores all potential jobs that can be marked as expired jobs. self._inactive_jobs are jobs that are already invalid. """ self.interval = EXPIRE_INTERVAL self._jobs_queue = queue.Queue() sel...
@@ -0,0 +1,137 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software ...
python/aibrix/aibrix/batch/scheduler.py
26
Python
0.071
style
30
51
51
false
[batch] job FIFO scheduler as baseline
231
vllm-project/aibrix
2,572
Go
Jeffwan
xinchen384
# Start sliding process in an async way asyncio.create_task(self.sliding_process()) self._policy = policy def append_job(self, job_id, due_time_seconds): # This submits a job to scheduler. The scheduler will dertermines # which job gets executed. self._jobs_queue.put...
TODO: let's refactor to use schedulerPolicy class abstraction here instead of if..else.. which is not scalable. If we determine to make it later. Let's have a TODO there
# Start sliding process in an async way asyncio.create_task(self.job_cleanup_loop()) self._policy = policy def append_job(self, job_id, due_time_seconds): # This submits a job to scheduler. The scheduler will determine # which job gets executed. self._jobs_queue.put(...
@@ -0,0 +1,137 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software ...
python/aibrix/aibrix/batch/scheduler.py
26
Python
0.429
refactor
169
51
51
false
[batch] job FIFO scheduler as baseline
231
vllm-project/aibrix
2,572
Go
Jeffwan
xinchen384
asyncio.create_task(self.sliding_process()) self._policy = policy def append_job(self, job_id, due_time_seconds): # This submits a job to scheduler. The scheduler will dertermines # which job gets executed. self._jobs_queue.put(job_id) def key_func(x): r...
nit: you can probably refactor a method called `get_inactive_job()` etc
asyncio.create_task(self.job_cleanup_loop()) self._policy = policy def append_job(self, job_id, due_time_seconds): # This submits a job to scheduler. The scheduler will determine # which job gets executed. self._jobs_queue.put(job_id) def key_func(x): re...
@@ -0,0 +1,137 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software ...
python/aibrix/aibrix/batch/scheduler.py
26
Python
0.429
refactor
71
51
51
false
[batch] job FIFO scheduler as baseline
231
vllm-project/aibrix
2,572
Go
Jeffwan
xinchen384
async def expire_jobs(self): # This is to expire jobs, which is important to achieve fairness. # Here fairness means that not all jobs are executed guaranteed. # Now we use the metric of due time to mark job expired. # Later this can extend it to other metrics. if self._poli...
what do we call it sliding? just curious
return job_id def get_inactive_jobs(self): return self._inactive_jobs async def expire_jobs(self): # This is to expire jobs based on specified due time per job. if self._policy == SchedulePolicy.FIFO: current_time = time.time() idx = 0 while...
@@ -0,0 +1,137 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software ...
python/aibrix/aibrix/batch/scheduler.py
26
Python
0.071
question
40
51
43
false
[batch] job FIFO scheduler as baseline
231
vllm-project/aibrix
2,572
Go
Jeffwan
xinchen384
) self._due_jobs_list.insert(index, item) def schedule_get_job(self): # Scheduler outputs a job to be processed following the specified policy. job_id = None if self._policy == SchedulePolicy.FIFO: if not self._jobs_queue.empty(): job_id = self._j...
how does expired state related to fairness? could you elaborate more details?
) self._due_jobs_list.insert(index, item) def schedule_get_job(self): # Scheduler outputs a job to be processed following the specified policy. job_id = None # [TODO] use class abstraction for SchedulingPolicy if self._policy == SchedulePolicy.FIFO: if n...
@@ -0,0 +1,137 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software ...
python/aibrix/aibrix/batch/scheduler.py
26
Python
0.286
question
77
51
51
false
[batch] job FIFO scheduler as baseline
231
vllm-project/aibrix
2,572
Go
Jeffwan
xinchen384
c.pods[pod.Name] = pod c.addPodAndModelMapping(pod.Name, modelName) klog.Infof("POD CREATED: %s/%s", pod.Namespace, pod.Name) c.debugInfo() } func (c *Cache) updatePod(oldObj interface{}, newObj interface{}) { c.mu.Lock() defer c.mu.Unlock() oldPod := oldObj.(*v1.Pod) oldModelName, ok := oldPod.Labels[modelI...
can we change this to v(4). We can use log level to control the messages. I see lots of logs in the controller manager
c.pods[pod.Name] = pod c.addPodAndModelMapping(pod.Name, modelName) klog.V(4).Infof("POD CREATED: %s/%s", pod.Namespace, pod.Name) c.debugInfo() } func (c *Cache) updatePod(oldObj interface{}, newObj interface{}) { c.mu.Lock() defer c.mu.Unlock() oldPod := oldObj.(*v1.Pod) oldModelName, ok := oldPod.Labels[m...
@@ -159,9 +159,11 @@ func (c *Cache) updatePod(oldObj interface{}, newObj interface{}) { return } + delete(c.pods, oldPod.Name) + c.pods[newPod.Name] = newPod c.deletePodAndModelMapping(oldPod.Name, oldModelName) c.addPodAndModelMapping(newPod.Name, newModelName) - klog.Infof("POD UPDATED. %s/%s %s", oldPod....
pkg/cache/cache.go
26
Go
0.429
suggestion
118
51
51
false
Fix concurrency issue with gateway RPM plugin
244
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
import os import shutil from pathlib import Path from urllib.parse import urljoin import uvicorn from fastapi import APIRouter, FastAPI, Request, Response from fastapi.datastructures import State from fastapi.responses import JSONResponse from prometheus_client import CollectorRegistry, make_asgi_app, multiprocess fro...
metrics part looks good to mean and this is a clean way to support metrics
INFO_METRICS.info( { "version": __version__.__version__, "engine": envs.INFERENCE_ENGINE, "engine_version": envs.INFERENCE_ENGINE_VERSION, } ) mount_metrics(app) init_app_state(app.state) app.include_router(router) return app app = build_app(...
@@ -101,11 +109,41 @@ async def unload_lora_adapter(request: UnloadLoraAdapterRequest, raw_request: Re def build_app(): app = FastAPI(debug=False) + INFO_METRICS.info( + { + "version": __version__.__version__, + "engine": envs.INFERENCE_ENGINE, + "engine_version": envs...
python/aibrix/app.py
26
Python
0.214
suggestion
75
112
39
false
[Misc ]Add runtime api metrics
251
vllm-project/aibrix
2,572
Go
Jeffwan
brosoul
// Step 2: Reconcile Loading if err := r.reconcileLoading(ctx, instance, selectedPod); err != nil { // retry any of the failure. instance.Status.Phase = modelv1alpha1.ModelAdapterFailed if err := r.Status().Update(ctx, instance); err != nil { klog.InfoS("Got error when updating status", "cluster name", req....
should we have wait period or retry count. Because right now if pod going thru rolling restart, then adapters will crash loop with them. For example, in rolling restart for pod A, all adapters are scheduled on pod B, then pod B restarts and adapters move to pod C.
// check the scheduled pod first, verify the mapping is still valid. // TODO: this needs to be changed once we support multiple lora adapters selectedPodName := instance.Status.Instances[0] if err := r.Get(ctx, types.NamespacedName{Namespace: instance.Namespace, Name: selectedPodName}, selectedPod); err != nil ...
@@ -296,6 +351,14 @@ func (r *ModelAdapterReconciler) DoReconcile(ctx context.Context, req ctrl.Reque return ctrl.Result{}, r.clearModelAdapterInstanceList(ctx, instance) } + if !utils.IsPodReady(selectedPod) || utils.IsPodTerminating(selectedPod) {
pkg/controller/modeladapter/modeladapter_controller.go
26
Go
0.5
bug
268
51
51
false
Improve model adapter reliability and stability
257
vllm-project/aibrix
2,572
Go
varungup90
Jeffwan
} } func getMetricsForPod(pod *v1.Pod, metricName string, metricsPort int) (float64, error) { // We should use the primary container port. In future, we can decide whether to use sidecar container's port url := fmt.Sprintf("http://%s:%d/metrics", pod.Status.PodIP, metricsPort) //// TODO a temp for debugging //url...
autoscaler has similar features. Let's refactor this part later and make sure cache and autoscaler fetcher can use same library
defer func() { if err := resp.Body.Close(); err != nil { klog.Errorf("Error closing response body: %v", err) } }() body, err := io.ReadAll(resp.Body) if err != nil { klog.Errorf("failed to read response from pod %s %s %d: %v", pod.Name, pod.Status.PodIP, podPort, err) continue } for _, met...
@@ -339,25 +365,95 @@ func (c *Cache) GetModelsForPod(podName string) (map[string]struct{}, error) { return models, nil } -func (c *Cache) IncrPodRequestCount(podName string) int { - c.mu.Lock() - defer c.mu.Unlock() +func (c *Cache) GetPodMetric(podName, metricName string) (float64, error) { + c.mu.RLock() + defe...
pkg/cache/cache.go
26
Go
0.429
performance
127
51
47
false
Use vllm metrics for routing
274
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
func (c *Cache) updatePodMetrics() { c.mu.Lock() defer c.mu.Unlock() for _, pod := range c.pods { if pod.Status.PodIP == "" { continue } podName := pod.Name for _, metricName := range metricNames { metricVal, err := getMetricsForPod(pod, metricName, 8000) if err != nil { continue } if le...
there's no need to fetch the `/metrics` endpoint for every metrics. Let's just fetch once and follow up metric reading can just parse it.
func (c *Cache) updatePodMetrics() { c.mu.Lock() defer c.mu.Unlock() for _, pod := range c.pods { if pod.Status.PodIP == "" { continue } podName := pod.Name if len(c.podMetrics[podName]) == 0 { c.podMetrics[podName] = map[string]float64{} } // We should use the primary container port. In future, ...
@@ -339,25 +365,95 @@ func (c *Cache) GetModelsForPod(podName string) (map[string]struct{}, error) { return models, nil } -func (c *Cache) IncrPodRequestCount(podName string) int { - c.mu.Lock() - defer c.mu.Unlock() +func (c *Cache) GetPodMetric(podName, metricName string) (float64, error) { + c.mu.RLock() + defe...
pkg/cache/cache.go
26
Go
0.5
suggestion
138
51
51
false
Use vllm metrics for routing
274
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
} else { klog.V(4).Info("Ignore inactive cluster", "name", cluster.Name, "state", cluster.Status.State, "deletionTime", cluster.DeletionTimestamp) } } return activeClusters } func isClusterActive(c rayclusterv1.RayCluster) bool { // Case 1: This RayCluster has been marked for deletion. if !c.DeletionTimes...
`isClusterActive` is used to decide whether we need to count this Raycluster and later use the count to compare with the desired number to decide whether to scale up or down. - If the Raycluster has been marked as deleted, do not count it. - If not been marked as delete, we categorize the Ray cluster into two statu...
} else { klog.V(4).Info("Ignore inactive cluster", "name", cluster.Name, "state", cluster.Status.State, "deletionTime", cluster.DeletionTimestamp) } } return activeClusters } func isClusterActive(c rayclusterv1.RayCluster) bool { // Case 1: This RayCluster has been marked for deletion. if !c.DeletionTimes...
@@ -110,10 +111,27 @@ func filterActiveClusters(clusters []rayclusterv1.RayCluster) []rayclusterv1.Ray } func isClusterActive(c rayclusterv1.RayCluster) bool { - // Do not use `c.Status.State != rayclusterv1.Ready`, creation staging doesn't have state created. - return c.Status.State != rayclusterv1.Failed && - c....
pkg/controller/rayclusterreplicaset/rayclusterreplicaset_utils.go
26
Go
0.786
bug
999
51
51
false
Improve Rayclusterreplicaset Status
295
vllm-project/aibrix
2,572
Go
Yicheng-Lu-llll
Yicheng-Lu-llll
continue } scaledRS, updatedRS, err := r.scaleReplicaSetAndRecordEvent(ctx, rs, 0, deployment) if err != nil { return false, err } if scaledRS { oldRSs[i] = updatedRS scaled = true } } return scaled, nil } // oldPodsRunning returns whether there are old pods running or any of the old ReplicaS...
In a Deployment, `oldPodsRunning` is used to check if all the Pods from the old ReplicaSet have already released their resources. If so, we can create a new ReplicaSet to update, following the recreate strategy. The code below is copied from `https://github.com/kubernetes/kubernetes`(we can see that Pod in status `v...
if *(rs.Spec.Replicas) == 0 { continue } scaledRS, updatedRS, err := r.scaleReplicaSetAndRecordEvent(ctx, rs, 0, deployment) if err != nil { return false, err } if scaledRS { oldRSs[i] = updatedRS scaled = true } } return scaled, nil } // oldPodsRunning returns whether there are old pods ru...
@@ -107,13 +107,7 @@ func oldPodsRunning(newRS *orchestrationv1alpha1.RayClusterReplicaSet, oldRSs [] continue } for _, pod := range podList {
pkg/controller/rayclusterfleet/recreate.go
26
Go
0.857
bug
1,720
39
40
false
Improve Rayclusterreplicaset Status
295
vllm-project/aibrix
2,572
Go
Yicheng-Lu-llll
Yicheng-Lu-llll
GetMaxScaleDownRate() float64 GetCurrentUsePerPod() float64 } // BaseScalingContext provides a base implementation of the ScalingContext interface. type BaseScalingContext struct { currentUsePerPod float64 targetValue float64 upTolerance float64 downTolerance float64 } func (b *BaseScalingContext) ...
This should be something has to be configured by user.
GetMaxScaleDownRate() float64 GetCurrentUsePerPod() float64 } // BaseScalingContext provides a base implementation of the ScalingContext interface. type BaseScalingContext struct { // Maximum rate at which to scale up MaxScaleUpRate float64 // Maximum rate at which to scale down, a value of 2.5 means the count ca...
@@ -28,10 +28,29 @@ type ScalingContext interface { // BaseScalingContext provides a base implementation of the ScalingContext interface. type BaseScalingContext struct { + // Maximum rate at which to scale up + MaxScaleUpRate float64 + // Maximum rate at which to scale down, a value of 2.5 means the count can redu...
pkg/controller/podautoscaler/common/context.go
26
Go
0.286
suggestion
54
48
51
false
Refactor AutoScaler: metricClient, context, reconcile
308
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
def test_job_output(): num_request = 100 generate_input_data(num_request) _storage.initialize_storage() job_id = _storage.submit_job_input("./one_job_input.json") print("succesfully create job: ", job_id) start_idx, num = 50, 10 requests = _storage.get_job_input_requests(job_id, start_idx...
why not to use `pytest` here? and seems you only invoke one test method?
# Copyright 2024 The Aibrix Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
@@ -101,3 +104,7 @@ def test_job_output(): _storage.delete_job(job_id) print("remove job id:", job_id) os.remove("./one_job_input.json") + + +if __name__ == "__main__": + test_submit_job_input()
python/aibrix/tests/test_storage.py
26
Python
0.429
question
72
27
107
false
[batch] use volcano TOS as batch storage
344
vllm-project/aibrix
2,572
Go
Jeffwan
xinchen384
# Copyright 2024 The Aibrix Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
please also add S3 later. You can use [minio](https://min.io/) for testing
# Copyright 2024 The Aibrix Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
@@ -14,14 +14,30 @@ import uuid +from aibrix.batch.storage.tos_storage import TOSStorage
python/aibrix/aibrix/batch/storage/batch_storage.py
18
Python
0.286
suggestion
74
43
43
false
[batch] use volcano TOS as batch storage
344
vllm-project/aibrix
2,572
Go
Jeffwan
xinchen384
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing per...
can we ask user to pass in the endpoint and region. they should be same as credentials. We can not fix it here. We already have cluster setup for other regions
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing per...
@@ -0,0 +1,198 @@ +# Copyright 2024 The Aibrix Team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable ...
python/aibrix/aibrix/batch/storage/tos_storage.py
26
Python
0.429
security
159
51
51
false
[batch] use volcano TOS as batch storage
344
vllm-project/aibrix
2,572
Go
Jeffwan
xinchen384
class TOSStorage(PersistentStorage): def __init__(self, access_key, secret_key, bucket_name="aibrix-batch"): """ This initializes client configuration to a TOS online bucket. All job information will be submitted to this TOS bucket. The two input keys are from Volcano TOS account. ...
can you remove chinese characters?
from aibrix.batch.storage.generic_storage import PersistentStorage class TOSStorage(PersistentStorage): def __init__(self, access_key, secret_key, endpoint, region, bucket_name): """ This initializes client configuration to a TOS online bucket. All job information will be submitted to this...
@@ -0,0 +1,198 @@ +# Copyright 2024 The Aibrix Team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable ...
python/aibrix/aibrix/batch/storage/tos_storage.py
26
Python
0.143
question
35
51
51
false
[batch] use volcano TOS as batch storage
344
vllm-project/aibrix
2,572
Go
Jeffwan
xinchen384
from aibrix.batch.storage.generic_storage import PersistentStorage class TOSStorage(PersistentStorage): def __init__(self, access_key, secret_key, bucket_name="aibrix-batch"): """ This initializes client configuration to a TOS online bucket. All job information will be submitted to this ...
can you use logging instead of print?
import json from aibrix.batch.storage.generic_storage import PersistentStorage class TOSStorage(PersistentStorage): def __init__(self, access_key, secret_key, endpoint, region, bucket_name): """ This initializes client configuration to a TOS online bucket. All job information will be submi...
@@ -0,0 +1,198 @@ +# Copyright 2024 The Aibrix Team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable ...
python/aibrix/aibrix/batch/storage/tos_storage.py
26
Python
0.143
question
37
51
51
false
[batch] use volcano TOS as batch storage
344
vllm-project/aibrix
2,572
Go
Jeffwan
xinchen384
try: self._client = tos.TosClientV2(ak, sk, endpoint, region) object_key = "test_key" string_io_obj = StringIO("hello world") result = self._client.put_object( self._bucket_name, object_key, content=string_io_obj ) print("...
why not create a single message and custom the error string?
try: self._client = tos.TosClientV2(ak, sk, endpoint, region) logging.info("Finished creating TOS client!!!") except tos.exceptions.TosClientError as e: logging.error( f"fail with client error, message:{e.message}, cause: {e.cause}" ) ...
@@ -0,0 +1,198 @@ +# Copyright 2024 The Aibrix Team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable ...
python/aibrix/aibrix/batch/storage/tos_storage.py
26
Python
0.357
question
60
51
51
false
[batch] use volcano TOS as batch storage
344
vllm-project/aibrix
2,572
Go
Jeffwan
xinchen384
if err != nil { klog.Error(err) continue } waitingReq, err := r.cache.GetPodMetric(pod.Name, num_requests_waiting) if err != nil { klog.Error(err) continue } swappedReq, err := r.cache.GetPodMetric(pod.Name, num_requests_swapped) if err != nil { klog.Error(err) continue } totalReq :=...
let's add some tests for the Route interface.
runningReq, err := r.cache.GetPodMetric(pod.Name, num_requests_running) if err != nil { klog.Error(err) continue } waitingReq, err := r.cache.GetPodMetric(pod.Name, num_requests_waiting) if err != nil { klog.Error(err) continue } swappedReq, err := r.cache.GetPodMetric(pod.Name, num_requests_...
@@ -77,5 +78,9 @@ func (r leastRequestRouter) Route(ctx context.Context, pods map[string]*v1.Pod) } } + if len(pods) == 0 || targetPodIP == "" {
pkg/plugins/gateway/algorithms/least_request.go
26
Go
0.071
suggestion
45
27
33
false
Add check if no pods are present
345
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
Port: ptr.To(gatewayv1.PortNumber(modelPort)), }, }, }, }, }, }, }, } if err := m.Client.Create(context.Background(), &httpRoute); err != nil { klog.Errorln(err) return } klog.Infof("httproute: %v created for model: %v", httpRoute.Name, modelName) m.createRefer...
a quick question, if we set namespace here, do we still need reference grant object? ![image](https://github.com/user-attachments/assets/5cf35be4-3a26-4a61-be87-d05169bf9fda)
Namespace: (*gatewayv1.Namespace)(&namespace), Port: ptr.To(gatewayv1.PortNumber(modelPort)), }, }, }, }, }, }, }, } err = m.Client.Create(context.Background(), &httpRoute) if err != nil && !apierrors.IsAlreadyExists(err) { klog.Errorln(err) return } i...
@@ -165,6 +171,38 @@ func (m *ModelRouter) createHTTPRoute(namespace string, labels map[string]string return } klog.Infof("httproute: %v created for model: %v", httpRoute.Name, modelName) + + m.createReferenceGrant(modelName, namespace) +} + +func (m *ModelRouter) createReferenceGrant(name, namespace string) { +...
pkg/controller/modelrouter/modelrouter_controller.go
26
Go
0.429
suggestion
177
51
51
false
Add reference grant to support httprouting for different namespace
347
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
"time" "github.com/google/uuid" "github.com/redis/go-redis/v9" openai "github.com/sashabaranov/go-openai" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" v1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/klog/v2" "github.com/aibrix/aibrix/pkg/cache" routing "github.com/aibrix/aib...
is there source of truth or single constant we can use? I remember somewhere else have the definition
"strings" "time" "github.com/google/uuid" "github.com/redis/go-redis/v9" openai "github.com/sashabaranov/go-openai" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" v1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/klog/v2" "github.com/aibrix/aibrix/pkg/cache" routing "github.com...
@@ -46,6 +47,7 @@ import ( var ( defaultRPM = 100 defaultTPMMultiplier = 1000 + routingStrategies = []string{"random", "least-request", "throughput"}
pkg/plugins/gateway/gateway.go
26
Go
0.429
suggestion
101
51
51
false
Add check for acceptable routing strategies
352
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
import json import os import random import time from datetime import datetime from typing import List, Optional, Tuple, Dict import openai import asyncio import logging from transformers import PreTrainedTokenizerBase from vllm.engine.arg_utils import EngineArgs from vllm.utils import FlexibleArgumentParser from be...
let's remove non English characters in github repo. the policy is a different bit different from our internal repo
import json import os import random import time from datetime import datetime from typing import List, Optional, Tuple, Dict import openai import asyncio import logging from transformers import PreTrainedTokenizerBase from vllm.engine.arg_utils import EngineArgs from vllm.utils import FlexibleArgumentParser from be...
@@ -21,20 +22,47 @@ except ImportError: from backend_request_func import get_tokenizer -logging.basicConfig( - level=logging.INFO, - format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', - handlers=[ - logging.StreamHandler() - ] -) +def setup_logging(log_filename, level=logging.INFO...
benchmarks/autoscaling/benchmark.py
26
Python
0.429
suggestion
114
51
51
false
optimize benchmark scripts for autoscaler, add more logs
356
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
import dataclasses import json import os import random import time from datetime import datetime from typing import List, Optional, Tuple, Dict import openai import asyncio import logging from transformers import PreTrainedTokenizerBase from vllm.engine.arg_utils import EngineArgs from vllm.utils import FlexibleArgu...
@happyandslow Can you help review the benchmark changes?
import dataclasses import json import os import random import time from datetime import datetime from typing import List, Optional, Tuple, Dict import openai import asyncio import logging from transformers import PreTrainedTokenizerBase from vllm.engine.arg_utils import EngineArgs from vllm.utils import FlexibleArgu...
@@ -3,6 +3,7 @@ import os import random import time +from datetime import datetime
benchmarks/autoscaling/benchmark.py
6
Python
0.286
performance
60
31
31
false
optimize benchmark scripts for autoscaler, add more logs
356
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
// Use 1 if there are zero current pods. readyPodsCount := math.Max(1, float64(originalReadyPodsCount)) maxScaleUp := math.Ceil(spec.MaxScaleUpRate * readyPodsCount) maxScaleDown := math.Floor(readyPodsCount / spec.MaxScaleDownRate) dspc := math.Ceil(observedStableValue / spec.TargetValue) dppc := math.Ceil(obs...
is this a debug message, if so, let's use `V(4)`
// Use 1 if there are zero current pods. readyPodsCount := math.Max(1, float64(originalReadyPodsCount)) maxScaleUp := math.Ceil(spec.MaxScaleUpRate * readyPodsCount) maxScaleDown := math.Floor(readyPodsCount / spec.MaxScaleDownRate) dspc := math.Ceil(observedStableValue / spec.TargetValue) dppc := math.Ceil(obs...
@@ -202,6 +202,14 @@ func (k *KpaAutoscaler) Scale(originalReadyPodsCount int, metricKey metrics.Name isOverPanicThreshold := dppc/readyPodsCount >= spec.PanicThreshold + klog.InfoS("--- KPA Details", "readyPodsCount", readyPodsCount,
pkg/controller/podautoscaler/scaler/kpa.go
26
Go
0.429
bug
48
51
51
false
optimize benchmark scripts for autoscaler, add more logs
356
vllm-project/aibrix
2,572
Go
Jeffwan
kr11
} if err := srv.Send(resp); err != nil { klog.Infof("send error %v", err) } } } func (s *Server) HandleRequestHeaders(ctx context.Context, requestID string, req *extProcPb.ProcessingRequest) (*extProcPb.ProcessingResponse, utils.User, int64, string) { klog.Info("\n\n") klog.Info("-- In RequestHeaders proc...
great. beside enabling check here. if we set envs, we should enable routing as well?
} if err := srv.Send(resp); err != nil { klog.Infof("send error %v", err) } } } func (s *Server) HandleRequestHeaders(ctx context.Context, requestID string, req *extProcPb.ProcessingRequest) (*extProcPb.ProcessingResponse, utils.User, int64, string) { klog.Info("\n\n") klog.Info("-- In RequestHeaders proc...
@@ -154,14 +155,11 @@ func (s *Server) HandleRequestHeaders(ctx context.Context, requestID string, req } if strings.ToLower(n.Key) == "routing-strategy" { routingStrategy = string(n.RawValue) + routingStrategyEnabled = true
pkg/plugins/gateway/gateway.go
26
Go
0.286
question
85
51
51
false
Validate routing strategy bug fix
364
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
func (s *Server) selectTargetPod(ctx context.Context, routingStrategy string, pods map[string]*v1.Pod) (string, error) { var route routing.Router switch routingStrategy { case "least-request": route = s.routers[routingStrategy] case "throughput": route = s.routers[routingStrategy] default: route = s.routers...
is there a chance ROUTING_ALGORITHM=""? or " ".
func (s *Server) selectTargetPod(ctx context.Context, routingStrategy string, pods map[string]*v1.Pod) (string, error) { var route routing.Router switch routingStrategy { case "least-request": route = s.routers[routingStrategy] case "throughput": route = s.routers[routingStrategy] default: route = s.routers...
@@ -480,6 +478,23 @@ func (s *Server) selectTargetPod(ctx context.Context, routingStrategy string, po return route.Route(ctx, pods) } +func validateRoutingStrategy(routingStrategy string, routingStrategyEnabled bool) bool { + routingStrategy = strings.TrimSpace(routingStrategy) + if routingStrategyEnabled && routi...
pkg/plugins/gateway/gateway.go
26
Go
0.071
suggestion
47
48
48
false
Validate routing strategy bug fix
364
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
return envoyTypePb.StatusCode_OK, nil } func (s *Server) selectTargetPod(ctx context.Context, routingStrategy string, pods map[string]*v1.Pod) (string, error) { var route routing.Router switch routingStrategy { case "least-request": route = s.routers[routingStrategy] case "throughput": route = s.routers[rout...
if this case, env setting override the request level setting?
return envoyTypePb.StatusCode_OK, nil } func (s *Server) selectTargetPod(ctx context.Context, routingStrategy string, pods map[string]*v1.Pod) (string, error) { var route routing.Router switch routingStrategy { case "least-request": route = s.routers[routingStrategy] case "throughput": route = s.routers[rout...
@@ -480,6 +478,23 @@ func (s *Server) selectTargetPod(ctx context.Context, routingStrategy string, po return route.Route(ctx, pods) } +func validateRoutingStrategy(routingStrategy string, routingStrategyEnabled bool) bool { + routingStrategy = strings.TrimSpace(routingStrategy) + if routingStrategyEnabled && routi...
pkg/plugins/gateway/gateway.go
26
Go
0.214
question
63
51
51
false
Validate routing strategy bug fix
364
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90
type MetricType string const ( ResourceMetrics MetricType = "resource" CustomMetrics MetricType = "custom" RawMetrics MetricType = "raw" ) // MetricFetcher defines an interface for fetching metrics. it could be Kubernetes metrics or Pod prometheus metrics. type MetricFetcher interface { FetchPodMetrics(ctx...
the fixed value was for local desktop testing. removing it produce stops dev working as expected. this is ok for standarization. just take this note if testing doesn't work. @kr11 We need to pass the fixed port from client side.
// MetricType defines the type of metrics to be fetched. type MetricType string const ( ResourceMetrics MetricType = "resource" CustomMetrics MetricType = "custom" RawMetrics MetricType = "raw" ) // MetricFetcher defines an interface for fetching metrics. it could be Kubernetes metrics or Pod prometheus met...
@@ -43,48 +44,53 @@ const ( // MetricFetcher defines an interface for fetching metrics. it could be Kubernetes metrics or Pod prometheus metrics. type MetricFetcher interface { + // Obseleted: Call FetchMetric instead. FetchPodMetrics(ctx context.Context, pod v1.Pod, metricsPort int, metricName string) (float64, ...
pkg/controller/podautoscaler/metrics/fetcher.go
26
Go
0.429
suggestion
229
51
51
false
Misc: add support to metricsSources property of podautoscaler
371
vllm-project/aibrix
2,572
Go
Jeffwan
zhangjyr
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the ...
good to switch to official sdk
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the ...
@@ -17,17 +17,20 @@ limitations under the License. package gateway import ( + "bytes" "context" "encoding/json" "fmt" "io" + "net/http" "slices" "strings" "time" "github.com/google/uuid" + "github.com/openai/openai-go"
pkg/plugins/gateway/gateway.go
26
Go
0.071
suggestion
30
51
51
false
Add envoy gateway streaming support
377
vllm-project/aibrix
2,572
Go
Jeffwan
varungup90