From 4aec74e0fb6deef046523c67f9f293ca2fdb8f51 Mon Sep 17 00:00:00 2001 From: Hassieb Pakzad <68423100+hassiebp@users.noreply.github.com> Date: Tue, 26 Nov 2024 15:34:21 +0100 Subject: [PATCH] fix(media): edge runtime support (#468) --- langfuse-core/src/media/LangfuseMedia.ts | 34 +++++++++++------------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/langfuse-core/src/media/LangfuseMedia.ts b/langfuse-core/src/media/LangfuseMedia.ts index a28316e4..13d61b04 100644 --- a/langfuse-core/src/media/LangfuseMedia.ts +++ b/langfuse-core/src/media/LangfuseMedia.ts @@ -1,21 +1,19 @@ -let fs: any; -let crypto: any; - -// Fail gracefully in environments without fs/crypto support -try { - fs = require("fs"); - crypto = require("crypto"); -} catch { - fs = undefined; - crypto = undefined; +let fs: any = null; +let cryptoModule: any = null; + +if (typeof process !== "undefined" && process.versions?.node) { + // Node + try { + fs = require("fs"); + cryptoModule = require("crypto"); + } catch (error) { + console.error("Error loading crypto or fs module", error); + } +} else if (typeof crypto !== "undefined") { + // Edge Runtime, Cloudflare Workers, etc. + cryptoModule = crypto; } -try { - crypto = require("crypto"); -} catch { - // Fail gracefully in environments without fs/crypto support - crypto = undefined; -} import { type MediaContentType } from "../types"; interface ParsedMediaReference { @@ -130,12 +128,12 @@ class LangfuseMedia { return undefined; } - if (!crypto) { + if (!cryptoModule) { console.error("Crypto support is not available in this environment"); return undefined; } - const sha256Hash = crypto.createHash("sha256").update(this._contentBytes).digest("base64"); + const sha256Hash = cryptoModule.createHash("sha256").update(this._contentBytes).digest("base64"); return sha256Hash; }