ronantakizawa/codereview-bench huggingface dataset:
Repository: vitejs/vite
File: packages/create-vite/src/index.ts (TypeScript)

Code before:
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import type { SpawnOptions } from 'node:child_process';
import spawn from 'cross-spawn'
import mri from 'mri'
import * as prompts from '@clack/prompts'
import colors from 'picocolors'

const {
  blue,
  blueBright,
  cyan,
  green,
  greenBright,
  magenta,
  red,
  redBright,
  reset,
  yellow,
} = colors

const argv = mri<{
  template?: string
  help?: boolean
  overwrite?: boolean
  immediate?: boolean
  rolldown?: boolean
  interactive?: boolean

Review comment (suggestion):
```suggestion
import type { SpawnOptions } from 'node:child_process'
```

Code after:
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import type { SpawnOptions } from 'node:child_process'
import spawn from 'cross-spawn'
import mri from 'mri'
import * as prompts from '@clack/prompts'
import colors from 'picocolors'

const {
  blue,
  blueBright,
  cyan,
  green,
  greenBright,
  magenta,
  red,
  redBright,
  reset,
  yellow,
} = colors

const argv = mri<{
  template?: string
  help?: boolean
  overwrite?: boolean
  immediate?: boolean
  rolldown?: boolean
  interactive?: boolean
Repository: vitejs/vite
File: packages/vite/src/node/__tests__/plugins/css.spec.ts (TypeScript)

Code before:
      cssUrlRE.test(
        'mask-image: image(skyblue,url(mask.png), linear-gradient(rgba(0, 0, 0, 1.0), transparent));',
      ),
    ).toBe(true)
  })
  test('should capture the full url with escaped parentheses', () => {
    const css = 'background-image: url(public/awkward-name\\)2.png);'
    const match = cssUrlRE.exec(css)

    if (match) {
      const capturedUrlContent = match[1].trim()
      try {
        // Try to assert
        expect(capturedUrlContent).toBe('public/awkward-name\\)2.png')
      } catch (error) {
        // If the assertion fails, it will enter the catch block
        console.error('Test failed! URL parsing did not match.')
        console.error('Expected:', 'public/awkward-name\\)2.png')
        console.error('Actual captured:', capturedUrlContent) // Output actual result

        // Must re-throw the error, otherwise the test would incorrectly pass
        throw error
      }
    } else {
      expect.fail('The regex should have found a match but it did not.')
    }
  })
})

