The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: add support for dropping and auto-extracting zip files in Edge Functions editor (#41801)
Lakshan Pererac3dfbc59564a
diff --git a/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types.ts b/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types.tsnew file mode 100644index 00000000000..4853d7ff8f7--- /dev/null+++ b/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types.ts@@ -0,0 +1,17 @@+export type FileData = {+ id: number+ name: string+ content: string+ selected?: boolean+}++export enum FileAction {+ CREATE_NEW = 'CREATE_NEW',+ REPLACE_EXISTING = 'REPLACE_EXISTING',+ REPLACE_NEW = 'REPLACE_NEW',+}++export type FileActionResult =+ | { action: FileAction.CREATE_NEW }+ | { action: FileAction.REPLACE_EXISTING; index: number }+ | { action: FileAction.REPLACE_NEW; index: number }diff --git a/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.utils.ts b/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.utils.tsindex 5e2403521f5..33f1665da1b 100644--- a/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.utils.ts+++ b/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.utils.ts@@ -1,3 +1,16 @@+import { formatBytes } from '@/lib/helpers'+import { BlobReader, BlobWriter, TextWriter, ZipReader } from '@zip.js/zip.js'+import { FileAction, type FileActionResult, type FileData } from './FileExplorerAndEditor.types'++// Configuration for zip file extraction+export const ZIP_EXTRACTION_CONFIG = {+ // Maximum total extracted size: 50MB (reasonable for edge functions)+ MAX_TOTAL_EXTRACTED_SIZE: 50 * 1024 * 1024, // 50MB++ // Maximum individual file size: 10MB+ MAX_INDIVIDUAL_FILE_SIZE: 10 * 1024 * 1024, // 10MB+} as const+export const isBinaryFile = (fileName: string): boolean => {const extension = fileName.split('.').pop()?.toLowerCase()const binaryExtensions = [@@ -47,3 +60,146 @@ export const getLanguageFromFileName = (fileName: string): string => {return 'plaintext' // Default to plaintext}}++/**+ * Check if a file is a zip archive based on file extension+ */+export const isZipFile = (fileName: string): boolean => {+ const extension = fileName.split('.').pop()?.toLowerCase()+ return extension === 'zip'+}++/**+ * Extract files from a zip archive+ * Returns an array of extracted files with their full paths as names (flat structure)+ */+export const extractZipFile = async (+ zipFile: File,+ onProgress?: (current: number, total: number) => void+): Promise<{ name: string; content: string; size: number }[]> => {+ const zipReader = new ZipReader(new BlobReader(zipFile))+ const entries = await zipReader.getEntries()++ const extractedFiles: { name: string; content: string; size: number }[] = []+ const skippedFiles: string[] = []+ const oversizedFiles: string[] = []+ const failedFiles: string[] = []++ let totalExtractedSize = 0++ // Filter out directories and process files+ const fileEntries = entries.filter((entry) => !entry.directory)++ for (let i = 0; i < fileEntries.length; i++) {+ const entry = fileEntries[i]+ const fileName = entry.filename++ // Report progress+ if (onProgress) {+ onProgress(i + 1, fileEntries.length)+ }++ // Skip hidden files and system files+ const pathParts = fileName.split('/')+ const hasHiddenFolder = pathParts.some((part) => part.startsWith('.') || part === '__MACOSX')+ if (hasHiddenFolder || fileName === '.DS_Store') {+ skippedFiles.push(fileName)+ continue+ }++ // Check individual file size+ const uncompressedSize = entry.uncompressedSize++ // Guard against undefined/NaN uncompressedSize to prevent bypass of size validation+ if (uncompressedSize === undefined || Number.isNaN(uncompressedSize)) {+ oversizedFiles.push(`${fileName} (unknown size - metadata unavailable)`)+ continue+ }++ if (uncompressedSize > ZIP_EXTRACTION_CONFIG.MAX_INDIVIDUAL_FILE_SIZE) {+ oversizedFiles.push(`${fileName} (${formatBytes(uncompressedSize)})`)+ continue+ }++ // Check total extracted size+ if (totalExtractedSize + uncompressedSize > ZIP_EXTRACTION_CONFIG.MAX_TOTAL_EXTRACTED_SIZE) {+ throw new Error(+ `Total extracted size would exceed ${formatBytes(ZIP_EXTRACTION_CONFIG.MAX_TOTAL_EXTRACTED_SIZE)}. ` ++ `Current: ${formatBytes(totalExtractedSize)}, ` ++ `Attempted to add: ${formatBytes(uncompressedSize)}`+ )+ }++ // Extract file content+ try {+ // Skip if entry is a directory or doesn't have getData method+ if (entry.directory || !entry.getData) {+ console.warn(`Entry ${fileName} is a directory or has no getData method, skipping`)+ failedFiles.push(fileName)+ continue+ }++ let content: string+ if (isBinaryFile(fileName)) {+ // For binary files, read as blob and convert to binary string+ const blob = await entry.getData(new BlobWriter())+ const arrayBuffer = await blob.arrayBuffer()+ const bytes = new Uint8Array(arrayBuffer)+ content = Array.from(bytes, (byte) => String.fromCharCode(byte)).join('')+ } else {+ // For text files, read as text+ content = await entry.getData(new TextWriter())+ }++ extractedFiles.push({+ name: fileName, // Keep full path as file name (flat structure)+ content,+ size: uncompressedSize,+ })++ totalExtractedSize += uncompressedSize+ } catch (error) {+ console.error(`Failed to extract file ${fileName}:`, error)+ failedFiles.push(fileName)+ }+ }++ await zipReader.close()++ // Throw error if no valid files found+ if (extractedFiles.length === 0) {+ const reasons: string[] = []+ if (skippedFiles.length > 0) {+ reasons.push(`${skippedFiles.length} hidden/system files`)+ }+ if (oversizedFiles.length > 0) {+ reasons.push(`${oversizedFiles.length} oversized files`)+ }+ if (failedFiles.length > 0) {+ reasons.push(`${failedFiles.length} files failed to extract`)+ }+ throw new Error(+ `No valid files found in zip archive. ${reasons.length > 0 ? 'Skipped: ' + reasons.join(', ') : ''}`+ )+ }++ return extractedFiles+}++export const getFileAction = (+ fileName: string,+ existingFiles: FileData[],+ newFiles: FileData[]+): FileActionResult => {+ const existingIndex = existingFiles.findIndex((f) => f.name === fileName)+ if (existingIndex !== -1) {+ return { action: FileAction.REPLACE_EXISTING, index: existingIndex }+ }++ const newIndex = newFiles.findIndex((f) => f.name === fileName)+ if (newIndex !== -1) {+ return { action: FileAction.REPLACE_NEW, index: newIndex }+ }++ return { action: FileAction.CREATE_NEW }+}diff --git a/apps/studio/components/ui/FileExplorerAndEditor/index.tsx b/apps/studio/components/ui/FileExplorerAndEditor/index.tsxindex 07c7450472b..94dfb1f52f1 100644--- a/apps/studio/components/ui/FileExplorerAndEditor/index.tsx+++ b/apps/studio/components/ui/FileExplorerAndEditor/index.tsx@@ -15,14 +15,14 @@ import {TreeView,TreeViewItem,} from 'ui'-import { getLanguageFromFileName, isBinaryFile } from './FileExplorerAndEditor.utils'--interface FileData {- id: number- name: string- content: string- selected?: boolean-}+import { FileAction, type FileData } from './FileExplorerAndEditor.types'+import {+ extractZipFile,+ getFileAction,+ getLanguageFromFileName,+ isBinaryFile,+ isZipFile,+} from './FileExplorerAndEditor.utils'interface FileExplorerAndEditorProps {files: FileData[]@@ -43,8 +43,14 @@ export const FileExplorerAndEditor = ({aiEndpoint,aiMetadata,}: FileExplorerAndEditorProps) => {- const selectedFile = files.find((f) => f.selected) ?? files[0]const [isDragOver, setIsDragOver] = useState(false)+ const [extractionProgress, setExtractionProgress] = useState<{+ current: number+ total: number+ } | null>(null)++ const selectedFile = files.find((f) => f.selected) ?? files[0]+ const isExtractingZip = extractionProgress !== nullconst [treeData, setTreeData] = useState({name: '',@@ -82,35 +88,123 @@ export const FileExplorerAndEditor = ({const addDroppedFiles = async (droppedFiles: FileList) => {const newFiles: FileData[] = []const updatedFiles = files.map((f) => ({ ...f, selected: false }))-- for (let i = 0; i < droppedFiles.length; i++) {- const file = droppedFiles[i]- const newId = Math.max(0, ...files.map((f) => f.id), ...newFiles.map((f) => f.id)) + 1-- try {- let content: string- if (isBinaryFile(file.name)) {- // For binary files, read as ArrayBuffer and convert to base64 or keep as binary data- const arrayBuffer = await file.arrayBuffer()- const bytes = new Uint8Array(arrayBuffer)- content = Array.from(bytes, (byte) => String.fromCharCode(byte)).join('')- } else {- content = await file.text()+ const allFiles: { name: string; content: string; size: number }[] = []++ let extractedCount = 0+ let replacedCount = 0+ let hasReplacedFiles = false // Track if any existing files were replaced++ for (const file of droppedFiles) {+ if (isZipFile(file.name)) {+ try {+ setExtractionProgress({ current: 0, total: 0 })+ const extractedFiles = await extractZipFile(file, (current, total) => {+ setExtractionProgress({ current, total })+ })+ allFiles.push(...extractedFiles)+ } catch (error) {+ toast.error(+ <div className="flex flex-col gap-y-1">+ <p className="text-foreground">Failed to extract {file.name}</p>+ <p className="text-foreground-light">+ {error instanceof Error ? error.message : 'Unknown error occurred'}+ </p>+ </div>,+ { duration: 8000 }+ )+ } finally {+ setExtractionProgress(null)}+ } else {+ try {+ let content: string+ if (isBinaryFile(file.name)) {+ // For binary files, read as ArrayBuffer and convert to base64 or keep as binary data+ const arrayBuffer = await file.arrayBuffer()+ const bytes = new Uint8Array(arrayBuffer)+ content = Array.from(bytes, (byte) => String.fromCharCode(byte)).join('')+ } else {+ content = await file.text()+ }+ allFiles.push({ name: file.name, size: file.size, content })+ } catch (error) {+ toast.error(`Failed to read file: ${file.name}: ${error}`)+ }+ }+ }++ for (const file of allFiles) {+ const actionResult = getFileAction(file.name, updatedFiles, newFiles)- newFiles.push({- id: newId,- name: file.name,- content,- selected: i === droppedFiles.length - 1, // Select the last dropped file- })- } catch (error) {- console.error(`Failed to read file ${file.name}:`, error)+ switch (actionResult.action) {+ case FileAction.REPLACE_EXISTING:+ updatedFiles[actionResult.index] = {+ ...updatedFiles[actionResult.index],+ content: file.content,+ selected: false,+ }+ replacedCount+++ hasReplacedFiles = true+ break++ case FileAction.REPLACE_NEW:+ newFiles[actionResult.index] = {+ ...newFiles[actionResult.index],+ content: file.content,+ selected: false,+ }+ replacedCount+++ break++ case FileAction.CREATE_NEW:+ const newId =+ Math.max(+ 0,+ ...files.map((f) => f.id),+ ...updatedFiles.map((f) => f.id),+ ...newFiles.map((f) => f.id)+ ) + 1+ newFiles.push({+ id: newId,+ name: file.name,+ content: file.content,+ selected: false,+ })+ extractedCount+++ break}}+ // Show success message+ const messages: string[] = []+ if (extractedCount > 0) {+ messages.push(`Added ${extractedCount} new file${extractedCount > 1 ? 's' : ''}`)+ }+ if (replacedCount > 0) {+ messages.push(`Replaced ${replacedCount} existing file${replacedCount > 1 ? 's' : ''}`)+ }+ const totalFilesProcessed = extractedCount + replacedCount++ if (totalFilesProcessed > 0) {+ toast.success(+ <div className="flex flex-col gap-y-1">+ <p className="text-foreground">+ Successfully added dropped file{totalFilesProcessed > 1 ? 's' : ''}+ </p>+ <p className="text-foreground-light">{messages.join(', ')}.</p>+ </div>,+ { duration: 5000 }+ )+ }++ // Select the last added/modified fileif (newFiles.length > 0) {+ newFiles[newFiles.length - 1].selected = trueonFilesChange([...updatedFiles, ...newFiles])+ } else if (hasReplacedFiles) {+ // If we only replaced files, select the first one+ updatedFiles[0].selected = true+ onFilesChange(updatedFiles)}}@@ -245,7 +339,7 @@ export const FileExplorerAndEditor = ({onDrop={handleDrop}><AnimatePresence>- {isDragOver && (+ {(isDragOver || isExtractingZip) && (<motion.divinitial={{ opacity: 0 }}animate={{ opacity: 1 }}@@ -254,7 +348,16 @@ export const FileExplorerAndEditor = ({className="absolute inset-0 bg bg-opacity-30 z-10 flex items-center justify-center"><div className="w-96 py-20 bg bg-opacity-60 border-2 border-dashed border-muted flex items-center justify-center">- <div className="text-base">Drop files here to add them</div>+ {isExtractingZip && extractionProgress ? (+ <div className="text-center space-y-2">+ <div className="text-base">Extracting zip file...</div>+ <div className="text-sm text-foreground-light">+ Processing file {extractionProgress.current} of {extractionProgress.total}+ </div>+ </div>+ ) : (+ <div className="text-base">Drop files here to add them</div>+ )}</div></motion.div>)}