Add Last-Modified conditional handling for static files
Co-authored-by: Theo Browne <[email protected]>
This commit is contained in:
1 parent
4ed9832794
commit
f8aae93a16
3 files changed
+102
-3
No files matched your search
@@ -245,6 +245,10 @@ async function main() {
|
||||
if (!assetEtag || assetEtag.length === 0) {
|
||||
throw new Error("Smoke test failed: expected ETag on built asset response.");
|
||||
}
|
||||
const assetLastModified = assetResponse.headers.get("last-modified");
|
||||
if (!assetLastModified || assetLastModified.length === 0) {
|
||||
throw new Error("Smoke test failed: expected Last-Modified on built asset response.");
|
||||
}
|
||||
const assetContentLength = Number(assetResponse.headers.get("content-length") ?? "0");
|
||||
if (!Number.isFinite(assetContentLength) || assetContentLength <= 0) {
|
||||
throw new Error(
|
||||
@@ -289,6 +293,27 @@ async function main() {
|
||||
`Smoke test failed: expected weak conditional asset status 304, received ${weakConditionalAsset.status}.`,
|
||||
);
|
||||
}
|
||||
const modifiedSinceAsset = await fetch(assetUrl, {
|
||||
headers: {
|
||||
"If-Modified-Since": assetLastModified,
|
||||
},
|
||||
});
|
||||
if (modifiedSinceAsset.status !== 304) {
|
||||
throw new Error(
|
||||
`Smoke test failed: expected If-Modified-Since asset status 304, received ${modifiedSinceAsset.status}.`,
|
||||
);
|
||||
}
|
||||
const precedenceAsset = await fetch(assetUrl, {
|
||||
headers: {
|
||||
"If-Modified-Since": assetLastModified,
|
||||
"If-None-Match": "\"definitely-different-etag\"",
|
||||
},
|
||||
});
|
||||
if (precedenceAsset.status !== 200) {
|
||||
throw new Error(
|
||||
`Smoke test failed: expected If-None-Match precedence status 200, received ${precedenceAsset.status}.`,
|
||||
);
|
||||
}
|
||||
const conditionalHeadAsset = await fetch(assetUrl, {
|
||||
method: "HEAD",
|
||||
headers: {
|
||||
@@ -321,6 +346,17 @@ async function main() {
|
||||
`Smoke test failed: expected no content-length (or 0) on conditional HEAD asset response, got ${conditionalHeadAssetContentLength}.`,
|
||||
);
|
||||
}
|
||||
const modifiedSinceHeadAsset = await fetch(assetUrl, {
|
||||
method: "HEAD",
|
||||
headers: {
|
||||
"If-Modified-Since": assetLastModified,
|
||||
},
|
||||
});
|
||||
if (modifiedSinceHeadAsset.status !== 304) {
|
||||
throw new Error(
|
||||
`Smoke test failed: expected If-Modified-Since HEAD asset status 304, received ${modifiedSinceHeadAsset.status}.`,
|
||||
);
|
||||
}
|
||||
const rangeEnd = Math.min(15, assetContentLength - 1);
|
||||
const rangedAsset = await fetch(assetUrl, {
|
||||
headers: {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
formatStartupError,
|
||||
ifModifiedSinceSatisfied,
|
||||
ifNoneMatchSatisfied,
|
||||
parseByteRangeHeader,
|
||||
parseCliOptions,
|
||||
@@ -959,6 +960,32 @@ describe("ifNoneMatchSatisfied", () => {
|
||||
it("does not match non-identical etags", () => {
|
||||
expect(ifNoneMatchSatisfied("\"foo\", \"bar\"", "\"abc\"")).toBe(false);
|
||||
});
|
||||
|
||||
it("supports array-valued header representations", () => {
|
||||
expect(ifNoneMatchSatisfied(["\"foo\"", "\"abc\""], "\"abc\"")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ifModifiedSinceSatisfied", () => {
|
||||
it("returns false for missing or invalid dates", () => {
|
||||
expect(ifModifiedSinceSatisfied(undefined, Date.now())).toBe(false);
|
||||
expect(ifModifiedSinceSatisfied("not-a-date", Date.now())).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true when resource has not changed since provided timestamp", () => {
|
||||
const modifiedAt = Date.parse("2026-01-01T12:00:00.100Z");
|
||||
expect(ifModifiedSinceSatisfied("Thu, 01 Jan 2026 12:00:00 GMT", modifiedAt)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when resource changed after provided timestamp", () => {
|
||||
const modifiedAt = Date.parse("2026-01-01T12:00:01.000Z");
|
||||
expect(ifModifiedSinceSatisfied("Thu, 01 Jan 2026 12:00:00 GMT", modifiedAt)).toBe(false);
|
||||
});
|
||||
|
||||
it("supports array-valued header representations", () => {
|
||||
const modifiedAt = Date.parse("2026-01-01T12:00:00.000Z");
|
||||
expect(ifModifiedSinceSatisfied(["Thu, 01 Jan 2026 12:00:00 GMT"], modifiedAt)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveStaticAssetReadTarget", () => {
|
||||
|
||||
+39
-3
@@ -521,12 +521,18 @@ function normalizeWeakEtag(etag: string): string {
|
||||
return trimmed.startsWith("W/") ? trimmed.slice(2).trim() : trimmed;
|
||||
}
|
||||
|
||||
export function ifNoneMatchSatisfied(ifNoneMatchHeader: string | undefined, etag: string): boolean {
|
||||
export function ifNoneMatchSatisfied(
|
||||
ifNoneMatchHeader: string | string[] | undefined,
|
||||
etag: string,
|
||||
): boolean {
|
||||
if (!ifNoneMatchHeader) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const candidates = ifNoneMatchHeader
|
||||
const rawHeaderValue = Array.isArray(ifNoneMatchHeader)
|
||||
? ifNoneMatchHeader.join(",")
|
||||
: ifNoneMatchHeader;
|
||||
const candidates = rawHeaderValue
|
||||
.split(",")
|
||||
.map((token) => token.trim())
|
||||
.filter((token) => token.length > 0);
|
||||
@@ -542,6 +548,29 @@ export function ifNoneMatchSatisfied(ifNoneMatchHeader: string | undefined, etag
|
||||
return candidates.some((candidate) => normalizeWeakEtag(candidate) === normalizedEtag);
|
||||
}
|
||||
|
||||
export function ifModifiedSinceSatisfied(
|
||||
ifModifiedSinceHeader: string | string[] | undefined,
|
||||
modifiedAtMs: number,
|
||||
): boolean {
|
||||
if (!ifModifiedSinceHeader) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const rawHeaderValue = Array.isArray(ifModifiedSinceHeader)
|
||||
? ifModifiedSinceHeader[0]
|
||||
: ifModifiedSinceHeader;
|
||||
if (!rawHeaderValue) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const parsedTimestamp = Date.parse(rawHeaderValue);
|
||||
if (!Number.isFinite(parsedTimestamp)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Math.floor(modifiedAtMs / 1_000) <= Math.floor(parsedTimestamp / 1_000);
|
||||
}
|
||||
|
||||
export function parseByteRangeHeader(
|
||||
rangeHeaderValue: string | undefined,
|
||||
fileSize: number,
|
||||
@@ -797,10 +826,17 @@ function startStaticWebServer(distRoot: string, port: number) {
|
||||
}
|
||||
|
||||
const etag = staticEtagFor(stats);
|
||||
const lastModified = stats.mtime.toUTCString();
|
||||
const hasIfNoneMatchHeader = request.headers["if-none-match"] !== undefined;
|
||||
const ifNoneMatchMatches = ifNoneMatchSatisfied(request.headers["if-none-match"], etag);
|
||||
const ifModifiedSinceMatches = hasIfNoneMatchHeader
|
||||
? false
|
||||
: ifModifiedSinceSatisfied(request.headers["if-modified-since"], stats.mtimeMs);
|
||||
|
||||
response.statusCode = resolvedRange ? 206 : 200;
|
||||
response.setHeader("Content-Type", contentTypeFor(targetPath));
|
||||
response.setHeader("ETag", etag);
|
||||
response.setHeader("Last-Modified", lastModified);
|
||||
response.setHeader(
|
||||
"Content-Length",
|
||||
String(resolvedRange ? resolvedRange.end - resolvedRange.start + 1 : stats.size),
|
||||
@@ -814,7 +850,7 @@ function startStaticWebServer(distRoot: string, port: number) {
|
||||
cacheControl: cacheControlFor(targetPath),
|
||||
});
|
||||
|
||||
if (!resolvedRange && ifNoneMatchSatisfied(request.headers["if-none-match"], etag)) {
|
||||
if (!resolvedRange && (ifNoneMatchMatches || ifModifiedSinceMatches)) {
|
||||
response.statusCode = 304;
|
||||
response.removeHeader("Content-Length");
|
||||
response.end();
|
||||
|
||||
Reference in new issue
Block a user