describe('css modules', () => {
  test('css module compose/from path resolutions', async () => {
    const { transform } = await createCssPluginTransform({
      configFile: false,
      resolve: {
        alias: [
          {
            find: '@',
            replacement: path.join(
              import.meta.dirname,
              './fixtures/css-module-compose',
            ),
          },
        ],
      },
    })

    const result = await transform(
      `\
.foo {
position: fixed;
composes: bar from '@/css/bar.module.css';

Review comment (refactor):
I think we can simplify this as
```suggestion
    expect(match?.[1].trim()).toBe('public/awkward-name\\)2.png')
```

Code after:
      cssUrlRE.test(
        'mask-image: image(skyblue,url(mask.png), linear-gradient(rgba(0, 0, 0, 1.0), transparent));',
      ),
    ).toBe(true)
  })

  test('should capture the full url with escaped parentheses', () => {
    const css = 'background-image: url(public/awkward-name\\)2.png);'
    const match = cssUrlRE.exec(css)
    expect(match?.[1].trim()).toBe('public/awkward-name\\)2.png')
  })
})

describe('css modules', () => {
  test('css module compose/from path resolutions', async () => {
    const { transform } = await createCssPluginTransform({
      configFile: false,
      resolve: {
        alias: [
          {
            find: '@',
            replacement: path.join(
              import.meta.dirname,
              './fixtures/css-module-compose',
            ),
          },
        ],
      },
    })

    const result = await transform(
      `\
.foo {
position: fixed;
composes: bar from '@/css/bar.module.css';
}`,
      '/css/foo.module.css',
    )

    expect(result.code).toMatchInlineSnapshot(
      `
      "._bar_1b4ow_1 {
        display: block;
        background: #f0f;
      }
      ._foo_86148_1 {
      position: fixed;
      }"
    `,
    )
  })
Repository: vitejs/vite
File: packages/vite/src/node/plugins/completeAmdWrap.ts (TypeScript)

Code before:
import type { Plugin } from '../plugin'

/**
 * ensure amd bundles request `require` to be injected
 */
export function completeAmdWrapPlugin(): Plugin {
  const AmdWrapRE =
    /\bdefine\((?:\s*\[([^\]]*)\],)?\s*(?:\(\s*)?function\s*\(([^)]*)\)\s*\{/g

  return {
    name: 'vite:force-amd-wrap-require',
    renderChunk(code, _chunk, opts) {
      if (opts.format !== 'amd') return

      return {
        code: code.replace(AmdWrapRE, (_, deps, params) => {
          if (deps && /"require"/.test(deps)) {
            return `define([${deps}], (function(${params}) {`
          }

          const newDeps = deps ? `"require", ${deps}` : '"require"'
          const newParams = params.trim() ? `require, ${params}` : 'require'

          return `define([${newDeps}], (function(${newParams}) {`
        }),
        map: null,
      }
    },
  }
}


Review comment (suggestion):
```suggestion
          if (deps?.includes('"require"')) {
```

Code after:
import type { Plugin } from '../plugin'

/**
 * ensure amd bundles request `require` to be injected
 */
export function completeAmdWrapPlugin(): Plugin {
  const AmdWrapRE =
    /\bdefine\((?:\s*\[([^\]]*)\],)?\s*(?:\(\s*)?function\s*\(([^)]*)\)\s*\{/g

  return {
    name: 'vite:force-amd-wrap-require',
    renderChunk(code, _chunk, opts) {
      if (opts.format !== 'amd') return

      return {
        code: code.replace(AmdWrapRE, (_, deps, params) => {
          if (deps?.includes(`"require"`) || deps?.includes(`'require'`)) {
            return `define([${deps}], (function(${params}) {`
          }

          const newDeps = deps ? `"require", ${deps}` : '"require"'
          const newParams = params.trim() ? `require, ${params}` : 'require'

          return `define([${newDeps}], (function(${newParams}) {`
        }),
        map: null, // no need to generate sourcemap as no mapping exists for the wrapper
      }
    },
  }
}
Repository: vitejs/vite
File: packages/vite/src/node/plugins/completeAmdWrap.ts (TypeScript)

Code before:
import type { Plugin } from '../plugin'

/**
 * ensure amd bundles request `require` to be injected
 */
export function completeAmdWrapPlugin(): Plugin {
  const AmdWrapRE =
    /\bdefine\((?:\s*\[([^\]]*)\],)?\s*(?:\(\s*)?function\s*\(([^)]*)\)\s*\{/g

  return {
    name: 'vite:force-amd-wrap-require',
    renderChunk(code, _chunk, opts) {
      if (opts.format !== 'amd') return

      return {
        code: code.replace(AmdWrapRE, (_, deps, params) => {
          if (deps && /"require"/.test(deps)) {
            return `define([${deps}], (function(${params}) {`
          }

          const newDeps = deps ? `"require", ${deps}` : '"require"'
          const newParams = params.trim() ? `require, ${params}` : 'require'

          return `define([${newDeps}], (function(${newParams}) {`
        }),
        map: null,
      }
    },
  }
}


Review comment (suggestion):
```suggestion
        map: null, // no need to generate sourcemap as no mapping exists for the wrapper
```
The `completeSystemWrapPlugin` does not have this comment, but I thought it would be nice to clarify this.


Code after:
import type { Plugin } from '../plugin'

/**
 * ensure amd bundles request `require` to be injected
 */
export function completeAmdWrapPlugin(): Plugin {
  const AmdWrapRE =
    /\bdefine\((?:\s*\[([^\]]*)\],)?\s*(?:\(\s*)?function\s*\(([^)]*)\)\s*\{/g

  return {
    name: 'vite:force-amd-wrap-require',
    renderChunk(code, _chunk, opts) {
      if (opts.format !== 'amd') return

      return {
        code: code.replace(AmdWrapRE, (_, deps, params) => {
          if (deps?.includes(`"require"`) || deps?.includes(`'require'`)) {
            return `define([${deps}], (function(${params}) {`
          }

          const newDeps = deps ? `"require", ${deps}` : '"require"'
          const newParams = params.trim() ? `require, ${params}` : 'require'

          return `define([${newDeps}], (function(${newParams}) {`
        }),
        map: null, // no need to generate sourcemap as no mapping exists for the wrapper
      }
    },
  }
}
Repository: vitejs/vite
File: packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts (TypeScript)

Code before:
// NOTE: Cannot use subpath imports for some reason
import '../../../../../../types/importMeta'

export interface ModuleType {
  name: string
}

export const basic = import.meta.glob<ModuleType>('./modules/*.ts')
// prettier-ignore
export const basicWithObjectKeys = Object.keys(import.meta.glob<ModuleType>('./modules/*.ts'))
// prettier-ignore
export const basicWithObjectValues = Object.values(import.meta.glob<ModuleType>('./modules/*.ts'))

export const basicEager = import.meta.glob<ModuleType>('./modules/*.ts', {
  eager: true,
})
export const basicEagerWithObjectKeys = Object.keys(
  import.meta.glob<ModuleType>('./modules/*.ts', {
    eager: true,
  }),
)
export const basicEagerWithObjectValues = Object.values(
  import.meta.glob<ModuleType>('./modules/*.ts', {
    eager: true,
  }),
)

Review comment (suggestion):
I think it's because the closest `package.json` is this one.
https://github.com/vitejs/vite/blob/2bdd262388a1eaee7853b7f8349dc9f60f2cc2f0/packages/vite/src/node/__tests__/package.json

Code after:
// NOTE: `#types/importMeta` does not work as `src/node/__tests__/package.json` shadows the root
// `package.json` and does not declare the subpath import.
import '../../../../../../types/importMeta'

export interface ModuleType {
  name: string
}

export const basic = import.meta.glob<ModuleType>('./modules/*.ts')
// prettier-ignore
export const basicWithObjectKeys = Object.keys(import.meta.glob<ModuleType>('./modules/*.ts'))
// prettier-ignore
export const basicWithObjectValues = Object.values(import.meta.glob<ModuleType>('./modules/*.ts'))

export const basicEager = import.meta.glob<ModuleType>('./modules/*.ts', {
  eager: true,
})
export const basicEagerWithObjectKeys = Object.keys(
  import.meta.glob<ModuleType>('./modules/*.ts', {
    eager: true,
  }),
)
export const basicEagerWithObjectValues = Object.values(
  import.meta.glob<ModuleType>('./modules/*.ts', {
    eager: true,
  }),
Repository: vitejs/vite
File: packages/vite/src/module-runner/importMetaResolver.ts (TypeScript)

Code before:
export type ImportMetaResolver = (specifier: string, importer: string) => string

const customizationHookNamespace = 'vite-module-runner:import-meta-resolve/v1/'
const customizationHooksModule = /* js */ `

export async function resolve(specifier, context, nextResolve) {
  if (specifier.startsWith(${JSON.stringify(customizationHookNamespace)})) {
    const data = specifier.slice(${JSON.stringify(customizationHookNamespace)}.length)
    const [parsedSpecifier, parsedImporter] = JSON.parse(data)
    specifier = parsedSpecifier
    context.parentURL = parsedImporter
  }

  return nextResolve(specifier, context)
}

`

export async function createImportMetaResolver(): Promise<
  ImportMetaResolver | undefined
> {
  let module: typeof import('node:module')
  try {
    module = (await import('node:module')).Module
  } catch {
    return
  }
  // `module.Module` may be `undefined` when `node:module` is mocked
  if (!module?.register) {
    return
  }

  try {
    const hookModuleContent = `data:text/javascript,${encodeURI(customizationHooksModule)}`
    module.register(hookModuleContent)
  } catch (e) {
    // For `--experimental-network-imports` flag that exists in Node before v22
    if ('code' in e && e.code === 'ERR_NETWORK_IMPORT_DISALLOWED') {
      return
    }
    throw e
  }

  return (specifier: string, importer: string) =>
    import.meta.resolve(
      `${customizationHookNamespace}${JSON.stringify([specifier, importer])}`,
    )
}


Review comment (suggestion):
The exported string contains leading and trailing blank lines that serve no functional purpose. These should be removed to improve code clarity and reduce unnecessary whitespace in the injected code.
```suggestion
(() => {
  const resolve = 'resolve'
  return (specifier, importer) =>
    import.meta[resolve](
      \`${customizationHookNamespace}\${JSON.stringify([specifier, importer])}\`,
    )
})()
```

Code after:
    module.register(hookModuleContent)
  } catch (e) {
    // For `--experimental-network-imports` flag that exists in Node before v22
    if ('code' in e && e.code === 'ERR_NETWORK_IMPORT_DISALLOWED') {
      return
    }
    throw e
  }

  return (specifier: string, importer: string) =>
    import.meta.resolve(
      `${customizationHookNamespace}${JSON.stringify([specifier, importer])}`,
    )
}

// NOTE: use computed string to avoid `define` replacing `import.meta.resolve` when bundled
export const importMetaResolveWithCustomHookString: string = /* js */ `

  (() => {
    const resolve = 'resolve'
    return (specifier, importer) =>
      import.meta[resolve](
        \`${customizationHookNamespace}\${JSON.stringify([specifier, importer])}\`,
      )
  })()

`
Repository: vitejs/vite
File: packages/vite/src/node/server/ws.ts (TypeScript)

Code before:
            `WebSocket server error: Port ${e.port} is already in use`,
          ),
          { error: e },
        )
      } else {
        config.logger.error(
          colors.red(`WebSocket server error:\n${e.stack || e.message}`),
          { error: e },
        )
      }
    })
  }

  const emitCustomEvent = <T extends string>(
    event: T,
    data: InferCustomEventPayload<T>,
    socket: WebSocketRaw,
    invoke?: 'send' | `send:${string}`,
  ) => {
    const listeners = customListeners.get(event)
    if (!listeners?.size) return

    const client = getSocketClient(socket)
    for (const listener of listeners) {
      listener(data, client, invoke)
    }
  }

  wss.on('connection', (socket) => {
    socket.on('message', (raw) => {
      if (!customListeners.size) return
      let parsed: any
      try {
        parsed = JSON.parse(String(raw))
      } catch {}
      if (!parsed || parsed.type !== 'custom' || !parsed.event) return
      emitCustomEvent(parsed.event, parsed.data, socket, parsed.invoke)
    })
    socket.on('error', (err) => {
      config.logger.error(`${colors.red(`ws error:`)}\n${err.stack}`, {
        timestamp: true,
        error: err,
      })
    })
    socket.on('close', () => {
      emitCustomEvent('vite:client-disconnect', undefined, socket)
    })

    emitCustomEvent('vite:client-connect', undefined, socket)

    socket.send(JSON.stringify({ type: 'connected' }))

Review comment (suggestion):
Unrelated, but this `parsed.invoke` (or anywhere `invoke` related) seems unused.

Code after:
          ),
          { error: e },
        )
      } else {
        config.logger.error(
          colors.red(`WebSocket server error:\n${e.stack || e.message}`),
          { error: e },
        )
      }
    })
  }

  const emitCustomEvent = <T extends string>(
    event: T,
    data: InferCustomEventPayload<T>,
    socket: WebSocketRaw,
  ) => {
    const listeners = customListeners.get(event)
    if (!listeners?.size) return

    const client = getSocketClient(socket)
    for (const listener of listeners) {
      listener(data, client)
    }
  }

  wss.on('connection', (socket) => {
    socket.on('message', (raw) => {
      if (!customListeners.size) return
      let parsed: any
      try {
        parsed = JSON.parse(String(raw))
      } catch {}
      if (!parsed || parsed.type !== 'custom' || !parsed.event) return
      emitCustomEvent(parsed.event, parsed.data, socket)
    })
    socket.on('error', (err) => {
      config.logger.error(`${colors.red(`ws error:`)}\n${err.stack}`, {
        timestamp: true,
        error: err,
      })
    })
    socket.on('close', () => {
      emitCustomEvent('vite:client:disconnect', undefined, socket)
    })

    emitCustomEvent('vite:client:connect', undefined, socket)

    socket.send(JSON.stringify({ type: 'connected' }))
    if (bufferedError) {
      socket.send(JSON.stringify(bufferedError))
Repository: vitejs/vite
File: packages/vite/src/node/plugins/css.ts (TypeScript)

Code before:

  return worker
}

type ScssWorkerResult = {
  css: string
  map?: string | undefined
  stats: { includedFiles: string[] }
}

const scssProcessor = (
  maxWorkers: number | undefined,
): StylePreprocessor<SassStylePreprocessorInternalOptions> => {
  let worker: ReturnType<typeof makeScssWorker> | undefined
  let failedSassEmbedded: boolean | undefined

  return {
    close() {
      worker?.stop()
    },
    async process(environment, source, root, options, resolvers) {
      let sassPackage = loadSassPackage(root, failedSassEmbedded ?? false)

      if (failedSassEmbedded === undefined) {
        failedSassEmbedded = false

        try {
          await import(sassPackage.path)
        } catch (e) {
          if (/sass-embedded-[a-z0-9]+-[a-z0-9]+/i.test(e.message)) {
            failedSassEmbedded = true
            sassPackage = loadSassPackage(root, failedSassEmbedded)
          }
        }
      }

      worker ??= makeScssWorker(environment, resolvers, maxWorkers)

      const { content: data, map: additionalMap } = await getSource(
        source,
        options.filename,
        options.additionalData,
        options.enableSourcemap,
      )

      const optionsWithoutAdditionalData = {
        ...options,
        additionalData: undefined,
      }
      try {
        const result = await worker.run(

Review comment (bug):
```suggestion
      if (failedSassEmbedded === undefined) {
        failedSassEmbedded = false
```

Code after:

  return worker
}

type ScssWorkerResult = {
  css: string
  map?: string | undefined
  stats: { includedFiles: string[] }
}

const scssProcessor = (
  maxWorkers: number | undefined,
): StylePreprocessor<SassStylePreprocessorInternalOptions> => {
  let worker: ReturnType<typeof makeScssWorker> | undefined
  let failedSassEmbedded: boolean | undefined

  return {
    close() {
      worker?.stop()
    },
    async process(environment, source, root, options, resolvers) {
      let sassPackage = loadSassPackage(root, failedSassEmbedded ?? false)
      if (failedSassEmbedded === undefined) {
        failedSassEmbedded = false
        try {
          await import(sassPackage.path)
        } catch (e) {
          if (/sass-embedded-[a-z0-9]+-[a-z0-9]+/i.test(e.message)) {
            failedSassEmbedded = true
            sassPackage = loadSassPackage(root, failedSassEmbedded)
          }
        }
      }

      worker ??= makeScssWorker(environment, resolvers, maxWorkers)

      const { content: data, map: additionalMap } = await getSource(
        source,
        options.filename,
        options.additionalData,
        options.enableSourcemap,
      )

      const optionsWithoutAdditionalData = {
        ...options,
        additionalData: undefined,
      }
      try {
        const result = await worker.run(
          pathToFileURL(sassPackage.path).href,
          data,
Repository: vitejs/vite
File: docs/.vitepress/config.ts (TypeScript)

Code before:
              link: '/config/worker-options',
            },
          ],
        },
      ],
      '/changes/': [
        {
          text: 'Breaking Changes',
          link: '/changes/',
        },
        {
          text: 'Current',
          items: [],
        },
        {
          text: 'Future',
          items: [
            {
              text: 'this.environment in Hooks',
              link: '/changes/this-environment-in-hooks',
            },
            {
              text: 'HMR hotUpdate Plugin Hook',
              link: '/changes/hotupdate-hook',
            },
            {
              text: 'Move to Per-environment APIs',
              link: '/changes/per-environment-apis',
            },
            {
              text: 'SSR Using ModuleRunner API',
              link: '/changes/ssr-using-modulerunner',
            },
            {
              text: 'Shared Plugins During Build',
              link: '/changes/shared-plugins-during-build',
            },
          ],
        },
        {
          text: 'Past',
          items: [],
        },
      ],
    },

    outline: {
      level: [2, 3],
    },
  },
  transformPageData(pageData) {

Review comment (suggestion):
`transformPageData` was previously use for reasons mentioned at https://github.com/vitejs/vite/pull/15984. However, I can't seem to replicate the issue now. We're only generating one `.html` file which servers would use for both `/path` and `/path.html`. There's no way that canonical links were only added to `/path.html` unless we generate two files or it was SSR.

`transformHead` seems to work the same from my testing and is the more direct API.

Code after:
            {
              text: 'Move to Per-environment APIs',
              link: '/changes/per-environment-apis',
            },
            {
              text: 'SSR Using ModuleRunner API',
              link: '/changes/ssr-using-modulerunner',
            },
            {
              text: 'Shared Plugins During Build',
              link: '/changes/shared-plugins-during-build',
            },
          ],
        },
        {
          text: 'Past',
          items: [],
        },
      ],
    },

    outline: {
      level: [2, 3],
    },
  },
  transformHead(ctx) {
    const path = ctx.page.replace(/(^|\/)index\.md$/, '$1').replace(/\.md$/, '')

    if (path !== '404') {
      const canonicalUrl = path ? `${ogUrl}/${path}` : ogUrl
      ctx.head.push(
        ['link', { rel: 'canonical', href: canonicalUrl }],
        ['meta', { property: 'og:title', content: ctx.pageData.title }],
      )
    }

    // For the landing page, move the google font links to the top for better performance
    if (path === '') {
      const googleFontLinks: HeadConfig[] = []
      for (let i = 0; i < ctx.head.length; i++) {
        const tag = ctx.head[i]
        if (
          tag[0] === 'link' &&
          (tag[1]?.href?.includes('fonts.googleapis.com') ||
            tag[1]?.href?.includes('fonts.gstatic.com'))
        ) {
          ctx.head.splice(i, 1)
          googleFontLinks.push(tag)
          i--
        }
      }
Repository: vitejs/vite
File: playground/wasm/__tests__/wasm.spec.ts (TypeScript)

Code before:
    const { default: light } = await import('../light.wasm?init')
    let result
    const instance = await light({
      imports: {
        imported_func: (res) => (result = res),
      },
    })
    expect(instance instanceof WebAssembly.Instance).toBe(true)
    // @ts-ignore
    instance.exports.exported_func()
    expect(result).toBe(42)
  })

  test('should work when output', async () => {
    const { default: heavy } = await import('../heavy.wasm?init')
    let result
    const instance = await heavy({
      imports: {
        imported_func: (res) => (result = res),
      },
    })
    expect(instance instanceof WebAssembly.Instance).toBe(true)
    // @ts-ignore
    instance.exports.exported_func()
    expect(result).toBe(24)
  })
})


Review comment (suggestion):
We can remove these tests as it's covered by the new `ssr-wasm` playground.

Code after:
import { expect, test } from 'vitest'
import { isBuild, page } from '~utils'

test('should work when inlined', async () => {
  await page.click('.inline-wasm .run')
  await expect
    .poll(() => page.textContent('.inline-wasm .result'))
    .toMatch('42')
})

test('should work when output', async () => {
  await page.click('.output-wasm .run')
  await expect
    .poll(() => page.textContent('.output-wasm .result'))
    .toMatch('24')
})

test('init function returns WebAssembly.Instance', async () => {
  await page.click('.init-returns-instance .run')
  await expect
    .poll(() => page.textContent('.init-returns-instance .result'))
    .toMatch('true')
})

test('?url', async () => {
  expect(await page.textContent('.url')).toMatch(
    isBuild ? 'data:application/wasm' : '/light.wasm',
  )
})

test('should work when wasm in worker', async () => {
  await expect.poll(() => page.textContent('.worker-wasm .result')).toMatch('3')
})