Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: send server headers in dev #107

Merged
merged 7 commits into from
May 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/hot-pandas-tan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"vite-plugin-static-copy": patch
---

send headers set by `server.headers` in dev
70 changes: 45 additions & 25 deletions src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { parse } from '@polka/url'
import { lookup } from 'mrmime'
import type { Stats } from 'node:fs'
import { statSync, createReadStream, existsSync } from 'node:fs'
import type { Connect } from 'vite'
import type { Connect, ServerOptions } from 'vite'
import type {
IncomingMessage,
OutgoingHttpHeaders,
Expand Down Expand Up @@ -205,17 +205,13 @@ function sendStatic(
createReadStream(file, opts).pipe(res)
}

async function sendTransform(
function sendTransform(
req: IncomingMessage,
res: ServerResponse,
file: string,
transform: TransformOptionObject
): Promise<boolean> {
const transformedContent = await getTransformedContent(file, transform)
if (transformedContent === null) {
return false
}

transform: TransformOptionObject,
transformedContent: string | Buffer
): void {
const transformHeaders = getTransformHeaders(
file,
transform.encoding,
Expand All @@ -225,15 +221,36 @@ async function sendTransform(
if (req.headers['if-none-match'] === transformHeaders['ETag']) {
res.writeHead(304)
res.end()
return true
return
}

const code = 200
const headers = getMergeHeaders(transformHeaders, res)

res.writeHead(code, headers)
res.end(transformedContent)
return true
return
}

function setHeaders(
res: ServerResponse,
pathname: string,
headers: OutgoingHttpHeaders | undefined
) {
// Matches js, jsx, ts, tsx.
// The reason this is done, is that the .ts file extension is reserved
// for the MIME type video/mp2t. In almost all cases, we can expect
// these files to be TypeScript files, and for Vite to serve them with
// this Content-Type.
if (/\.[tj]sx?$/.test(pathname)) {
res.setHeader('Content-Type', 'application/javascript')
}

if (headers) {
for (const name in headers) {
res.setHeader(name, headers[name]!)
}
}
}

function return404(res: ServerResponse, next: Connect.NextFunction) {
Expand All @@ -246,7 +263,11 @@ function return404(res: ServerResponse, next: Connect.NextFunction) {
}

export function serveStaticCopyMiddleware(
{ root, publicDir }: { root: string; publicDir: string },
{
root,
publicDir,
server
}: { root: string; publicDir: string; server: ServerOptions },
fileMap: FileMap
): Connect.NextHandleFunction {
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
Expand All @@ -267,30 +288,29 @@ export function serveStaticCopyMiddleware(
return
}

// Matches js, jsx, ts, tsx.
// The reason this is done, is that the .ts file extension is reserved
// for the MIME type video/mp2t. In almost all cases, we can expect
// these files to be TypeScript files, and for Vite to serve them with
// this Content-Type.
if (/\.[tj]sx?$/.test(pathname)) {
res.setHeader('Content-Type', 'application/javascript')
}

const transformOption = resolveTransformOption(data.transform)
if (transformOption) {
const sent = await sendTransform(
req,
res,
const transformedContent = await getTransformedContent(
data.filepath,
transformOption
)
if (!sent) {
if (transformedContent === null) {
return404(res, next)
return
}

setHeaders(res, pathname, server.headers)
sendTransform(
req,
res,
data.filepath,
transformOption,
transformedContent
)
return
}

setHeaders(res, pathname, server.headers)
sendStatic(req, res, data.filepath, data.stats)
} catch (e) {
if (e instanceof Error) {
Expand Down
6 changes: 6 additions & 0 deletions test/fixtures/vite.other.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ import { viteStaticCopy } from 'vite-plugin-static-copy'

export default defineConfig({
appType: 'custom', // disable SPA/MPA fallback
server: {
headers: {
'Cross-Origin-Embedder-Policy': 'require-corp',
'Cross-Origin-Opener-Policy': 'same-origin'
}
},
plugins: [
viteStaticCopy({
targets: [
Expand Down
9 changes: 9 additions & 0 deletions test/tests.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,15 @@ describe('serve', () => {
expect(res.status).toBe(200)
expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')
})

test.concurrent('headers', async () => {
const res = await fetchFromServer(server, '/fixture1/foo.txt')
expect(res.status).toBe(200)
expect(res.headers.get('Cross-Origin-Embedder-Policy')).toBe(
'require-corp'
)
expect(res.headers.get('Cross-Origin-Opener-Policy')).toBe('same-origin')
})
})
})

Expand Down
Loading