From caf97be705951407cf2d09fa02036df43a51293f Mon Sep 17 00:00:00 2001 From: Igor Katsuba Date: Sun, 10 Nov 2024 23:40:52 +0200 Subject: [PATCH 1/2] fix: implement custom fetch handling in ApiClient for Cloudflare compatibility --- src/core/client.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/core/client.ts b/src/core/client.ts index f707a593..28c0d8fb 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -252,7 +252,14 @@ class ApiClient { }, canUseWebhookReply: options.canUseWebhookReply ?? (() => false), sensitiveLogs: options.sensitiveLogs ?? false, - fetch: options.fetch ?? fetch, + // In an ideal world, `fetch` is independent of the context being called, + // but in a Cloudflare worker, any context other than global throws an error. + // That is why we need to call custom fetch or fetch without context. + fetch: ((...args: Parameters) => { + const { fetch: customFetch } = options; + + return (customFetch ?? fetch)(...args); + }) as typeof fetch, }; this.fetch = this.options.fetch; if (this.options.apiRoot.endsWith("/")) { From 0da7c738e6a02e69c108ff59df7f75be9d1efcf0 Mon Sep 17 00:00:00 2001 From: Igor Katsuba Date: Mon, 11 Nov 2024 20:48:13 +0200 Subject: [PATCH 2/2] chore: compute the fetch option just once --- src/core/client.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/core/client.ts b/src/core/client.ts index 28c0d8fb..807be506 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -241,6 +241,13 @@ class ApiClient { ) { const apiRoot = options.apiRoot ?? "https://api.telegram.org"; const environment = options.environment ?? "prod"; + + // In an ideal world, `fetch` is independent of the context being called, + // but in a Cloudflare worker, any context other than global throws an error. + // That is why we need to call custom fetch or fetch without context. + const { fetch: customFetch } = options; + const fetchFn = customFetch ?? fetch; + this.options = { apiRoot, environment, @@ -252,14 +259,9 @@ class ApiClient { }, canUseWebhookReply: options.canUseWebhookReply ?? (() => false), sensitiveLogs: options.sensitiveLogs ?? false, - // In an ideal world, `fetch` is independent of the context being called, - // but in a Cloudflare worker, any context other than global throws an error. - // That is why we need to call custom fetch or fetch without context. - fetch: ((...args: Parameters) => { - const { fetch: customFetch } = options; - - return (customFetch ?? fetch)(...args); - }) as typeof fetch, + fetch: + ((...args: Parameters) => + fetchFn(...args)) as typeof fetch, }; this.fetch = this.options.fetch; if (this.options.apiRoot.endsWith("/")) {