The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Deploy edge function from Assistant (#33293)
Saxon Fletcherf58b594ee83f
diff --git a/apps/studio/components/layouts/FunctionsLayout/FunctionsLayout.tsx b/apps/studio/components/layouts/FunctionsLayout/FunctionsLayout.tsxindex fe3439d7f69..5a0236642a2 100644--- a/apps/studio/components/layouts/FunctionsLayout/FunctionsLayout.tsx+++ b/apps/studio/components/layouts/FunctionsLayout/FunctionsLayout.tsx@@ -5,16 +5,16 @@ import type { PropsWithChildren } from 'react'import { useParams } from 'common'import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'import APIDocsButton from 'components/ui/APIDocsButton'+import { DocsButton } from 'components/ui/DocsButton'import NoPermission from 'components/ui/NoPermission'import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'import { withAuth } from 'hooks/misc/withAuth'-import { Code, ExternalLink } from 'lucide-react'-import { Button } from 'ui'+import { Code } from 'lucide-react'+import { Button, cn } from 'ui'import FunctionsNav from '../../interfaces/Functions/FunctionsNav'import ProjectLayout from '../ProjectLayout/ProjectLayout'-import { DocsButton } from 'components/ui/DocsButton'interface FunctionsLayoutProps {title?: string@@ -65,18 +65,18 @@ const FunctionsLayout = ({ title, children }: PropsWithChildren<FunctionsLayoutP) : (<div className="flex h-full flex-grow flex-col py-6"><div- className={[+ className={cn('mx-auto flex w-full flex-col transition-all',- '1xl:px-28 gap-4 px-5 lg:px-16 xl:px-24 2xl:px-32',- ].join(' ')}+ '1xl:px-28 gap-4 px-5 lg:px-16 xl:px-24 2xl:px-32'+ )}><div className="item-center flex flex-col justify-between gap-y-4 xl:flex-row"><div className="flex items-center gap-3 w-full"><div- className={[+ className={cn('h-6 w-6 rounded border border-brand-600 bg-brand-300',- 'flex items-center justify-center text-brand',- ].join(' ')}+ 'flex items-center justify-center text-brand'+ )}><Code size={14} strokeWidth={3} /></div>@@ -122,10 +122,7 @@ const FunctionsLayout = ({ title, children }: PropsWithChildren<FunctionsLayoutP}/>)}- <DocsButton- className="translate-y-[1px]"- href="https://supabase.com/docs/guides/functions"- />+ <DocsButton href="https://supabase.com/docs/guides/functions" /></div></div></div>diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.tsindex c587434a402..9f847ae2c8c 100644--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts@@ -1,10 +1,11 @@export type SupportedAssistantEntities = 'rls-policies' | 'functions'export type SupportedAssistantQuickPromptTypes = 'suggest' | 'examples' | 'ask'-export type AssistantSnippetProps = {- title: string- runQuery: 'true' | 'false'- isChart?: 'true' | 'false'+export interface AssistantSnippetProps {+ title?: string+ isChart?: string+ runQuery?: stringxAxis?: stringyAxis?: string+ name?: string}diff --git a/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsx b/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsxindex 56777e53466..d7a38e9c464 100644--- a/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsx@@ -16,6 +16,7 @@ import { AssistantSnippetProps } from './AIAssistant.types'import { identifyQueryType } from './AIAssistant.utils'import CollapsibleCodeBlock from './CollapsibleCodeBlock'import { MessageContext } from './Message'+import { EdgeFunctionBlock } from '../EdgeFunctionBlock/EdgeFunctionBlock'export const OrderedList = memo(({ children }: { children: ReactNode }) => (<ol className="flex flex-col gap-y-4">{children}</ol>@@ -149,19 +150,22 @@ export const MarkdownPre = ({ children }: { children: any }) => {})const language = children[0].props.className?.replace('language-', '') || 'sql'- const rawSql = language === 'sql' ? children[0].props.children : undefined- const formatted = (rawSql || [''])[0]- const propsMatch = formatted.match(/--\s*props:\s*(\{[^}]+\})/)+ const rawContent = children[0].props.children[0]+ const propsMatch = rawContent.match(/--\s*props:\s*(\{[^}]+\})/)const snippetProps: AssistantSnippetProps = useMemo(() => (propsMatch ? JSON.parse(propsMatch[1]) : {}),[propsMatch])+const { xAxis, yAxis } = snippetProps- const title = snippetProps.title || 'SQL Query'+ const title = snippetProps.title || (language === 'edge' ? 'Edge Function' : 'SQL Query')const isChart = snippetProps.isChart === 'true'const runQuery = snippetProps.runQuery === 'true'- const sql = formatted?.replace(/--\s*props:\s*\{[^}]+\}/, '').trim()++ // Strip props from the content for both SQL and edge functions+ const cleanContent = rawContent.replace(/--\s*props:\s*\{[^}]+\}/, '').trim()+const isDraggableToReports =supportSQLBlocks && canCreateSQLSnippet && router.pathname.endsWith('/reports/[id]')@@ -180,23 +184,28 @@ export const MarkdownPre = ({ children }: { children: any }) => {action: TelemetryActions.ASSISTANT_SUGGESTION_RUN_QUERY_CLICKED,properties: {queryType,- ...(queryType === 'mutation' ? { category: identifyQueryType(sql) ?? 'unknown' } : {}),+ ...(queryType === 'mutation'+ ? { category: identifyQueryType(cleanContent) ?? 'unknown' }+ : {}),},})}return (<div className="w-auto -ml-[36px] overflow-x-hidden">- {language === 'sql' ? (+ {language === 'edge' ? (+ <EdgeFunctionBlock+ label={title}+ code={cleanContent}+ functionName={snippetProps.name || 'my-function'}+ showCode={!readOnly}+ />+ ) : language === 'sql' ? (readOnly ? (- <CollapsibleCodeBlock- value={children[0].props.children[0]}- language="sql"- hideLineNumbers- />+ <CollapsibleCodeBlock value={cleanContent} language="sql" hideLineNumbers />) : (<MemoizedQueryBlock- sql={sql}+ sql={cleanContent}title={title}xAxis={xAxis}yAxis={yAxis}@@ -211,7 +220,7 @@ export const MarkdownPre = ({ children }: { children: any }) => {onDragStart={(e: DragEvent<Element>) => {e.dataTransfer.setData('application/json',- JSON.stringify({ label: title, sql, config: chartConfig.current })+ JSON.stringify({ label: title, sql: cleanContent, config: chartConfig.current }))}}/>@@ -219,7 +228,7 @@ export const MarkdownPre = ({ children }: { children: any }) => {) : (<CodeBlockhideLineNumbers- value={children[0].props.children[0]}+ value={cleanContent}language={language as CodeBlockLang}className={cn('max-h-96 max-w-none block border rounded !bg-transparent !py-3 !px-3.5 prose dark:prose-dark text-foreground',diff --git a/apps/studio/components/ui/EdgeFunctionBlock/EdgeFunctionBlock.tsx b/apps/studio/components/ui/EdgeFunctionBlock/EdgeFunctionBlock.tsxnew file mode 100644index 00000000000..39c9274ebca--- /dev/null+++ b/apps/studio/components/ui/EdgeFunctionBlock/EdgeFunctionBlock.tsx@@ -0,0 +1,207 @@+import { DragEvent, ReactNode, useState } from 'react'+import { toast } from 'sonner'+import { useParams } from 'common'+import { useEdgeFunctionDeployMutation } from 'data/edge-functions/edge-functions-deploy-mutation'+import { ReportBlockContainer } from 'components/interfaces/Reports/ReportBlock/ReportBlockContainer'+import { Button, CodeBlock, cn, CodeBlockLang } from 'ui'+import { Code } from 'lucide-react'+import Link from 'next/link'+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'+import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'+import { Admonition } from 'ui-patterns'++interface EdgeFunctionBlockProps {+ /** Title of the EdgeFunctionBlock */+ label: string+ /** Function code to display */+ code: string+ /** Function name/slug */+ functionName: string+ /** Any other actions specific to the parent to be rendered in the header */+ actions?: ReactNode+ /** Toggle visiblity of code on render */+ showCode?: boolean+ /** Whether function block is draggable */+ draggable?: boolean+ /** Tooltip when hovering over the header of the block */+ tooltip?: ReactNode+ /** Optional callback on drag start */+ onDragStart?: (e: DragEvent<Element>) => void+}++export const EdgeFunctionBlock = ({+ label,+ code,+ functionName,+ actions,+ showCode: _showCode = false,+ tooltip,+}: EdgeFunctionBlockProps) => {+ const { ref } = useParams()+ const [isDeployed, setIsDeployed] = useState(false)+ const [showWarning, setShowWarning] = useState(false)+ const { data: settings } = useProjectSettingsV2Query({ projectRef: ref })+ const { data: existingFunction } = useEdgeFunctionQuery({ projectRef: ref, slug: functionName })++ const { mutateAsync: deployFunction, isLoading: isDeploying } = useEdgeFunctionDeployMutation({+ onSuccess: () => {+ setIsDeployed(true)+ toast.success('Successfully deployed edge function')+ },+ })++ const handleDeploy = async () => {+ if (!code || isDeploying || !ref) return++ if (existingFunction) {+ return setShowWarning(true)+ }++ try {+ const deployResult = await deployFunction({+ projectRef: ref,+ metadata: {+ entrypoint_path: 'index.ts',+ name: functionName,+ verify_jwt: true,+ },+ files: [{ name: 'index.ts', content: code }],+ })+ } catch (error) {+ toast.error(+ `Failed to deploy function: ${error instanceof Error ? error.message : 'Unknown error'}`+ )+ }+ }++ let functionUrl = 'Function URL not available'+ const endpoint = settings?.app_config?.endpoint+ if (endpoint) {+ const restUrl = `https://${endpoint}`+ const restUrlTld = restUrl ? new URL(restUrl).hostname.split('.').pop() : 'co'+ functionUrl =+ ref && functionName && restUrlTld+ ? `https://${ref}.supabase.${restUrlTld}/functions/v1/${functionName}`+ : 'Function URL will be available after deployment'+ }+ return (+ <ReportBlockContainer+ tooltip={tooltip}+ icon={<Code size={16} strokeWidth={1.5} className="text-foreground-muted" />}+ label={label}+ actions={+ ref && functionName ? (+ <>+ <Button+ type="outline"+ size="tiny"+ loading={isDeploying}+ disabled={!ref}+ onClick={handleDeploy}+ >+ {isDeploying ? 'Deploying...' : 'Deploy'}+ </Button>++ {actions}+ </>+ ) : null+ }+ >+ {showWarning && ref && functionName && (+ <Admonition+ type="warning"+ className="mb-0 rounded-none border-0 border-b shrink-0 bg-background-100"+ >+ <p>An edge function with the name "{functionName}" already exists.</p>+ <p className="text-foreground-light">+ Deploying will replace the existing function. Are you sure you want to proceed?+ </p>+ <div className="flex justify-stretch mt-2 gap-2">+ <Button+ type="outline"+ size="tiny"+ className="w-full flex-1"+ onClick={() => setShowWarning(false)}+ >+ Cancel+ </Button>+ <Button+ type="danger"+ size="tiny"+ className="w-full flex-1"+ onClick={async () => {+ setShowWarning(false)+ try {+ await deployFunction({+ projectRef: ref,+ metadata: {+ entrypoint_path: 'index.ts',+ name: functionName,+ verify_jwt: true,+ },+ files: [{ name: 'index.ts', content: code }],+ })+ } catch (error) {+ toast.error(+ `Failed to deploy function: ${error instanceof Error ? error.message : 'Unknown error'}`+ )+ }+ }}+ >+ Replace function+ </Button>+ </div>+ </Admonition>+ )}++ <div className="shrink-0 w-full max-h-96 overflow-y-auto">+ <CodeBlock+ hideLineNumbers+ wrapLines={false}+ value={code}+ language={'typescript' as CodeBlockLang}+ className={cn(+ 'max-w-none block !bg-transparent !py-3 !px-3.5 prose dark:prose-dark border-0 text-foreground !rounded-none w-full',+ '[&>code]:m-0 [&>code>span]:text-foreground'+ )}+ />+ </div>++ {(isDeploying || isDeployed) && (+ <div className="p-4 w-full border-t bg-surface-75 text-xs">+ {isDeploying ? (+ <p className="text-foreground-light">Deploying function...</p>+ ) : (+ <>+ <p className="text-foreground-light mb-2">+ The{' '}+ <Link+ className="text-foreground"+ href={`/project/${ref}/functions/${functionName}/details`}+ >+ new function+ </Link>{' '}+ is now live at:+ </p>+ <CodeBlock+ language="bash"+ hideLineNumbers+ value={functionUrl}+ className="text-xs p-2"+ />+ <p className="text-foreground-light mt-4 mb-2">+ To download and work on this function locally, use the CLI command:+ </p>+ <CodeBlock+ hideLineNumbers+ language="bash"+ value={`supabase functions download ${functionName}`}+ className="text-xs p-2"+ />+ </>+ )}+ </div>+ )}+ </ReportBlockContainer>+ )+}diff --git a/apps/studio/pages/api/ai/sql/generate-v3.ts b/apps/studio/pages/api/ai/sql/generate-v3.tsindex 3de5a1b502e..40558735417 100644--- a/apps/studio/pages/api/ai/sql/generate-v3.ts+++ b/apps/studio/pages/api/ai/sql/generate-v3.ts@@ -116,6 +116,19 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {- Default to create or replace whenever possible for updating an existing function, otherwise use the alter function statementPlease make sure that all queries are valid Postgres SQL queries+ # You write edge functions+ Your purpose is to generate entire edge functions with the constraints given by the user.+ - First, always use the getEdgeFunctionKnowledge tool to get knowledge about how to write edge functions for Supabase+ - When writing edge functions, always ensure that they are written in TypeScript and Deno JavaScript runtime.+ - When writing edge functions, write complete code so the user doesn't need to replace any placeholders.+ - When writing edge functions, always ensure that they are written in a way that is compatible with the database schema.+ - When suggesting edge functions, follow the guidelines in getEdgeFunctionKnowledge tool. Always create personalised edge functions based on the database schema+ - When outputting edge functions, always include a props comment in the first line of the code block:+ -- props: {"name": "function-name", "title": "Human readable title"}+ - The function name in the props must be URL-friendly (use hyphens instead of spaces or underscores)+ - Always wrap the edge function code in a markdown code block with the language set to 'edge'+ - The props comment must be the first line inside the code block, followed by the actual function code+# You convert sql to supabase-js client codeUse the convertSqlToSupabaseJs tool to convert select sql to supabase-js client code. Only provide js code snippets if explicitly asked. If conversion isn't supported, build a postgres function instead and suggest using supabase-js to call it via "const { data, error } = await supabase.rpc('echo', { say: '👋'})"diff --git a/apps/studio/pages/api/ai/sql/tools.ts b/apps/studio/pages/api/ai/sql/tools.tsindex 87344f14ba2..d3b212ce83a 100644--- a/apps/studio/pages/api/ai/sql/tools.ts+++ b/apps/studio/pages/api/ai/sql/tools.ts@@ -387,5 +387,187 @@ export const getTools = ({}},}),+ getEdgeFunctionKnowledge: tool({+ description: 'Get knowledge about how to write edge functions for Supabase',+ parameters: z.object({}),+ execute: async ({}) => {+ return stripIndent`+ # Writing Supabase Edge Functions++ You're an expert in writing TypeScript and Deno JavaScript runtime. Generate **high-quality Supabase Edge Functions** that adhere to the following best practices:++ ## Guidelines++ 1. Try to use Web APIs and Deno's core APIs instead of external dependencies (eg: use fetch instead of Axios, use WebSockets API instead of node-ws)+ 2. Do NOT use bare specifiers when importing dependencies. If you need to use an external dependency, make sure it's prefixed with either \`npm:\` or \`jsr:\`. For example, \`@supabase/supabase-js\` should be written as \`npm:@supabase/supabase-js\`.+ 3. For external imports, always define a version. For example, \`npm:@express\` should be written as \`npm:[email protected]\`.+ 4. For external dependencies, importing via \`npm:\` and \`jsr:\` is preferred. Minimize the use of imports from @\`deno.land/x\` , \`esm.sh\` and @\`unpkg.com\` . If you have a package from one of those CDNs, you can replace the CDN hostname with \`npm:\` specifier.+ 5. You can also use Node built-in APIs. You will need to import them using \`node:\` specifier. For example, to import Node process: \`import process from "node:process"\`. Use Node APIs when you find gaps in Deno APIs.+ 6. Do NOT use \`import { serve } from "https://deno.land/[email protected]/http/server.ts"\`. Instead use the built-in \`Deno.serve\`.+ 7. Following environment variables (ie. secrets) are pre-populated in both local and hosted Supabase environments. Users don't need to manually set them:+ * SUPABASE_URL+ * SUPABASE_ANON_KEY+ * SUPABASE_SERVICE_ROLE_KEY+ * SUPABASE_DB_URL+ 8. To set other environment variables the user can go to project settings then edge functions to set them+ 9. A single Edge Function can handle multiple routes. It is recommended to use a library like Express or Hono to handle the routes as it's easier for developer to understand and maintain. Each route must be prefixed with \`/function-name\` so they are routed correctly.+ 10. File write operations are ONLY permitted on \`/tmp\` directory. You can use either Deno or Node File APIs.+ 11. Use \`EdgeRuntime.waitUntil(promise)\` static method to run long-running tasks in the background without blocking response to a request. Do NOT assume it is available in the request / execution context.++ ## Example Templates++ ### Simple Hello World Function++ \`\`\`edge+ // Setup type definitions for built-in Supabase Runtime APIs+ import "jsr:@supabase/functions-js/edge-runtime.d.ts";+ interface reqPayload {+ name: string;+ }++ console.info('server started');++ Deno.serve(async (req: Request) => {+ const { name }: reqPayload = await req.json();+ const data = {+ message: \`Hello \${name} from foo!\`,+ };++ return new Response(+ JSON.stringify(data),+ { headers: { 'Content-Type': 'application/json', 'Connection': 'keep-alive' }}+ );+ });+ \`\`\`++ ### Example Function using Node built-in API++ \`\`\`edge+ // Setup type definitions for built-in Supabase 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);+ \`\`\`++ ### Using npm packages in Functions++ \`\`\`edge+ // Setup type definitions for built-in Supabase Runtime APIs+ import "jsr:@supabase/functions-js/edge-runtime.d.ts";+ import express from "npm:[email protected]";++ const app = express();++ app.get(/(.*)/, (req, res) => {+ res.send("Welcome to Supabase");+ });++ app.listen(8000);+ \`\`\`++ ### Generate embeddings using built-in @Supabase.ai API++ \`\`\`edge+ // Setup type definitions for built-in Supabase Runtime APIs+ import "jsr:@supabase/functions-js/edge-runtime.d.ts";+ const model = new Supabase.ai.Session('gte-small');++ Deno.serve(async (req: Request) => {+ const params = new URL(req.url).searchParams;+ const input = params.get('text');+ const output = await model.run(input, { mean_pool: true, normalize: true });+ return new Response(+ JSON.stringify(output),+ {+ headers: {+ 'Content-Type': 'application/json',+ 'Connection': 'keep-alive',+ },+ },+ );+ });+ \`\`\`++ ## Integrating with Supabase Auth++ \`\`\`edge+ // Setup type definitions for built-in Supabase Runtime APIs+ import "jsr:@supabase/functions-js/edge-runtime.d.ts";+ import { createClient } from \\'jsr:@supabase/supabase-js@2\\'+ import { corsHeaders } from \\'../_shared/cors.ts\\'++ console.log(\`Function "select-from-table-with-auth-rls" up and running!\`)++ Deno.serve(async (req: Request) => {+ // This is needed if you\\'re planning to invoke your function from a browser.+ if (req.method === \\'OPTIONS\\') {+ return new Response(\\'ok\\', { headers: corsHeaders })+ }++ try {+ // Create a Supabase client with the Auth context of the logged in user.+ const supabaseClient = createClient(+ // Supabase API URL - env var exported by default.+ Deno.env.get('SUPABASE_URL')!,+ // Supabase API ANON KEY - env var exported by default.+ Deno.env.get('SUPABASE_ANON_KEY')!,+ // Create client with Auth context of the user that called the function.+ // This way your row-level-security (RLS) policies are applied.+ {+ global: {+ headers: { Authorization: req.headers.get(\\'Authorization\\')! },+ },+ }+ )++ // First get the token from the Authorization header+ const token = req.headers.get(\\'Authorization\\').replace(\\'Bearer \\', \\'\\')++ // Now we can get the session or user object+ const {+ data: { user },+ } = await supabaseClient.auth.getUser(token)++ // And we can run queries in the context of our authenticated user+ const { data, error } = await supabaseClient.from(\\'users\\').select(\\'*\\')+ if (error) throw error++ return new Response(JSON.stringify({ user, data }), {+ headers: { ...corsHeaders, \\'Content-Type\\': \\'application/json\\' },+ status: 200,+ })+ } catch (error) {+ return new Response(JSON.stringify({ error: error.message }), {+ headers: { ...corsHeaders, \\'Content-Type\\': \\'application/json\\' },+ status: 400,+ })+ }+ })++ // To invoke:+ // curl -i --location --request POST \\'http://localhost:54321/functions/v1/select-from-table-with-auth-rls\\' \\+ // --header \\'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTs\\' \\+ // --header \\'Content-Type: application/json\\' \\+ // --data \\'{"name":"Functions"}\\'+ \`\`\`+ `+ },+ }),}}