Skip to content

Commit

Permalink
feat: handle static assets in case-sensitive manner
Browse files Browse the repository at this point in the history
  • Loading branch information
benmccann committed Oct 14, 2022
1 parent f542727 commit 24ff932
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
33 changes: 32 additions & 1 deletion packages/vite/src/node/server/middlewares/static.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import fs from 'node:fs'
import path from 'node:path'
import type { OutgoingHttpHeaders, ServerResponse } from 'node:http'
import type { Options } from 'sirv'
Expand Down Expand Up @@ -48,8 +49,20 @@ export function servePublicMiddleware(

// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
return function viteServePublicMiddleware(req, res, next) {
const url = req.url!
// skip import request and internal requests `/@fs/ /@vite-client` etc...
if (isImportRequest(req.url!) || isInternalRequest(req.url!)) {
if (isImportRequest(url) || isInternalRequest(url)) {
return next()
}
const queryStringIdx = url.indexOf('?')
const pathname =
queryStringIdx >= 0 ? url.substring(0, queryStringIdx) : url
const file = dir + pathname
if (
!fs.existsSync(file) ||
fs.statSync(file).isDirectory() ||
!hasCorrectCase(file, dir)
) {
return next()
}
serve(req, res, next)
Expand Down Expand Up @@ -217,3 +230,21 @@ function renderRestrictedErrorHTML(msg: string): string {
</body>
`
}

/**
* Determine if a file is being requested with the correct case, to ensure
* consistent behaviour between dev and prod and across operating systems.
* Note that we can't use realpath here, because we don't want to follow
* symlinks.
*/
function hasCorrectCase(file: string, assets: string): boolean {
if (file === assets) return true

const parent = path.dirname(file)

if (fs.readdirSync(parent).includes(path.basename(file))) {
return hasCorrectCase(parent, assets)
}

return false
}
7 changes: 7 additions & 0 deletions playground/assets/__tests__/assets.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import fetch from 'node-fetch'
import { describe, expect, test } from 'vitest'
import {
browserLogs,
Expand All @@ -12,6 +13,7 @@ import {
readFile,
readManifest,
untilUpdated,
viteTestUrl,
watcher
} from '~utils'

Expand All @@ -27,6 +29,11 @@ test('should have no 404s', () => {
})
})

test('should get a 404 when using incorrect case', async () => {
expect((await fetch(viteTestUrl + 'raw.js')).status).toBe(200)
expect((await fetch(viteTestUrl + 'RAW.js')).status).toBe(404)
})

describe('injected scripts', () => {
test('@vite/client', async () => {
const hasClient = await page.$(
Expand Down

0 comments on commit 24ff932

Please sign in to comment.