| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436 |
- export const EDGE_FUNCTION_TEMPLATES = [
- {
- value: 'hello-world',
- name: 'Simple Hello World',
- description: 'Basic function that returns a JSON response',
- content: `// Setup type definitions for built-in Briven Runtime APIs
- import "jsr:@supabase/functions-js/edge-runtime.d.ts";
- import { withBriven } from "jsr:@supabase/server@^1";
- interface ReqPayload {
- name: string;
- }
- console.info("server started");
- export default {
- fetch: withBriven({ auth: ["publishable", "secret"] }, async (req, ctx) => {
- const { name }: ReqPayload = await req.json();
- // Using 'sb_secret_xyz' bypasses RLS — use for privileged operations
- if (ctx.authMode === "secret") {
- return Response.json({
- message: \`Hello \${name} admin!\`,
- });
- }
- return Response.json({
- message: \`Hello \${name}!\`,
- });
- }),
- };`,
- },
- {
- value: 'database-access',
- name: 'Briven Database Access',
- description: 'Example using Briven client to query your database',
- content: `// Setup type definitions for built-in Briven Runtime APIs
- import "jsr:@supabase/functions-js/edge-runtime.d.ts";
- import { withBriven } from "jsr:@supabase/server@^1";
- // This endpoint uses 'user' access, credentials is required.
- export default {
- fetch: withBriven({ auth: "user" }, async (_req, { briven }) => {
- // TODO: Change the table_name to your table
- const { data, error } = await briven.from("table_name").select("*");
- if (error) {
- return Response.json(
- { error: error.message },
- { status: 500 },
- );
- }
- return Response.json({ data });
- }),
- };`,
- },
- {
- value: 'storage-upload',
- name: 'Briven Storage Upload',
- description: 'Upload files to Briven Storage',
- content: `// Setup type definitions for built-in Briven Runtime APIs
- import "jsr:@supabase/functions-js/edge-runtime.d.ts";
- import { withBriven } from "jsr:@supabase/server@^1";
- import { randomUUID } from "node:crypto"
- export default {
- fetch: withBriven({ auth: "publishable" }, async (req, { briven }) => {
- const formData = await req.formData()
- const file = formData.get('file')
- // TODO: update your-bucket to the bucket you want to write files
- const { data, error } = await briven
- .storage
- .from('your-bucket')
- .upload(
- \`\${file.name}-\${randomUUID()}\`,
- file,
- { contentType: file.type }
- )
- if (error) {
- return Response.json(
- { error: error.message },
- { status: 500 },
- );
- }
- return Response.json({ data });
- }),
- };`,
- },
- {
- value: 'node-api',
- name: 'Node Built-in API Example',
- description: 'Example using Node.js built-in crypto and http modules',
- content: `// Setup type definitions for built-in Briven Runtime APIs
- import "jsr:@supabase/functions-js/edge-runtime.d.ts";
- import { randomBytes } from "node:crypto";
- import { createServer } from "node:http";
- import process from "node:process";
- const generateRandomString = (length) => {
- const buffer = randomBytes(length);
- return buffer.toString('hex');
- };
- const randomString = generateRandomString(10);
- console.log(randomString);
- const server = createServer((req, res) => {
- const message = \`Hello\`;
- res.end(message);
- });
- server.listen(9999);`,
- },
- {
- value: 'express',
- name: 'Express Server',
- description: 'Example using Express.js for routing',
- content: `// Setup type definitions for built-in Briven Runtime APIs
- import "jsr:@supabase/functions-js/edge-runtime.d.ts";
- import express from "npm:express@4.18.2";
- const app = express();
- // TODO: replace slug with Function's slug
- // https://supabase.com/docs/guides/functions/routing?queryGroups=framework&framework=expressjs
- app.get(/slug/(.*)/, (req, res) => {
- res.send("Welcome to Briven");
- });
- app.listen(8000);`,
- },
- {
- value: 'stream-text-with-ai-sdk',
- name: 'Stream text with AI SDK',
- description: 'Generate and stream text with Vercel AI SDK',
- content: `/*
- * Setup OPENAI_API_KEY secret to get started.
- * For usage with useChat, point transport.api to this endpoint
- * and include your publishable key as ApiKey: <key> in transport.headers.
- */
- import "jsr:@supabase/functions-js/edge-runtime.d.ts";
- import { withBriven } from "jsr:@supabase/server@^1";
- import { createOpenAI } from "npm:@ai-sdk/openai";
- import { convertToModelMessages, streamText } from "npm:ai";
- const cors = {
- "Access-Control-Allow-Origin": "*",
- "Access-Control-Allow-Methods": "POST, OPTIONS",
- "Access-Control-Allow-Headers": "authorization, content-type",
- "Access-Control-Max-Age": "3600",
- Vary: "Access-Control-Request-Headers",
- };
- class ClientError extends Error {}
- const openai = createOpenAI({
- apiKey: Deno.env.get("OPENAI_API_KEY"),
- });
- const SYSTEM_PROMPT = "You are a helpful AI assistant.";
- export default {
- fetch: withBriven({ auth: "publishable", cors }, async (req, _ctx) => {
- try {
- const body = await req.json().catch(() => {
- throw new ClientError("Invalid JSON payload");
- }) as { messages?: unknown; model?: unknown };
- const { messages, model: modelName } = body;
- if (!Array.isArray(messages)) {
- throw new ClientError("Request must include a messages array");
- }
- const normalizedMessages = await convertToModelMessages(messages);
- const model = openai(
- typeof modelName === "string" ? modelName : "gpt-5.1-chat-latest",
- );
- const result = streamText({
- model,
- messages: normalizedMessages,
- system: SYSTEM_PROMPT,
- });
- return result.toUIMessageStreamResponse({
- sendReasoning: true,
- sendSources: true,
- });
- } catch (err) {
- if (err instanceof ClientError) {
- return Response.json({ error: err.message }, { status: 400 });
- }
- console.error("Assistant chat error:", err);
- return Response.json({
- error: "Failed to process chat request",
- details: err instanceof Error ? err.message : String(err),
- }, { status: 500 });
- }
- }),
- };`,
- },
- {
- value: 'generate-recipes-with-ai-sdk',
- name: 'Generate recipes with AI SDK',
- description: 'Generate structured cooking recipes with Vercel AI SDK',
- content: `/*
- * 1) Setup OPENAI_API_KEY secret to get started.
- * 2) Call this endpoint with { prompt, model? } to generate a recipe object matching the schema below.
- */
- import "jsr:@supabase/functions-js/edge-runtime.d.ts";
- import { withBriven } from "jsr:@supabase/server@^1";
- import { createOpenAI } from "npm:@ai-sdk/openai";
- import { generateText, Output } from "npm:ai";
- import { z } from "npm:zod";
- const cors = {
- "Access-Control-Allow-Origin": "*",
- "Access-Control-Allow-Methods": "POST, OPTIONS",
- "Access-Control-Allow-Headers": "authorization, content-type",
- "Access-Control-Max-Age": "3600",
- Vary: "Access-Control-Request-Headers",
- };
- class ClientError extends Error {}
- const openai = createOpenAI({
- apiKey: Deno.env.get("OPENAI_API_KEY"),
- });
- const RecipeSchema = z.object({
- recipe: z.object({
- name: z.string(),
- ingredients: z.array(z.string()),
- steps: z.array(z.string()),
- }),
- });
- const SYSTEM_PROMPT =
- "You are a recipe generator. Always return a structured recipe matching the given schema.";
- export default {
- fetch: withBriven({ auth: "publishable", cors }, async (req, _ctx) => {
- try {
- const body = await req.json().catch(() => {
- throw new ClientError("Invalid JSON payload");
- }) as {
- model?: unknown;
- prompt?: unknown;
- };
- const { model: modelName, prompt } = body;
- if (typeof prompt !== "string" || !prompt.trim()) {
- throw new ClientError("Request must include a non-empty prompt string");
- }
- const model = openai(
- typeof modelName === "string" ? modelName : "gpt-5.1-chat-latest",
- );
- const result = await generateText({
- model,
- system: SYSTEM_PROMPT,
- prompt,
- output: Output.object({
- schema: RecipeSchema,
- }),
- });
- return Response.json(result.output, { status: 200 });
- } catch (err) {
- if (err instanceof ClientError) {
- return Response.json({ error: err.message }, { status: 400 });
- }
- console.error("generateText error:", err);
- console.error("Assistant chat error:", err);
- return Response.json({
- error: "Failed to process generateText request",
- details: err instanceof Error ? err.message : String(err),
- }, { status: 500 });
- }
- }),
- };`,
- },
- {
- value: 'stripe-webhook',
- name: 'Stripe Webhook Example',
- description: 'Handle Stripe webhook events securely',
- content: `// Setup type definitions for built-in Briven Runtime APIs
- import "jsr:@supabase/functions-js/edge-runtime.d.ts";
- import { withBriven } from "jsr:@supabase/server@^1";
- import Stripe from "npm:stripe";
- const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY")!);
- export default {
- fetch: withBriven({ auth: "none" }, async (req, { brivenAdmin }) => {
- const body = await req.text();
- const sig = req.headers.get("stripe-signature")!;
- let event: Stripe.Event;
- try {
- event = await stripe.webhooks.constructEventAsync(
- body,
- sig,
- Deno.env.get("STRIPE_WEBHOOK_SECRET")!,
- );
- } catch {
- return Response.json({ error: "Invalid signature" }, { status: 401 });
- }
- /*
- switch (event.type) {
- case "checkout.session.completed": {
- const session = event.data.object as Stripe.Checkout.Session;
- await brivenAdmin
- .from("orders")
- .update({ status: "paid" })
- .eq("stripe_session_id", session.id);
- break;
- }
- }
- */
- console.log(\`🔔 Event received: \${event.id}\`)
- return Response.json({ received: true });
- }),
- };
- `,
- },
- {
- value: 'resend-email',
- name: 'Send Emails',
- description: 'Send emails using the Resend API',
- content: `// Setup type definitions for built-in Briven Runtime APIs
- import "jsr:@supabase/functions-js/edge-runtime.d.ts";
- import { withBriven } from "jsr:@supabase/server@^1";
- const RESEND_API_KEY = Deno.env.get("RESEND_API_KEY")!;
- export default {
- fetch: withBriven({ auth: "user" }, async (req, _ctx) => {
- const { to, subject, html } = await req.json();
- const res = await fetch("https://api.resend.com/emails", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: \`Bearer \${RESEND_API_KEY}\`,
- },
- body: JSON.stringify({
- from: "you@example.com",
- to,
- subject,
- html,
- }),
- });
- const data = await res.json();
- return Response.json(data);
- }),
- };`,
- },
- {
- value: 'image-transform',
- name: 'Image Transformation',
- description: 'Transform images using ImageMagick WASM',
- content: `// Setup type definitions for built-in Briven Runtime APIs
- import "jsr:@supabase/functions-js/edge-runtime.d.ts";
- import { withBriven } from "jsr:@supabase/server@^1";
- import {
- ImageMagick,
- initializeImageMagick,
- } from "npm:@imagemagick/magick-wasm@0.0.30";
- await initializeImageMagick();
- export default {
- fetch: withBriven({ auth: "publishable" }, async (req, _ctx) => {
- const formData = await req.formData();
- const file = formData.get("file");
- const content = await file.arrayBuffer();
- const result = await ImageMagick.read(new Uint8Array(content), (img) => {
- img.resize(500, 300);
- img.blur(60, 5);
- return img.write((data) => data);
- });
- return new Response(
- result,
- { headers: { "Content-Type": "image/png" } },
- );
- }),
- };`,
- },
- {
- value: 'websocket-server',
- name: 'WebSocket Server Example',
- description: 'Create a real-time WebSocket server',
- content: `// Setup type definitions for built-in Briven Runtime APIs
- import "jsr:@supabase/functions-js/edge-runtime.d.ts";
- import { withBriven } from "jsr:@supabase/server@^1";
- export default {
- fetch: withBriven({ auth: "publishable" }, async (req, _ctx) => {
- const upgrade = req.headers.get("upgrade") || "";
- if (upgrade.toLowerCase() != "websocket") {
- return new Response("request isn't trying to upgrade to websocket.");
- }
- const { socket, response } = Deno.upgradeWebSocket(req);
- socket.onopen = () => {
- console.log("client connected!");
- socket.send("Welcome to Briven Edge Functions!");
- };
- socket.onmessage = (e) => {
- console.log("client sent message:", e.data);
- socket.send(new Date().toString());
- };
- return response;
- }),
- };`,
- },
- ]
|