diff --git a/.tool-versions b/.tool-versions index bc89cc4..04e52ae 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1 +1 @@ -deno 1.37.1 +deno 1.38.3 diff --git a/src/deps.ts b/src/deps.ts index e3d32ef..a02ad20 100644 --- a/src/deps.ts +++ b/src/deps.ts @@ -76,5 +76,6 @@ export { default as uuid62 } from 'npm:uuid62@^1.0.2'; export { Machina } from 'https://gitlab.com/soapbox-pub/nostr-machina/-/raw/08a157d39f2741c9a3a4364cb97db36e71d8c03a/mod.ts'; export * as Sentry from 'https://deno.land/x/sentry@7.78.0/index.js'; export { sentry as sentryMiddleware } from 'npm:@hono/sentry@^1.0.0'; +export * as Comlink from 'npm:comlink@^4.4.1'; export type * as TypeFest from 'npm:type-fest@^4.3.0'; diff --git a/src/utils/nip05.ts b/src/utils/nip05.ts index 2205ded..b655175 100644 --- a/src/utils/nip05.ts +++ b/src/utils/nip05.ts @@ -1,5 +1,6 @@ import { TTLCache, z } from '@/deps.ts'; import { Time } from '@/utils/time.ts'; +import { fetchWorker } from '@/workers/fetch.ts'; const nip05Cache = new TTLCache>({ ttl: Time.hours(1), max: 5000 }); @@ -19,7 +20,7 @@ async function lookup(value: string, opts: LookupOpts = {}): Promise fetch(url, { signal }), + fetch: (url) => fetchWorker(url, { signal }), }); return { diff --git a/src/workers/fetch.test.ts b/src/workers/fetch.test.ts new file mode 100644 index 0000000..d5054fe --- /dev/null +++ b/src/workers/fetch.test.ts @@ -0,0 +1,14 @@ +import { assert } from '@/deps-test.ts'; + +import { fetchWorker } from './fetch.ts'; + +Deno.test('fetchWorker', async () => { + await sleep(2000); + const response = await fetchWorker('https://example.com'); + const text = await response.text(); + assert(text.includes('Example Domain')); +}); + +function sleep(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/src/workers/fetch.ts b/src/workers/fetch.ts new file mode 100644 index 0000000..61a4a4a --- /dev/null +++ b/src/workers/fetch.ts @@ -0,0 +1,19 @@ +import { Comlink } from '@/deps.ts'; + +import type { FetchWorker } from './fetch.worker.ts'; + +const _worker = Comlink.wrap( + new Worker( + new URL('./fetch.worker.ts', import.meta.url), + { type: 'module' }, + ), +); + +const fetchWorker: typeof fetch = async (input) => { + const url = input instanceof Request ? input.url : input.toString(); + + const args = await _worker.fetch(url); + return new Response(...args); +}; + +export { fetchWorker }; diff --git a/src/workers/fetch.worker.ts b/src/workers/fetch.worker.ts new file mode 100644 index 0000000..3c86255 --- /dev/null +++ b/src/workers/fetch.worker.ts @@ -0,0 +1,17 @@ +import { Comlink } from '@/deps.ts'; + +export const FetchWorker = { + async fetch(url: string): Promise<[BodyInit, ResponseInit]> { + const response = await fetch(url); + return [ + await response.text(), + { + status: response.status, + statusText: response.statusText, + headers: Array.from(response.headers.entries()), + }, + ]; + }, +}; + +Comlink.expose(FetchWorker);