|
| 1 | +import type { Plugin } from 'vite' |
| 2 | +import { basename } from 'pathe' |
| 3 | +import { expect, test } from 'vitest' |
| 4 | +import { runBrowserTests } from './utils' |
| 5 | + |
| 6 | +const versionedRequestRegexp = /[?&]v=\w{8}/ |
| 7 | + |
| 8 | +function recordDependencyResponses() { |
| 9 | + const responses: { kind: 'chunk' | 'entry'; cacheControl: string }[] = [] |
| 10 | + const plugin: Plugin = { |
| 11 | + name: 'record-dependency-responses', |
| 12 | + configureServer(server) { |
| 13 | + server.middlewares.use((req, res, next) => { |
| 14 | + res.on('finish', () => { |
| 15 | + if (!req.url || !versionedRequestRegexp.test(req.url)) { |
| 16 | + return |
| 17 | + } |
| 18 | + const chunks = server.environments.client.depsOptimizer?.metadata.chunks ?? {} |
| 19 | + const chunkFiles = new Set(Object.values(chunks).map((chunk) => basename(chunk.file))) |
| 20 | + const file = basename(new URL(req.url, 'http://localhost').pathname) |
| 21 | + responses.push({ |
| 22 | + kind: chunkFiles.has(file) ? 'chunk' : 'entry', |
| 23 | + cacheControl: String(res.getHeader('cache-control')), |
| 24 | + }) |
| 25 | + }) |
| 26 | + next() |
| 27 | + }) |
| 28 | + }, |
| 29 | + } |
| 30 | + return { plugin, responses } |
| 31 | +} |
| 32 | + |
| 33 | +function summarize(responses: { kind: string; cacheControl: string }[]) { |
| 34 | + const summary: Record<string, string[]> = {} |
| 35 | + for (const { kind, cacheControl } of responses) { |
| 36 | + const values = (summary[kind] ??= []) |
| 37 | + if (!values.includes(cacheControl)) { |
| 38 | + values.push(cacheControl) |
| 39 | + } |
| 40 | + } |
| 41 | + return summary |
| 42 | +} |
| 43 | + |
| 44 | +test('shared optimizer chunks keep immutable caching when mocks are served by request interception', async () => { |
| 45 | + const { plugin, responses } = recordDependencyResponses() |
| 46 | + const { stderr } = await runBrowserTests( |
| 47 | + { |
| 48 | + root: './fixtures/optimized-chunks-cache', |
| 49 | + browser: { importMapMocks: false }, |
| 50 | + }, |
| 51 | + undefined, |
| 52 | + { plugins: [plugin] }, |
| 53 | + ) |
| 54 | + |
| 55 | + expect(stderr).toReportNoErrors() |
| 56 | + expect(summarize(responses)).toMatchInlineSnapshot(` |
| 57 | + { |
| 58 | + "chunk": [ |
| 59 | + "max-age=31536000,immutable", |
| 60 | + ], |
| 61 | + "entry": [ |
| 62 | + "no-cache", |
| 63 | + ], |
| 64 | + } |
| 65 | + `) |
| 66 | +}) |
0 commit comments