ronantakizawa/codereview-bench huggingface dataset:
Repository: tailwindlabs/tailwindcss
File: packages/@tailwindcss-node/src/compile.ts (TypeScript)

Code before:
      let [module, moduleDependencies] = await Promise.all([
        importModule(pathToFileURL(resolvedPath).href + '?id=' + Date.now()),
        getModuleDependencies(resolvedPath),
      ])

      onDependency(resolvedPath)
      for (let file of moduleDependencies) {
        onDependency(file)
      }
      return module.default ?? module
    },
  })
}

// Attempts to import the module using the native `import()` function. If this
// fails, it sets up `jiti` and attempts to import this way so that `.ts` files
// can be resolved properly.
let jiti: null | Jiti = null
async function importModule(path: string): Promise<any> {
  try {
    return await import(path)
  } catch (error) {
    try {
      if (!jiti) {
        jiti = createJiti(import.meta.url, { moduleCache: false, fsCache: false })
      }
      return await jiti.import(path)
    } catch {}
    throw error
  }
}


Review comment (performance):
```suggestion
      jiti ??= createJiti(import.meta.url, { moduleCache: false, fsCache: false, interopDefault: true })
```

In v3 we use the `interopDefault` flag and I _think_ we need to here as well?

Code after:
      let [module, moduleDependencies] = await Promise.all([
        importModule(pathToFileURL(resolvedPath).href + '?id=' + Date.now()),
        getModuleDependencies(resolvedPath),
      ])

      onDependency(resolvedPath)
      for (let file of moduleDependencies) {
        onDependency(file)
      }
      return module.default ?? module
    },
  })
}

// Attempts to import the module using the native `import()` function. If this
// fails, it sets up `jiti` and attempts to import this way so that `.ts` files
// can be resolved properly.
let jiti: null | Jiti = null
async function importModule(path: string): Promise<any> {
  try {
    return await import(path)
  } catch (error) {
    try {
      jiti ??= createJiti(import.meta.url, { moduleCache: false, fsCache: false })
      return await jiti.import(path)
    } catch {}
    throw error
  }
}
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/value-parser.ts (TypeScript)

