Skip to content

feat(studio-local): functions management api - function blob artifacts - #42349

Merged
charislam merged 6 commits into
supabase:masterfrom
kallebysantos:feat-local-functions-management-api-3-function-blob-artifacts
Feb 6, 2026
Merged

charislam merged 6 commits into
supabase:masterfrom
kallebysantos:feat-local-functions-management-api-3-function-blob-artifacts

Conversation

@kallebysantos

@kallebysantos kallebysantos commented Jan 31, 2026 •

Copy link
Copy Markdown
Member

What kind of change does this PR introduce?

Feature

What is the current behavior?

Functions page on self-hosted differs from Platform

What is the new behavior?

Note

This PR only add readonly operations. Function edit and deploy should be implemented in a future one.

Adds the possibility to download and see function code in Self-Host version.

Details image

Summary by CodeRabbit

  • New Features

    • API endpoint to stream function files/artifacts as multipart/form-data.
    • New function file entry type and server-side file listing for functions.
  • Improvements

    • Edge Functions "Code" navigation item always visible.
    • Download popover reworked: ZIP download always available; CLI section shown only on supported platforms.
    • Editor set to read-only and file actions disabled on unsupported environments.
  • Editor

    • Added JavaScript, TypeScript, and Markdown language modules for the embedded editor.

@kallebysantos
kallebysantos requested a review from a team as a code owner January 31, 2026 22:04
@github-actions

Copy link
Copy Markdown
Contributor

Thanks for contributing to Supabase! ❤️ Our team will review your PR.

