Skip to content

Commit 60eb5e9

Browse files
authored
fix(dispatch): serve .md and other text assets with correct content-type (#215)
* fix(dispatch): serve correct content-type for .md and re-derive stored octet-stream Add md/markdown/yaml/yml/toml to the MIME table, and treat a stored application/octet-stream as unknown so it is re-derived from the path at serve time. Content-addressed assets are never re-uploaded, so this heals already-deployed files (e.g. viteplus.dev .md pages) without a redeploy. * refactor(dispatch): fold application/null sentinel into resolveAssetContentType Return string | undefined from the resolver so the 'omit Content-Type header' decision lives in one place, collapsing the three duplicated `contentType !== 'application/null'` guards at the call sites to a plain `if (contentType)`.
1 parent 7d0bd71 commit 60eb5e9

4 files changed

Lines changed: 180 additions & 9 deletions

File tree

‎packages/dispatch/src/index.ts‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import {
1818
} from './isr.ts';
1919
import { recordRequest, sendUsageEvent, type RequestType } from './metering.ts';
2020
import { applyRoutingRules, mergeQueryIntoLocation, type RedirectRule } from './routing-rules.ts';
21-
import { resolveStaticPath, getContentType } from './static.ts';
21+
import { resolveStaticPath, resolveAssetContentType } from './static.ts';
2222
import type { AssetConfig } from './static.ts';
2323
import { buildVariantOriginalUrl, type QueryAllowlist } from './variant-key.ts';
2424

@@ -1132,13 +1132,12 @@ async function fetchStaticAsset(
11321132
if (!obj) {
11331133
return null;
11341134
}
1135-
const contentType = obj.httpMetadata?.contentType ?? getContentType(path);
1135+
const contentType = resolveAssetContentType(obj.httpMetadata?.contentType, path);
11361136
const headers: HeadersInit = {
11371137
ETag: obj.httpEtag,
11381138
...(obj.size ? { 'Content-Length': String(obj.size) } : {}),
11391139
};
1140-
// "application/null" is a sentinel meaning "no Content-Type header" (matches Wrangler)
1141-
if (contentType && contentType !== 'application/null') {
1140+
if (contentType) {
11421141
(headers as Record<string, string>)['Content-Type'] = contentType;
11431142
}
11441143
return new Response(obj.body, { headers });
@@ -1151,11 +1150,11 @@ async function fetchStaticAsset(
11511150
cacheTtl: 86400,
11521151
});
11531152
if (scoped.value) {
1154-
const contentType = scoped.metadata?.ct ?? getContentType(path);
1153+
const contentType = resolveAssetContentType(scoped.metadata?.ct, path);
11551154
const headers: HeadersInit = {
11561155
'Content-Length': String((scoped.value as ArrayBuffer).byteLength),
11571156
};
1158-
if (contentType && contentType !== 'application/null') {
1157+
if (contentType) {
11591158
(headers as Record<string, string>)['Content-Type'] = contentType;
11601159
}
11611160
return new Response(scoped.value, { headers });
@@ -1169,12 +1168,11 @@ async function fetchStaticAsset(
11691168
if (!value) {
11701169
return null;
11711170
}
1172-
const contentType = metadata?.ct ?? getContentType(path);
1171+
const contentType = resolveAssetContentType(metadata?.ct, path);
11731172
const headers: HeadersInit = {
11741173
'Content-Length': String((value as ArrayBuffer).byteLength),
11751174
};
1176-
// "application/null" is a sentinel meaning "no Content-Type header" (matches Wrangler)
1177-
if (contentType && contentType !== 'application/null') {
1175+
if (contentType) {
11781176
(headers as Record<string, string>)['Content-Type'] = contentType;
11791177
}
11801178
return new Response(value, { headers });

‎packages/dispatch/src/static.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,11 @@ const MIME_TYPES: Record<string, string> = {
127127
svg: 'image/svg+xml; charset=utf-8',
128128
txt: 'text/plain; charset=utf-8',
129129
csv: 'text/csv; charset=utf-8',
130+
md: 'text/markdown; charset=utf-8',
131+
markdown: 'text/markdown; charset=utf-8',
132+
yaml: 'text/yaml; charset=utf-8',
133+
yml: 'text/yaml; charset=utf-8',
134+
toml: 'application/toml',
130135
png: 'image/png',
131136
jpg: 'image/jpeg',
132137
jpeg: 'image/jpeg',
@@ -156,3 +161,32 @@ export function getContentType(path: string): string {
156161
const ext = path.split('.').pop()?.toLowerCase() ?? '';
157162
return MIME_TYPES[ext] ?? 'application/octet-stream';
158163
}
164+
165+
/**
166+
* Resolve the Content-Type to serve for a stored asset, reconciling the value
167+
* persisted at upload time (R2 `httpMetadata.contentType` / KV `ct` metadata)
168+
* with a fresh path-based lookup. Returns `undefined` when no Content-Type
169+
* header should be emitted.
170+
*
171+
* `application/null` is a sentinel (matching Wrangler) meaning "omit the
172+
* Content-Type header entirely".
173+
*
174+
* `application/octet-stream` is the uploader's no-information default: older
175+
* CLI versions stamped it on any extension their MIME table did not recognize
176+
* (e.g. `.md`). Because assets are content-addressed and never re-uploaded,
177+
* those stale octet-stream values can't be corrected at the source, so we
178+
* treat a stored octet-stream as "unknown" and re-derive from the path here.
179+
* Any other stored value is authoritative and honored as-is.
180+
*/
181+
export function resolveAssetContentType(
182+
stored: string | null | undefined,
183+
path: string,
184+
): string | undefined {
185+
if (stored === 'application/null') {
186+
return undefined;
187+
}
188+
if (!stored || stored === 'application/octet-stream') {
189+
return getContentType(path);
190+
}
191+
return stored;
192+
}

‎packages/dispatch/test/unit/index.test.ts‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2926,3 +2926,125 @@ describe('static deployment caching (KV/R2)', () => {
29262926
);
29272927
});
29282928
});
2929+
2930+
describe('static asset content-type normalization', () => {
2931+
// Assets uploaded before the CLI's MIME table knew an extension carry a
2932+
// stored `application/octet-stream` content type (R2 httpMetadata / KV `ct`
2933+
// metadata). Dispatch must treat that stored default as "unknown" and
2934+
// re-derive from the path so already-deployed files serve correctly.
2935+
function createContentTypeEnv(options: {
2936+
manifest: Record<string, string>;
2937+
kvAssets?: Record<string, { body: string; ct: string }>;
2938+
r2Assets?: Record<string, { body: string; contentType: string }>;
2939+
}): Env {
2940+
return {
2941+
ROUTING: {
2942+
get: async (key: string) =>
2943+
key.startsWith('manifest:')
2944+
? JSON.stringify(options.manifest)
2945+
: JSON.stringify({
2946+
workerName: '',
2947+
projectId: 'proj-1',
2948+
staticDeploymentId: 'deploy-abc',
2949+
version: 'deploy-abc',
2950+
}),
2951+
},
2952+
DISPATCH: { get: vi.fn(() => ({ fetch: vi.fn() })) },
2953+
ISR_CACHE: { getWithMetadata: async () => ({ value: null, metadata: null }) },
2954+
STATIC_ASSETS: {
2955+
getWithMetadata: async (key: string) => {
2956+
const hash = key.replace(/^assets\/[^/]+\//, '');
2957+
const asset = options.kvAssets?.[hash];
2958+
if (!asset) {
2959+
return { value: null, metadata: null };
2960+
}
2961+
return {
2962+
value: new TextEncoder().encode(asset.body).buffer,
2963+
metadata: { ct: asset.ct },
2964+
};
2965+
},
2966+
},
2967+
STATIC_ASSETS_R2: {
2968+
get: async (key: string) => {
2969+
const hash = key.replace(/^assets\/[^/]+\//, '');
2970+
const asset = options.r2Assets?.[hash];
2971+
if (!asset) {
2972+
return null;
2973+
}
2974+
return {
2975+
body: asset.body,
2976+
size: asset.body.length,
2977+
httpEtag: '"ad7a5ae51c0bc3bbd2d6c7cbdc238c3e"',
2978+
httpMetadata: { contentType: asset.contentType },
2979+
};
2980+
},
2981+
},
2982+
ANALYTICS: { writeDataPoint: () => {} },
2983+
} as unknown as Env;
2984+
}
2985+
2986+
it('re-derives content type for .md stored in R2 as application/octet-stream', async () => {
2987+
const env = createContentTypeEnv({
2988+
manifest: { '/guide/page.md': '!hash_md' },
2989+
r2Assets: { hash_md: { body: '# hello', contentType: 'application/octet-stream' } },
2990+
});
2991+
2992+
const res = await app.fetch(
2993+
new Request('https://test.void.app/guide/page.md'),
2994+
env,
2995+
createCtx(),
2996+
);
2997+
expect(res.status).toBe(200);
2998+
expect(res.headers.get('Content-Type')).toBe('text/markdown; charset=utf-8');
2999+
});
3000+
3001+
it('re-derives content type for .md stored in KV as application/octet-stream', async () => {
3002+
const env = createContentTypeEnv({
3003+
manifest: { '/guide/page.md': 'hash_md' },
3004+
kvAssets: { hash_md: { body: '# hello', ct: 'application/octet-stream' } },
3005+
});
3006+
3007+
const res = await app.fetch(
3008+
new Request('https://test.void.app/guide/page.md'),
3009+
env,
3010+
createCtx(),
3011+
);
3012+
expect(res.status).toBe(200);
3013+
expect(res.headers.get('Content-Type')).toBe('text/markdown; charset=utf-8');
3014+
});
3015+
3016+
it('honors an explicit stored content type that is not octet-stream', async () => {
3017+
const env = createContentTypeEnv({
3018+
manifest: { '/guide/page.md': 'hash_md' },
3019+
kvAssets: { hash_md: { body: '# hello', ct: 'text/plain; charset=utf-8' } },
3020+
});
3021+
3022+
const res = await app.fetch(
3023+
new Request('https://test.void.app/guide/page.md'),
3024+
env,
3025+
createCtx(),
3026+
);
3027+
expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8');
3028+
});
3029+
3030+
it('keeps application/octet-stream when the extension is also unknown', async () => {
3031+
const env = createContentTypeEnv({
3032+
manifest: { '/file.xyz': 'hash_xyz' },
3033+
kvAssets: { hash_xyz: { body: 'data', ct: 'application/octet-stream' } },
3034+
});
3035+
3036+
const res = await app.fetch(new Request('https://test.void.app/file.xyz'), env, createCtx());
3037+
expect(res.headers.get('Content-Type')).toBe('application/octet-stream');
3038+
});
3039+
3040+
it('omits the Content-Type header for the application/null sentinel', async () => {
3041+
const env = createContentTypeEnv({
3042+
manifest: { '/data.bin': 'hash_bin' },
3043+
kvAssets: { hash_bin: { body: 'data', ct: 'application/null' } },
3044+
});
3045+
3046+
const res = await app.fetch(new Request('https://test.void.app/data.bin'), env, createCtx());
3047+
expect(res.status).toBe(200);
3048+
expect(res.headers.get('Content-Type')).toBeNull();
3049+
});
3050+
});

‎packages/dispatch/test/unit/static.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,23 @@ describe('getContentType', () => {
196196
expect(getContentType('/module.wasm')).toBe('application/wasm');
197197
});
198198

199+
it('returns text/markdown for .md files', () => {
200+
expect(getContentType('/guide/github-actions-cache.md')).toBe('text/markdown; charset=utf-8');
201+
});
202+
203+
it('returns text/markdown for .markdown files', () => {
204+
expect(getContentType('/notes.markdown')).toBe('text/markdown; charset=utf-8');
205+
});
206+
207+
it('returns text/yaml for .yaml and .yml files', () => {
208+
expect(getContentType('/config.yaml')).toBe('text/yaml; charset=utf-8');
209+
expect(getContentType('/config.yml')).toBe('text/yaml; charset=utf-8');
210+
});
211+
212+
it('returns application/toml for .toml files', () => {
213+
expect(getContentType('/config.toml')).toBe('application/toml');
214+
});
215+
199216
it('returns application/octet-stream for unknown extensions', () => {
200217
expect(getContentType('/file.xyz')).toBe('application/octet-stream');
201218
});

0 commit comments

Comments
 (0)