Code before:
      case GREAT_THAN:
      case EQUAL: {
        // 1. Handle everything before the separator as a word
        // Handle everything before the closing paren a word
        if (buffer.length > 0) {
          let node = word(buffer)
          if (parent) {
            parent.nodes.push(node)
          } else {
            ast.push(node)
          }
          buffer = ''
        }

        // 2. Look ahead and find the end of the separator
        let start = i
        let end = i + 1
        for (; end < input.length; end++) {
          peekChar = input.charCodeAt(end)
          if (
            peekChar !== COLON &&
            peekChar !== COMMA &&
            peekChar !== SPACE &&
            peekChar !== LESSER_THAN &&
            peekChar !== GREAT_THAN &&
            peekChar !== EQUAL
          ) {
            break
          }
        }
        i = end - 1

        let node = separator(input.slice(start, end))
        if (parent) {
          parent.nodes.push(node)
        } else {
          ast.push(node)
        }

        break
      }

      // Start of a string.
      case SINGLE_QUOTE:
      case DOUBLE_QUOTE: {
        let start = i

        // We need to ensure that the closing quote is the same as the opening
        // quote.
        //
        // E.g.:

Review comment (suggestion):
```suggestion
            peekChar !== LESS_THAN &&
            peekChar !== GREATER_THAN &&
            peekChar !== EQUALS
```

Code after:
      case GREATER_THAN:
      case EQUALS: {
        // 1. Handle everything before the separator as a word
        // Handle everything before the closing paren a word
        if (buffer.length > 0) {
          let node = word(buffer)
          if (parent) {
            parent.nodes.push(node)
          } else {
            ast.push(node)
          }
          buffer = ''
        }

        // 2. Look ahead and find the end of the separator
        let start = i
        let end = i + 1
        for (; end < input.length; end++) {
          peekChar = input.charCodeAt(end)
          if (
            peekChar !== COLON &&
            peekChar !== COMMA &&
            peekChar !== SPACE &&
            peekChar !== LESS_THAN &&
            peekChar !== GREATER_THAN &&
            peekChar !== EQUALS
          ) {
            break
          }
        }
        i = end - 1

        let node = separator(input.slice(start, end))
        if (parent) {
          parent.nodes.push(node)
        } else {
          ast.push(node)
        }

        break
      }

      // Start of a string.
      case SINGLE_QUOTE:
      case DOUBLE_QUOTE: {
        let start = i

        // We need to ensure that the closing quote is the same as the opening
        // quote.
        //
        // E.g.:
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/value-parser.ts (TypeScript)

Code before:
  let stack: (ValueFunctionNode | null)[] = []

  let parent = null as ValueFunctionNode | null

  let buffer = ''

  let peekChar

  for (let i = 0; i < input.length; i++) {
    let currentChar = input.charCodeAt(i)

    switch (currentChar) {
      // Space and commas are bundled into separators
      //
      // E.g.:
      //
      // ```css
      // foo(bar, baz)
      //        ^^
      // ```
      case COLON:
      case COMMA:
      case SPACE:
      case LESSER_THAN:
      case GREAT_THAN:
      case EQUAL: {
        // 1. Handle everything before the separator as a word
        // Handle everything before the closing paren a word
        if (buffer.length > 0) {
          let node = word(buffer)
          if (parent) {
            parent.nodes.push(node)
          } else {
            ast.push(node)
          }
          buffer = ''
        }

        // 2. Look ahead and find the end of the separator
        let start = i
        let end = i + 1
        for (; end < input.length; end++) {
          peekChar = input.charCodeAt(end)
          if (
            peekChar !== COLON &&
            peekChar !== COMMA &&
            peekChar !== SPACE &&
            peekChar !== LESSER_THAN &&
            peekChar !== GREAT_THAN &&
            peekChar !== EQUAL
          ) {

Review comment (suggestion):
```suggestion
      case LESS_THAN:
      case GREATER_THAN:
      case EQUALS: {
```

Code after:
  let stack: (ValueFunctionNode | null)[] = []

  let parent = null as ValueFunctionNode | null

  let buffer = ''

  let peekChar

  for (let i = 0; i < input.length; i++) {
    let currentChar = input.charCodeAt(i)

    switch (currentChar) {
      // Space and commas are bundled into separators
      //
      // E.g.:
      //
      // ```css
      // foo(bar, baz)
      //        ^^
      // ```
      case COLON:
      case COMMA:
      case SPACE:
      case LESS_THAN:
      case GREATER_THAN:
      case EQUALS: {
        // 1. Handle everything before the separator as a word
        // Handle everything before the closing paren a word
        if (buffer.length > 0) {
          let node = word(buffer)
          if (parent) {
            parent.nodes.push(node)
          } else {
            ast.push(node)
          }
          buffer = ''
        }

        // 2. Look ahead and find the end of the separator
        let start = i
        let end = i + 1
        for (; end < input.length; end++) {
          peekChar = input.charCodeAt(end)
          if (
            peekChar !== COLON &&
            peekChar !== COMMA &&
            peekChar !== SPACE &&
            peekChar !== LESS_THAN &&
            peekChar !== GREATER_THAN &&
            peekChar !== EQUALS
          ) {
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/value-parser.ts (TypeScript)

Code before:
  for (const node of ast) {
    switch (node.kind) {
      case 'word':
      case 'separator': {
        css += node.value
        break
      }
      case 'function': {
        css += node.value + '(' + toCss(node.nodes) + ')'
      }
    }
  }
  return css
}

const BACKSLASH = 0x5c
const CLOSE_PAREN = 0x29
const COLON = 0x3a
const COMMA = 0x2c
const DOUBLE_QUOTE = 0x22
const OPEN_PAREN = 0x28
const SINGLE_QUOTE = 0x27
const SPACE = 0x20
const LESSER_THAN = 0x3c
const GREAT_THAN = 0x3e
const EQUAL = 0x3d

export function parse(input: string) {
  input = input.replaceAll('\r\n', '\n')

  let ast: ValueAstNode[] = []

  let stack: (ValueFunctionNode | null)[] = []

  let parent = null as ValueFunctionNode | null

  let buffer = ''

  let peekChar

  for (let i = 0; i < input.length; i++) {
    let currentChar = input.charCodeAt(i)

    switch (currentChar) {
      // Space and commas are bundled into separators
      //
      // E.g.:
      //
      // ```css
      // foo(bar, baz)
      //        ^^

Review comment (suggestion):
```suggestion
const LESS_THAN = 0x3c
const GREATER_THAN = 0x3e
const EQUALS = 0x3d
```

Code after:
  for (const node of ast) {
    switch (node.kind) {
      case 'word':
      case 'separator': {
        css += node.value
        break
      }
      case 'function': {
        css += node.value + '(' + toCss(node.nodes) + ')'
      }
    }
  }
  return css
}

const BACKSLASH = 0x5c
const CLOSE_PAREN = 0x29
const COLON = 0x3a
const COMMA = 0x2c
const DOUBLE_QUOTE = 0x22
const OPEN_PAREN = 0x28
const SINGLE_QUOTE = 0x27
const SPACE = 0x20
const LESS_THAN = 0x3c
const GREATER_THAN = 0x3e
const EQUALS = 0x3d

export function parse(input: string) {
  input = input.replaceAll('\r\n', '\n')

  let ast: ValueAstNode[] = []

  let stack: (ValueFunctionNode | null)[] = []

  let parent = null as ValueFunctionNode | null

  let buffer = ''

  let peekChar

  for (let i = 0; i < input.length; i++) {
    let currentChar = input.charCodeAt(i)

    switch (currentChar) {
      // Space and commas are bundled into separators
      //
      // E.g.:
      //
      // ```css
      // foo(bar, baz)
      //        ^^
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/index.test.ts (TypeScript)

Code before:
          loadPlugin: async () => {
            return ({ addVariant }: PluginAPI) => {
              addVariant('hocus', '&:hover, &:focus')
            }
          },
        },
      ),
    ).rejects.toThrowErrorMatchingInlineSnapshot(`[Error: \`@plugin\` cannot be nested.]`))

  test('@plugin can accept options', async () => {
    expect.hasAssertions()

    let { build } = await compile(
      css`
        @tailwind utilities;
        @plugin "my-plugin" {
          color: red;
        }
      `,
      {
        loadPlugin: async () => {
          return plugin.withOptions((options) => {
            expect(options).toEqual({
              color: 'red',
            })

            return ({ addUtilities }) => {
              addUtilities({
                '.text-primary': {
                  color: options.color,
                },
              })
            }
          })
        },
      },
    )

    let compiled = build(['text-primary'])

    expect(optimizeCss(compiled).trim()).toMatchInlineSnapshot(`
      ".text-primary {
        color: red;
      }"
    `)
  })

  test('@plugin options can be null, booleans, string, numbers, or arrays including those types', async () => {
    expect.hasAssertions()

    await compile(

Review comment (suggestion):
Hm am I the only one who finds it confusing that we manually specify `--color-orange` here as a theme variable that is _not_ inline and yet, because of the plugin that we import later, it won't be emitted as CSS variable. I understand the reason that we don't want to emit CSS variables for plugins because of the weird names that some plugins use but if we overwrite something that is part of the user configured theme, I would kind of expect the CSS variable to still work (if someone writes a `@theme` like this, I think they expect `var(--color-orange)` to work. 🤔 

Code after:
        ['bg-potato', 'bg-tomato'],
      ),
    ).toMatchInlineSnapshot(`
      ":root {
        --color-potato: #ac855b;
        --color-tomato: tomato;
      }

      .bg-potato {
        background-color: var(--color-potato, #ac855b);
      }

      .bg-tomato {
        background-color: var(--color-tomato, tomato);
      }"
    `)
  })

  test('`default` theme values can be overridden by plugin theme values', async () => {
    let { build } = await compile(
      css`
        @theme default {
          --color-red: red;
        }
        @theme {
          --color-orange: orange;
        }
        @plugin "my-plugin";
        @tailwind utilities;
      `,
      {
        loadPlugin: async () => {
          return plugin(({}) => {}, {
            theme: {
              extend: {
                colors: {
                  red: 'tomato',
                  orange: '#f28500',
                },
              },
            },
          })
        },
      },
    )

    expect(optimizeCss(build(['text-red', 'text-orange'])).trim()).toMatchInlineSnapshot(`
      ":root {
        --color-orange: orange;
      }
Repository: tailwindlabs/tailwindcss
File: integrations/utils.ts (TypeScript)

Code before:
) {
  let end = Date.now() + timeout
  let error: any
  while (Date.now() < end) {
    try {
      return await fn()
    } catch (err) {
      error = err
      await new Promise((resolve) => setTimeout(resolve, delay))
    }
  }
  throw error
}

export async function fetchStyles(port: number, path = '/'): Promise<string> {
  let index = await fetch(`http://localhost:${port}${path}`)
  let html = await index.text()

  let linkRegex = /<link rel="stylesheet" href="([a-zA-Z0-9\/_\.\?=%-]+)"/gi
  let styleRegex = /<style\b[^>]*>([\s\S]*?)<\/style>/gi

  let stylesheets: string[] = []

  let paths: string[] = []
  let match
  while ((match = linkRegex.exec(html)) !== null) {
    let path: string = match[1]
    if (path.startsWith('./')) {
      path = path.slice(1)
    }
    paths.push(path)
  }
  stylesheets.push(
    ...(await Promise.all(
      paths.map(async (path) => {
        let css = await fetch(`http://localhost:${port}${path}`, {
          headers: {
            Accept: 'text/css',
          },
        })
        return await css.text()
      }),
    )),
  )

  while ((match = styleRegex.exec(html)) !== null) {
    stylesheets.push(match[1])
  }

  return stylesheets.reduce((acc, css) => {
    return acc + '\n' + css

Review comment (suggestion):
```suggestion
  for (let match of html.matchAll(linkRegex)) {
```

Code after:
) {
  let end = Date.now() + timeout
  let error: any
  while (Date.now() < end) {
    try {
      return await fn()
    } catch (err) {
      error = err
      await new Promise((resolve) => setTimeout(resolve, delay))
    }
  }
  throw error
}

export async function fetchStyles(port: number, path = '/'): Promise<string> {
  let index = await fetch(`http://localhost:${port}${path}`)
  let html = await index.text()

  let linkRegex = /<link rel="stylesheet" href="([a-zA-Z0-9\/_\.\?=%-]+)"/gi
  let styleRegex = /<style\b[^>]*>([\s\S]*?)<\/style>/gi

  let stylesheets: string[] = []

  let paths: string[] = []
  let match
  for (let match of html.matchAll(linkRegex)) {
    let path: string = match[1]
    if (path.startsWith('./')) {
      path = path.slice(1)
    }
    paths.push(path)
  }
  stylesheets.push(
    ...(await Promise.all(
      paths.map(async (path) => {
        let css = await fetch(`http://localhost:${port}${path}`, {
          headers: {
            Accept: 'text/css',
          },
        })
        return await css.text()
      }),
    )),
  )

  for (let match of html.matchAll(styleRegex)) {
    stylesheets.push(match[1])
  }

  return stylesheets.reduce((acc, css) => {
    return acc + '\n' + css
Repository: tailwindlabs/tailwindcss
File: integrations/utils.ts (TypeScript)

Code before:

  let stylesheets: string[] = []

  let paths: string[] = []
  let match
  while ((match = linkRegex.exec(html)) !== null) {
    let path: string = match[1]
    if (path.startsWith('./')) {
      path = path.slice(1)
    }
    paths.push(path)
  }
  stylesheets.push(
    ...(await Promise.all(
      paths.map(async (path) => {
        let css = await fetch(`http://localhost:${port}${path}`, {
          headers: {
            Accept: 'text/css',
          },
        })
        return await css.text()
      }),
    )),
  )

  while ((match = styleRegex.exec(html)) !== null) {
    stylesheets.push(match[1])
  }

  return stylesheets.reduce((acc, css) => {
    return acc + '\n' + css
  }, '')
}

async function gracefullyRemove(dir: string) {
  // Skip removing the directory in CI because it can stall on Windows
  if (!process.env.CI) {
    await fs.rm(dir, { recursive: true, force: true })
  }
}

async function dirExists(dir: string): Promise<boolean> {
  try {
    return await fs.stat(dir).then((stat) => stat.isDirectory())
  } catch {
    return false
  }
}


Review comment (suggestion):
```suggestion
  for (let match of html.matchAll(styleRegex)) {
```

Code after:

  let stylesheets: string[] = []

  let paths: string[] = []
  let match
  for (let match of html.matchAll(linkRegex)) {
    let path: string = match[1]
    if (path.startsWith('./')) {
      path = path.slice(1)
    }
    paths.push(path)
  }
  stylesheets.push(
    ...(await Promise.all(
      paths.map(async (path) => {
        let css = await fetch(`http://localhost:${port}${path}`, {
          headers: {
            Accept: 'text/css',
          },
        })
        return await css.text()
      }),
    )),
  )

  for (let match of html.matchAll(styleRegex)) {
    stylesheets.push(match[1])
  }

  return stylesheets.reduce((acc, css) => {
    return acc + '\n' + css
  }, '')
}

async function gracefullyRemove(dir: string) {
  // Skip removing the directory in CI because it can stall on Windows
  if (!process.env.CI) {
    await fs.rm(dir, { recursive: true, force: true })
  }
}

async function dirExists(dir: string): Promise<boolean> {
  try {
    return await fs.stat(dir).then((stat) => stat.isDirectory())
  } catch {
    return false
  }
}
Repository: tailwindlabs/tailwindcss
File: packages/@tailwindcss-node/src/index.ts (TypeScript)

Code before:
import * as Module from 'node:module'
import { pathToFileURL } from 'node:url'
export * from './compile'

// In Bun, ESM modules will also populate `require.cache`, so the module hook is
// not necessary.
if (!process.versions.bun) {
  let localRequire = Module.createRequire(import.meta.url)
  Module.register?.(pathToFileURL(localRequire.resolve('@tailwindcss/node/esm-cache-loader')))
}


Review comment (performance):
Maybe add a comment as to _why_ we're doing the conditional check?

Something like this maybe?

```
// Register was not added until Node v18.19.0 and v20.6.0
// Not calling it means that while ESM dependencies don't get reloaded the actual included files will because they cache bust directly by using `?id=…`
```

Code after:
import * as Module from 'node:module'
import { pathToFileURL } from 'node:url'
export * from './compile'

// In Bun, ESM modules will also populate `require.cache`, so the module hook is
// not necessary.
if (!process.versions.bun) {
  let localRequire = Module.createRequire(import.meta.url)

  // `Module#register` was added in Node v18.19.0 and v20.6.0
  //
  // Not calling it means that while ESM dependencies don't get reloaded, the
  // actual included files will because they cache bust directly via `?id=…`
  Module.register?.(pathToFileURL(localRequire.resolve('@tailwindcss/node/esm-cache-loader')))
}
Repository: tailwindlabs/tailwindcss
File: integrations/vite/css-modules.test.ts (TypeScript)

Code before:
import { describe, expect } from 'vitest'
import { css, html, test, ts, txt } from '../utils'
;['postcss', 'lightningcss'].forEach((transformer) => {
  describe(transformer, () => {
    test(
      `dev mode`,
      {
        fs: {
          'package.json': txt`
            {
              "type": "module",
              "dependencies": {
                "@tailwindcss/vite": "workspace:^",
                "tailwindcss": "workspace:^"
              },
              "devDependencies": {
                ${transformer === 'lightningcss' ? `"lightningcss": "^1.26.0",` : ''}
                "vite": "^5.3.5"
              }
            }
          `,
          'vite.config.ts': ts`
            import tailwindcss from '@tailwindcss/vite'
            import { defineConfig } from 'vite'

            export default defineConfig({
              css: ${transformer === 'postcss' ? '{}' : "{ transformer: 'lightningcss' }"},
              build: { cssMinify: false },

Review comment (suggestion):
I know we do this in other places, but I think a normal for loop is a bit cleaner here (gets rid of the `;` and allows a new line again)

```suggestion
for (let transformer of ['postcss', 'lightningcss']) {
```

Or, if it gives us any benefits, we could use `describe.each` as well: https://vitest.dev/api/#describe-each

Code after:
import { describe, expect } from 'vitest'
import { css, html, test, ts, txt } from '../utils'

for (let transformer of ['postcss', 'lightningcss']) {
  describe(transformer, () => {
    test(
      `dev mode`,
      {
        fs: {
          'package.json': txt`
            {
              "type": "module",
              "dependencies": {
                "@tailwindcss/vite": "workspace:^",
                "tailwindcss": "workspace:^"
              },
              "devDependencies": {
                ${transformer === 'lightningcss' ? `"lightningcss": "^1.26.0",` : ''}
                "vite": "^5.3.5"
              }
            }
          `,
          'vite.config.ts': ts`
            import tailwindcss from '@tailwindcss/vite'
            import { defineConfig } from 'vite'

            export default defineConfig({
              css: ${transformer === 'postcss' ? '{}' : "{ transformer: 'lightningcss' }"},