A few tips for a smoother review process:

  • If you have a local version of the repo, run pnpm run format to make sure formatting checks pass.
  • Once we've reviewed your PR, please don't trivially merge master (don't click Update branch if there are no merge conflicts to be fixed). This invalidates any pre-merge checks we've run.

@vercel

vercel Bot commented Jan 31, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
design-system Ready Ready Preview, Comment Feb 6, 2026 7:55pm
docs Ready Ready Preview, Comment, Open in v0 Feb 6, 2026 7:55pm
learn Error Error Feb 6, 2026 7:55pm
studio-self-hosted Ready Ready Preview, Comment Feb 6, 2026 7:55pm
studio-staging Ready Ready Preview, Comment Feb 6, 2026 7:55pm
ui-library Ready Ready Preview, Comment Feb 6, 2026 7:55pm
zone-www-dot-com Ready Ready Preview, Comment, Open in v0 Feb 6, 2026 7:55pm
2 Skipped Deployments
Project Deployment Actions Updated (UTC)
cms Ignored Ignored Feb 6, 2026 7:55pm
studio Ignored Ignored Feb 6, 2026 7:55pm

Request Review

@vercel

vercel Bot commented Jan 31, 2026

Copy link
Copy Markdown

@kallebysantos is attempting to deploy a commit to the Supabase Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jan 31, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds IS_PLATFORM gating across Edge Functions UI and File Explorer, exposes function file entries via a new FileSystem store method and authenticated multipart GET API endpoint, and adds Monaco language modules for JavaScript, TypeScript, and Markdown.

Changes

Cohort / File(s) Summary
Edge Functions Navigation & UI
apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout.tsx, apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
Moves the Code nav item to the main navigation, restructures the Download popover to always render while gating CLI-specific content by IS_PLATFORM, and gates the Deploy UI block behind IS_PLATFORM.
File Explorer & Editor
apps/studio/components/ui/FileExplorerAndEditor/index.tsx
Adds IS_PLATFORM checks to Add File button, context menu (rename/delete), rename/edit handlers, and sets AI editor to readOnly when not on platform.
Edge Function Query
apps/studio/data/edge-functions/edge-function-body-query.ts
Removes IS_PLATFORM from the query enabled condition so the hook runs when projectRef, slug, and the caller-enabled flag are present.
Self-hosted Functions Store & Types
apps/studio/lib/api/self-hosted/functions/fileSystemStore.ts, apps/studio/lib/api/self-hosted/functions/types.ts
Adds exported FunctionFileEntry type and a new getFileEntriesBySlug(slug) method that validates paths, recursively reads files, and returns entries with absolutePath, relativePath, and size.
API Endpoint
apps/studio/pages/api/v1/projects/[ref]/functions/[slug]/body.ts
New authenticated GET handler that fetches file entries from the store and streams an in-memory multipart/form-data response containing metadata and file parts to the client.
Monaco Editor Language Modules
apps/studio/public/monaco-editor/basic-languages/javascript/javascript.js, apps/studio/public/monaco-editor/basic-languages/markdown/markdown.js, apps/studio/public/monaco-editor/basic-languages/typescript/typescript.js, apps/studio/public/monaco-editor/language/typescript/tsMode.js
Adds AMD modules for JavaScript, Markdown, and TypeScript language definitions and a TypeScript language mode (language-service adapters/workers) for the Monaco editor.

Sequence Diagram

sequenceDiagram
    participant Client as Client/Browser
    participant API as Next API Handler (body.ts)
    participant Store as FunctionsArtifactStore
    participant FS as File System
    participant Stream as Multipart Stream Builder

    Client->>API: GET /api/v1/projects/[ref]/functions/[slug]/body
    API->>API: validate slug & auth
    API->>Store: getFileEntriesBySlug(slug)
    Store->>FS: read folder recursively
    FS-->>Store: file entries + stats
    Store-->>API: FunctionFileEntry[]
    API->>Stream: build metadata part
    loop for each file
      API->>Stream: add file part (headers)
      Stream->>FS: stream file contents
      FS-->>Stream: file data
    end
    Stream->>Client: stream multipart/form-data response
Loading

Possibly related PRs

Suggested reviewers

  • saltcod
  • aantti
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding function blob artifacts API for functions management in studio-local, which is the core purpose of this PR.
Description check ✅ Passed The PR description follows the template structure with clear sections, explains the change is a feature for read-only function operations in self-hosted, provides context about future work, and includes a visual screenshot. However, it is missing the CONTRIBUTING.md acknowledgement section from the template.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@apps/studio/lib/api/self-hosted/functions/fileSystemStore.ts`:
- Around line 72-85: The function parseFileToFunctionBlobArtifact is returning a
filename that leaks the full server path by using path.join(file.parentPath,
file.name) instead of a path relative to the function root; change it to compute
a relative path from originalFolderPath (e.g., use
path.relative(originalFolderPath, path.join(file.parentPath, file.name)) and use
that relativePath for the filename field), normalizing separators if needed so
the client receives a clean relative filename rather than an absolute server
path.
- Around line 33-40: The code in getBlobArtifactsBySlug allows path traversal by
joining slug directly to this.folderPath; change to resolve and validate the
target before reading: compute const base = path.resolve(this.folderPath) and
const target = path.resolve(base, slug), then ensure path.relative(base, target)
does not start with '..' (and optionally that path.isAbsolute(target) is within
base); if the check fails, throw or return []; after that use await stat(target)
to confirm it's a directory before calling readdir on functionFolderPath. Ensure
you reference function names/vars getBlobArtifactsBySlug, this.folderPath,
functionFolderPath/target, and readdir/stat in the change.

In `@apps/studio/pages/api/v1/projects/`[ref]/functions/[slug]/body.ts:
- Around line 49-56: The response is currently sending multipartResponse.text(),
which decodes UTF-8 and corrupts binary parts; instead read the body with
multipartResponse.arrayBuffer(), convert to a Node Buffer, set the Content-Type
header from multipartResponse.headers.get('content-type') (already done via
multipartResponse), and send the Buffer via res.status(200).send(...). Update
the code paths that reference multipartResponse, form, and res to use
arrayBuffer -> Buffer.from(arrayBuffer) and send that buffer.
🧹 Nitpick comments (2)
apps/studio/data/edge-functions/edge-function-body-query.ts (1)

6-6: Unused import after removing IS_PLATFORM gating.

The IS_PLATFORM constant is imported but no longer used in this file after removing it from the enabled condition. Consider removing this import to avoid dead code.

🧹 Suggested cleanup
-import { IS_PLATFORM } from 'lib/constants'
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx (1)

54-61: Duplicate refetchOnMount option.

refetchOnMount: false appears twice in the query options (lines 55 and 58). The second declaration shadows the first, which is harmless but indicates unintentional duplication.

🧹 Remove duplicate option
       {
         // [Alaister]: These parameters prevent the function files
         // from being refetched when the user is editing the code
         retry: false,
         retryOnMount: false,
         refetchOnWindowFocus: false,
         staleTime: Infinity,
-        refetchOnMount: false,
         refetchOnReconnect: false,
         refetchInterval: false,
         refetchIntervalInBackground: false,
       }

@aantti aantti assigned aantti and unassigned aantti Feb 2, 2026
@aantti aantti added cli Related to supabase/cli edge functions self-hosted Related to self-hosted Supabase labels Feb 2, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@apps/studio/lib/api/self-hosted/functions/fileSystemStore.ts`:
- Around line 36-42: The code calls readdir(functionFolderPath, ...) which
throws ENOENT when slug refers to a non-existent function; wrap the readdir call
in a try/catch inside the same function so that if the caught error.code ===
'ENOENT' you return an empty array (preserving the current guard that checks
functionFolderPath.startsWith(...)), and for any other error rethrow it; update
references to functionFolderPath, slug and readdir accordingly so the behaviour
is consistent and only ENOENT is handled silently.

In `@apps/studio/pages/api/v1/projects/`[ref]/functions/[slug]/body.ts:
- Around line 57-59: Add a defensive null check for multipartResponse.body
before calling Readable.fromWeb; if multipartResponse.body is null/undefined,
set an appropriate status (e.g., res.status(204) or res.status(500) with an
error message) and end the response instead of using the non-null assertion.
Locate the code that builds/receives multipartResponse (variable
multipartResponse) and replace the current lines that call
Readable.fromWeb(multipartResponse.body!) and readable.pipe(res) with a guard
that returns early when body is missing, otherwise create the Readable via
Readable.fromWeb(multipartResponse.body) and pipe it to res.
🧹 Nitpick comments (2)
apps/studio/lib/api/self-hosted/functions/fileSystemStore.ts (1)

46-47: Redundant isFile() check in helper function.

Line 46 already filters entries to files only, so the if (!file.isFile()) return check at line 78 is redundant. Consider removing it for clarity.

apps/studio/pages/api/v1/projects/[ref]/functions/[slug]/body.ts (1)

30-48: Consider returning 404 when function has no artifacts.

If getBlobArtifactsBySlug returns an empty array (e.g., function slug doesn't exist or has no files), the endpoint returns 200 with only metadata. This may confuse clients expecting function code or a clear "not found" signal.

💡 Suggested check
   const blobArtifacts = await store.getBlobArtifactsBySlug(slug)

+  if (blobArtifacts.length === 0) {
+    return res.status(404).json({ error: { message: `Function '${slug}' not found or has no files` } })
+  }
+
   const form = new FormData()

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@apps/studio/lib/api/self-hosted/functions/fileSystemStore.ts`:
- Around line 33-59: Prettier formatting is failing for the getFileEntriesBySlug
function in fileSystemStore.ts; run the project's Prettier/formatting tool (or
npm/yarn format script) against
apps/studio/lib/api/self-hosted/functions/fileSystemStore.ts to apply the repo's
formatting rules, then commit the updated file so the CI Prettier check
passes—ensure you preserve existing logic in getFileEntriesBySlug, including use
of path.resolve, readdir/stat, and the returned fileEntries structure.

In `@apps/studio/pages/api/v1/projects/`[ref]/functions/[slug]/body.ts:
- Around line 63-66: The multipart header writes entry.relativePath directly
into Content-Disposition which can contain quotes or CR/LF and corrupt the
stream; update the code that builds the header (the res.write call using
boundary and entry.relativePath) to produce a safe filename by
sanitizing/encoding the value—e.g., remove or replace CR and LF, escape
quotes/backslashes, and include an encoded fallback (filename* with RFC5987
percent-encoding or use encodeURIComponent on the name) so the header uses only
safe characters; ensure the same sanitized/encoded identifier is used both for
filename and filename* parameters.

@charislam
charislam force-pushed the feat-local-functions-management-api-3-function-blob-artifacts branch from 5998132 to c8be8fb Compare February 6, 2026 19:50
multipartResponse.headers.get('content-type') ?? 'multipart/form-data'
)

return res.status(200).send(await multipartResponse.text())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This loads everything into memory which could be significant, let's try streaming instead

async getBlobArtifactsBySlug(slug: string): Promise<FunctionBlobArtifact[]> {
if (slug === 'main') return []

const functionFolderPath = path.join(this.folderPath, slug)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

possible path traversal here?

@coveralls

Copy link
Copy Markdown

Coverage Status

coverage: 65.978% (-0.3%) from 66.278%
when pulling c8be8fb on kallebysantos:feat-local-functions-management-api-3-function-blob-artifacts
into 6bbe2c3 on supabase:master.

@charislam
charislam enabled auto-merge (squash) February 6, 2026 20:03
@charislam
charislam merged commit 997203c into supabase:master Feb 6, 2026
14 checks passed
charislam added a commit that referenced this pull request Feb 18, 2026
…nments (#42992)

Feature

## What is the current behavior?

The Functions counter on the Home page is only displayed in platform
environments.
In self-hosted setups, the counter is hidden due to a platform guard,
even though Functions may be available.

## What is the new behavior?

The Functions counter is now also displayed in self-hosted environments.

This is now possible thanks to the following PRs:

- #40690  
- #42322  
- #42349  
- #42350  

These PRs introduce and enable the API required for listing Functions in
Studio, making it feasible to show the Functions count outside of the
platform environment.

## Additional context

Related issues: #36285

This change removes the platform-only restriction around the Functions
card in the Home interface, allowing feature parity between platform and
self-hosted deployments where the Functions API is available.

---------

Co-authored-by: Andrey A. <[email protected]>
Co-authored-by: Charis Lam <[email protected]>

This branch had an error being deployed

1 failed deployment
Preview – learn — c8be8fb3 Deployed Feb 6, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli Related to supabase/cli edge functions self-hosted Related to self-hosted Supabase

Projects

Development

Successfully merging this pull request may close these issues.

4 participants