diff --git a/.changeset/thin-spies-watch.md b/.changeset/thin-spies-watch.md new file mode 100644 index 0000000..acfca0b --- /dev/null +++ b/.changeset/thin-spies-watch.md @@ -0,0 +1,5 @@ +--- +'@hono/vite-dev-server': minor +--- + +feat: support `cf` property in Cloudflare adapter diff --git a/packages/dev-server/e2e/e2e.test.ts b/packages/dev-server/e2e/e2e.test.ts index cfe3659..59d36bd 100644 --- a/packages/dev-server/e2e/e2e.test.ts +++ b/packages/dev-server/e2e/e2e.test.ts @@ -95,3 +95,9 @@ test('Should not throw an error if accessing the `caches`', async ({ page }) => // It does **not** return cached content. expect(await resCached?.text()).not.toBe('cached') }) + +test('Should set `cf` properties', async ({ page }) => { + const res = await page.goto('/cf') + expect(res?.ok()).toBe(true) + expect(await res?.json()).toEqual({ cf: true }) +}) diff --git a/packages/dev-server/e2e/mock/worker.ts b/packages/dev-server/e2e/mock/worker.ts index 5158269..56044cc 100644 --- a/packages/dev-server/e2e/mock/worker.ts +++ b/packages/dev-server/e2e/mock/worker.ts @@ -92,4 +92,11 @@ app.get('/cache', async (c) => { return c.text('first') }) +app.get('/cf', (c) => { + return c.json({ + // @ts-expect-error `Request.cf` is not typed + cf: typeof c.req.raw.cf === 'object' ? true : false, + }) +}) + export default app diff --git a/packages/dev-server/src/adapter/cloudflare.ts b/packages/dev-server/src/adapter/cloudflare.ts index 6a4892f..0e5872f 100644 --- a/packages/dev-server/src/adapter/cloudflare.ts +++ b/packages/dev-server/src/adapter/cloudflare.ts @@ -16,6 +16,7 @@ export const cloudflareAdapter: (options?: CloudflareAdapterOptions) => Promise< proxy ??= await getPlatformProxy(options?.proxy) // Cache API provided by `getPlatformProxy` currently do nothing. Object.assign(globalThis, { caches: proxy.caches }) + if (typeof globalThis.navigator === 'undefined') { // @ts-expect-error not typed well globalThis.navigator = { @@ -28,6 +29,14 @@ export const cloudflareAdapter: (options?: CloudflareAdapterOptions) => Promise< }) } + Object.defineProperty(Request.prototype, 'cf', { + get: function () { + return proxy.cf + }, + configurable: true, + enumerable: true, + }) + return { env: proxy.env, executionContext: proxy.ctx,