diff --git a/.changeset/three-pumas-cough.md b/.changeset/three-pumas-cough.md new file mode 100644 index 0000000..f7ffb5c --- /dev/null +++ b/.changeset/three-pumas-cough.md @@ -0,0 +1,5 @@ +--- +'@hono/vite-dev-server': patch +--- + +fix(dev-server): Add null check and error handling for proxy disposal in cloudflareAdapter diff --git a/packages/dev-server/src/adapter/cloudflare.ts b/packages/dev-server/src/adapter/cloudflare.ts index 0e5872f..02f0ce3 100644 --- a/packages/dev-server/src/adapter/cloudflare.ts +++ b/packages/dev-server/src/adapter/cloudflare.ts @@ -8,7 +8,7 @@ type CloudflareAdapterOptions = { proxy: Parameters[0] } -let proxy: Awaited>> +let proxy: Awaited>> | undefined = undefined export const cloudflareAdapter: (options?: CloudflareAdapterOptions) => Promise = async ( options @@ -16,7 +16,6 @@ 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 = { @@ -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, @@ -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 + } } }, }