# Plan: Deno Compatibility for MadBase Edge Functions ## Problem Statement Currently, MadBase executes Edge Functions as WASM modules via `wasmtime`. Supabase-compatible Edge Functions (like those in `accountaflow`) are written in TypeScript and target a Deno environment. Migrating these requires 1:1 compatibility for the `Deno` namespace, ES modules, and standard web APIs (Fetch, Request, Response). ## Proposed Architecture ### 1. Dual-Runtime Strategy Extend the `functions` crate to support two runtimes: - **WasmRuntime**: Existing `wasmtime` based executor for compiled modules. - **DenoRuntime**: A new V8-based executor utilizing `deno_core` and `deno_runtime`. ### 2. Runtime Detection The gateway should detect the function type: - **DenoRuntime (V8)**: Files ending in `.ts` or `.js`. Recommended for standard Edge Functions due to JIT-optimized performance. - **WasmRuntime (Wasmtime)**: Native WASM binaries (Rust, Go, C++). Best for specialized, high-performance logic or pre-compiled modules. ## Implementation Steps ### Phase 1: Core Integration - Add `deno_core` and `deno_runtime` dependencies to `madbase/functions/Cargo.toml`. - Create `functions/src/deno_runtime.rs`. - Implement `execute_script(code: String, payload: Value)` using `JsRuntime`. ### Phase 2: Supabase Environment Compatibility - **Process Environment**: Inject `SUPABASE_URL`, `SUPABASE_ANON_KEY`, and `SUPABASE_SERVICE_ROLE_KEY`. - **Global Objects**: Implement a shim for `Deno.serve` to capture the incoming request and route it to the script's handler. - **Header Parsing**: Ensure standard headers (`apikey`, `Authorization`) are passed through. ### Phase 3: Module Resolution - Implement a `ModuleLoader` that handles imports from `https://esm.sh/`. - Support local imports from a shared functions directory (like `_shared`). ## API Changes ### Gateway Modify `POST /functions/v1` to accept `type: "typescript" | "wasm"`. Default to "typescript" for source code. ### Deployment Table Update the `functions` table schema in the control plane to store the runtime type. ## Verification Plan ### Automated Tests 1. **Hello World Test**: Deploy a simple `.ts` function and verify the output. 2. **Supabase Client Test**: Deploy a function that imports `@supabase/supabase-js` from `esm.sh` and queries the MadBase Data API. 3. **Environment Variable Test**: Verify `Deno.env.get` returns expected MadBase configuration. ### Manual Verification 1. Attempt to deploy the `invite-staff` function from `accountaflow` directly to MadBase. 2. Verify cross-organization invitation logic works.