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

fix(dev-server) cloudflare adapter restart #173

Merged
merged 3 commits into from
Aug 30, 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/three-pumas-cough.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hono/vite-dev-server': patch
---

fix(dev-server): Add null check and error handling for proxy disposal in cloudflareAdapter
24 changes: 15 additions & 9 deletions packages/dev-server/src/adapter/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ type CloudflareAdapterOptions = {
proxy: Parameters<typeof getPlatformProxy>[0]
}

let proxy: Awaited<ReturnType<typeof getPlatformProxy<Env>>>
let proxy: Awaited<ReturnType<typeof getPlatformProxy<Env>>> | undefined = undefined

export const cloudflareAdapter: (options?: CloudflareAdapterOptions) => Promise<Adapter> = async (
options
) => {
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 @@ -31,7 +30,10 @@ export const cloudflareAdapter: (options?: CloudflareAdapterOptions) => Promise<

Object.defineProperty(Request.prototype, 'cf', {
get: function () {
return proxy.cf
if (proxy !== undefined) {
return proxy.cf
}
throw new Error('Proxy is not initialized')
},
configurable: true,
enumerable: true,
Expand All @@ -41,12 +43,16 @@ export const cloudflareAdapter: (options?: CloudflareAdapterOptions) => Promise<
env: proxy.env,
executionContext: proxy.ctx,
onServerClose: async () => {
try {
await proxy.dispose()
} catch {
/**
* It throws an error if server is not running.
*/
if (proxy !== undefined) {
try {
await proxy.dispose()
} catch (error) {
/**
* It throws an error if server is not running.
*/
} finally {
proxy = undefined
}
}
},
}
Expand Down
Loading