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

feat(dev-server): support cf property in Cloudflare adapter #161

Merged
merged 2 commits into from
Aug 12, 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/thin-spies-watch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hono/vite-dev-server': minor
---

feat: support `cf` property in Cloudflare adapter
6 changes: 6 additions & 0 deletions packages/dev-server/e2e/e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
})
7 changes: 7 additions & 0 deletions packages/dev-server/e2e/mock/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 9 additions & 0 deletions packages/dev-server/src/adapter/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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,
Expand Down
Loading