Skip to content

Commit

Permalink
Merge pull request #26 from relevantsam/main
Browse files Browse the repository at this point in the history
fix: support system paths (windows)
  • Loading branch information
SaltyAom authored Apr 24, 2024
2 parents f3f0607 + b1863f5 commit edb2931
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 16 deletions.
38 changes: 24 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { Elysia, NotFoundError } from 'elysia'

import { readdir, stat } from 'fs/promises'
import { resolve, resolve as resolveFn, join } from 'path'
import { resolve, resolve as resolveFn, join, sep} from 'path'
import Cache from 'node-cache'

import { generateETag, isCached } from './cache'
import { Stats } from 'fs'

const URL_PATH_SEP = '/'
const fileExists = (path: string) => stat(path).then(() => true, () => false)

const statCache = new Cache({
Expand Down Expand Up @@ -35,7 +36,7 @@ const listFiles = async (dir: string): Promise<string[]> => {

const all = await Promise.all(
files.map(async (name) => {
const file = dir + '/' + name
const file = dir + sep + name
const stats = await stat(file)

return stats && stats.isDirectory()
Expand Down Expand Up @@ -153,8 +154,9 @@ export const staticPlugin = async <Prefix extends string = '/prefix'>(
}
) => {
const files = await listFiles(resolveFn(assets))
const isFSSepUnsafe = sep !== URL_PATH_SEP

if (prefix === '/') prefix = '' as Prefix
if (prefix === URL_PATH_SEP) prefix = '' as Prefix

const shouldIgnore = (file: string) => {
if (!ignorePatterns.length) return false
Expand Down Expand Up @@ -191,7 +193,7 @@ export const staticPlugin = async <Prefix extends string = '/prefix'>(

let fileName = filePath
.replace(resolve(), '')
.replace(`${assets}/`, '')
.replace(`${assets}${sep}`, '')

if (noExtension) {
const temp = fileName.split('.')
Expand All @@ -203,8 +205,11 @@ export const staticPlugin = async <Prefix extends string = '/prefix'>(
const file = Bun.file(filePath)
const etag = await generateETag(file)

const pathName = isFSSepUnsafe ?
prefix + fileName.split(sep).join(URL_PATH_SEP) :
join(prefix, fileName)
app.get(
join(prefix, fileName),
pathName,
noCache
? new Response(file, {
headers
Expand All @@ -226,15 +231,15 @@ export const staticPlugin = async <Prefix extends string = '/prefix'>(
}
)

if (indexHTML && fileName.endsWith('/index.html'))
if (indexHTML && pathName.endsWith('/index.html'))
app.get(
join(prefix, fileName.replace('/index.html', '')),
join(prefix, pathName.replace('/index.html', '')),
noCache
? new Response(file, {
headers
})
: async ({ headers: reqHeaders }) => {
if (await isCached(reqHeaders, etag, filePath)) {
if (await isCached(reqHeaders, etag, pathName)) {
return new Response(null, {
status: 304,
headers
Expand All @@ -260,10 +265,15 @@ export const staticPlugin = async <Prefix extends string = '/prefix'>(
app.onError(() => {}).get(
`${prefix}/*`,
async ({ params, headers: reqHeaders }) => {
const path = enableDecodeURI
let path = enableDecodeURI
? decodeURI(`${assets}/${decodeURI(params['*'])}`)
: `${assets}/${params['*']}`
// Handle varying filepath separators
if (isFSSepUnsafe) {
path = path.replace(URL_PATH_SEP, sep)
}

// Note that path must match the system separator
if (shouldIgnore(path)) throw new NotFoundError()

try {
Expand All @@ -286,21 +296,21 @@ export const staticPlugin = async <Prefix extends string = '/prefix'>(
indexHTML &&
(hasCache =
htmlCache.get<boolean>(
`${path}/index.html`
`${path}${sep}index.html`
) ??
(await fileExists(`${path}/index.html`)))
(await fileExists(`${path}${sep}index.html`)))
) {
if (hasCache === undefined)
htmlCache.set(
`${path}/index.html`,
`${path}${sep}index.html`,
true
)

file = Bun.file(`${path}/index.html`)
file = Bun.file(`${path}${sep}index.html`)
} else {
if (indexHTML && hasCache === undefined)
htmlCache.set(
`${path}/index.html`,
`${path}${sep}index.html`,
false
)

Expand Down
4 changes: 2 additions & 2 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Elysia } from 'elysia'
import { staticPlugin } from '../src'

import { describe, expect, it } from 'bun:test'
import { join } from 'path'
import { join, sep } from 'path'

const req = (path: string) => new Request(`http://localhost${path}`)

Expand Down Expand Up @@ -98,7 +98,7 @@ describe('Static Plugin', () => {
it('ignore string pattern', async () => {
const app = new Elysia({ forceErrorEncapsulation: true }).use(
staticPlugin({
ignorePatterns: ['public/takodachi.png']
ignorePatterns: [`public${sep}takodachi.png`]
})
)

Expand Down

0 comments on commit edb2931

Please sign in to comment.