The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(storage): archived objects data layer (#49677)
Francesco Sansalvadore876bb8cf9e9e
diff --git a/apps/studio/components/interfaces/Storage/Storage.types.ts b/apps/studio/components/interfaces/Storage/Storage.types.tsindex 3763158c309..a738cdf60d6 100644--- a/apps/studio/components/interfaces/Storage/Storage.types.ts+++ b/apps/studio/components/interfaces/Storage/Storage.types.ts@@ -40,6 +40,8 @@ export interface StorageItem {// UI specific properties, not from APIisCorrupted: booleanpath?: string+ /** Set on a row synthesized from the archived list; absent on a synthesized folder. */+ archived?: { archivedObjectId?: string }}export type StorageItemWithColumn = StorageItem & { columnIndex: number }diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.test.tsnew file mode 100644index 00000000000..f53e336eede--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it } from 'vitest'++import { STORAGE_ROW_TYPES } from '../Storage.constants'+import { getArchivedOverlayItems, getArchivedSegments } from './archivedOverlay.utils'+import type { ArchivedObject } from '@/data/storage/versioning/archived-objects-query'++const archived = (path: string, overrides: Partial<ArchivedObject> = {}): ArchivedObject => ({+ id: `id-${path}`,+ path,+ archivedAt: '2026-08-01T00:00:00Z',+ currentVersion: {+ versionId: `v-${path}`,+ size: 1024,+ createdAt: '2026-07-01T00:00:00Z',+ action: 'overwrite',+ },+ noncurrentVersions: [],+ ...overrides,+})++const overlay = (+ folderSegments: string[],+ archivedObjects: ArchivedObject[],+ existingItemNames: string[] = []+) =>+ getArchivedOverlayItems({+ folderSegments,+ archivedObjects,+ existingItemNames: new Set(existingItemNames),+ })++describe('getArchivedSegments', () => {+ it('splits a nested path into segments', () => {+ expect(getArchivedSegments(archived('matches/round-3/final.png'))).toEqual([+ 'matches',+ 'round-3',+ 'final.png',+ ])+ })++ it('tolerates leading, trailing and repeated slashes', () => {+ expect(getArchivedSegments(archived('/matches//round-3/final.png/'))).toEqual([+ 'matches',+ 'round-3',+ 'final.png',+ ])+ })++ it('handles a file at the bucket root', () => {+ expect(getArchivedSegments(archived('logo.svg'))).toEqual(['logo.svg'])+ })+})++describe('getArchivedOverlayItems', () => {+ it('returns nothing when there is nothing archived', () => {+ expect(overlay([], [])).toEqual([])+ })++ it('surfaces a root-level object as a file row at the root', () => {+ const [row] = overlay([], [archived('logo.svg')])+ expect(row.name).toBe('logo.svg')+ expect(row.type).toBe(STORAGE_ROW_TYPES.FILE)+ expect(row.archived).toEqual({ archivedObjectId: 'id-logo.svg' })+ expect(row.path).toBe('logo.svg')+ })++ it('carries the archived size and timestamp onto the row', () => {+ const [row] = overlay([], [archived('logo.svg')])+ expect(row.metadata?.size).toBe(1024)+ expect(row.updated_at).toBe('2026-08-01T00:00:00Z')+ })++ it('does not surface a root object when viewing a subfolder', () => {+ expect(overlay(['matches'], [archived('logo.svg')])).toEqual([])+ })++ it('surfaces a nested object as a folder row one level up', () => {+ const rows = overlay([], [archived('matches/final.png')])+ expect(rows).toHaveLength(1)+ expect(rows[0].name).toBe('matches')+ expect(rows[0].type).toBe(STORAGE_ROW_TYPES.FOLDER)+ expect(rows[0].archived).toEqual({})+ })++ it('surfaces the file itself once inside that folder', () => {+ const rows = overlay(['matches'], [archived('matches/final.png')])+ expect(rows).toHaveLength(1)+ expect(rows[0].name).toBe('final.png')+ expect(rows[0].type).toBe(STORAGE_ROW_TYPES.FILE)+ })++ it('coalesces several objects under one subfolder into a single row', () => {+ const rows = overlay(+ [],+ [archived('matches/a.png'), archived('matches/b.png'), archived('matches/deep/c.png')]+ )+ expect(rows.map((r) => r.name)).toEqual(['matches'])+ })++ it('skips a folder that already exists in the live listing', () => {+ expect(overlay([], [archived('matches/final.png')], ['matches'])).toEqual([])+ })++ it('skips a file that already exists in the live listing', () => {+ expect(overlay([], [archived('logo.svg')], ['logo.svg'])).toEqual([])+ })++ it('orders folders before files', () => {+ const rows = overlay([], [archived('logo.svg'), archived('matches/final.png')])+ expect(rows.map((r) => r.type)).toEqual([STORAGE_ROW_TYPES.FOLDER, STORAGE_ROW_TYPES.FILE])+ })++ it('hides the empty folder placeholder, as the live listing does', () => {+ expect(overlay(['matches'], [archived('matches/.emptyFolderPlaceholder')])).toEqual([])+ })++ it('still shows the folder whose only archived object is the placeholder', () => {+ const rows = overlay([], [archived('matches/.emptyFolderPlaceholder')])+ expect(rows.map((r) => r.name)).toEqual(['matches'])+ expect(rows[0].type).toBe(STORAGE_ROW_TYPES.FOLDER)+ })++ it('still shows a folder that holds a real object beside the placeholder', () => {+ const rows = overlay(+ [],+ [archived('matches/.emptyFolderPlaceholder'), archived('matches/final.png')]+ )+ expect(rows.map((r) => r.name)).toEqual(['matches'])+ })++ it('only descends one level at a time', () => {+ const rows = overlay([], [archived('a/b/c/d.png')])+ expect(rows.map((r) => r.name)).toEqual(['a'])+ expect(overlay(['a'], [archived('a/b/c/d.png')]).map((r) => r.name)).toEqual(['b'])+ })+})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.tsnew file mode 100644index 00000000000..0592b5a1535--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.ts@@ -0,0 +1,89 @@+import { STORAGE_ROW_STATUS, STORAGE_ROW_TYPES } from '../Storage.constants'+import type { StorageItem } from '../Storage.types'+import { EMPTY_FOLDER_PLACEHOLDER_FILE_NAME } from './StorageExplorer.utils'+import type { ArchivedObject } from '@/data/storage/versioning/archived-objects-query'++const splitPath = (path: string): string[] => path.split('/').filter((segment) => segment !== '')++/** The only place that interprets `ArchivedObject.path`. */+export const getArchivedSegments = (object: ArchivedObject): string[] => splitPath(object.path)++const isUnderFolder = (folderSegments: string[], objectSegments: string[]): boolean => {+ if (objectSegments.length <= folderSegments.length) return false+ return folderSegments.every((segment, index) => segment === objectSegments[index])+}++export interface ArchivedOverlayInput {+ folderSegments: string[]+ archivedObjects: ArchivedObject[]+ /** Names from the live listing; a live item of the same name wins. */+ existingItemNames: Set<string>+}++/** Objects deeper down coalesce into one folder row per next segment. */+export const getArchivedOverlayItems = ({+ folderSegments,+ archivedObjects,+ existingItemNames,+}: ArchivedOverlayInput): StorageItem[] => {+ const files: StorageItem[] = []+ const folderNames = new Set<string>()++ for (const object of archivedObjects) {+ const segments = getArchivedSegments(object)+ if (!isUnderFolder(folderSegments, segments)) continue++ const nextSegment = segments[folderSegments.length]+ const isDirectChild = segments.length === folderSegments.length + 1++ if (!isDirectChild) {+ folderNames.add(nextSegment)+ continue+ }++ // Hidden as in the live listing. It still rolled the folder up above, so an archived+ // empty folder stays visible and actionable rather than showing its placeholder.+ if (nextSegment === EMPTY_FOLDER_PLACEHOLDER_FILE_NAME) continue++ if (existingItemNames.has(nextSegment)) continue++ files.push({+ id: object.id,+ name: nextSegment,+ type: STORAGE_ROW_TYPES.FILE,+ status: STORAGE_ROW_STATUS.READY,+ metadata: {+ size: object.currentVersion.size,+ mimetype: '',+ cacheControl: '',+ contentLength: object.currentVersion.size,+ httpStatusCode: 0,+ eTag: '',+ lastModified: object.archivedAt,+ },+ created_at: null,+ updated_at: object.archivedAt,+ last_accessed_at: null,+ isCorrupted: false,+ path: [...folderSegments, nextSegment].join('/'),+ archived: { archivedObjectId: object.id },+ })+ }++ const folders: StorageItem[] = [...folderNames]+ .filter((folderName) => !existingItemNames.has(folderName))+ .map((folderName) => ({+ id: null,+ name: folderName,+ type: STORAGE_ROW_TYPES.FOLDER,+ status: STORAGE_ROW_STATUS.READY,+ metadata: null,+ created_at: null,+ updated_at: null,+ last_accessed_at: null,+ isCorrupted: false,+ archived: {},+ }))++ return [...folders, ...files]+}diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/archivedVersions.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedVersions.utils.test.tsnew file mode 100644index 00000000000..43c499930d4--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedVersions.utils.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest'++import { getMergedArchivedVersions } from './archivedVersions.utils'+import type { ArchivedObject } from '@/data/storage/versioning/archived-objects-query'++const object: ArchivedObject = {+ id: 'obj-1',+ path: 'matches/final.png',+ archivedAt: '2026-08-10T00:00:00Z',+ currentVersion: {+ versionId: 'v-current',+ size: 900,+ createdAt: '2026-08-01T00:00:00Z',+ action: 'overwrite',+ },+ noncurrentVersions: [+ { versionId: 'v-2', size: 800, createdAt: '2026-07-20T00:00:00Z', action: 'overwrite' },+ { versionId: 'v-1', size: 700, createdAt: '2026-07-01T00:00:00Z', action: 'initial upload' },+ ],+}++describe('getMergedArchivedVersions', () => {+ it('puts the version that was live at archive time first', () => {+ const [first] = getMergedArchivedVersions(object)+ expect(first.versionId).toBe('v-current')+ expect(first.wasCurrentAtArchive).toBe(true)+ })++ it('follows it with the retained noncurrent versions, newest first', () => {+ expect(getMergedArchivedVersions(object).map((v) => v.versionId)).toEqual([+ 'v-current',+ 'v-2',+ 'v-1',+ ])+ })++ it('flags only the first row as having been current', () => {+ const rows = getMergedArchivedVersions(object)+ expect(rows.filter((v) => v.wasCurrentAtArchive)).toHaveLength(1)+ })++ it('preserves each version’s own size and action rather than inventing them', () => {+ const rows = getMergedArchivedVersions(object)+ expect(rows.map((v) => v.size)).toEqual([900, 800, 700])+ expect(rows.map((v) => v.action)).toEqual(['overwrite', 'overwrite', 'initial upload'])+ })++ it('returns just the archived version when nothing else was retained', () => {+ const rows = getMergedArchivedVersions({ ...object, noncurrentVersions: [] })+ expect(rows).toHaveLength(1)+ expect(rows[0].wasCurrentAtArchive).toBe(true)+ })+})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/archivedVersions.utils.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedVersions.utils.tsnew file mode 100644index 00000000000..687d4c6e3be--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedVersions.utils.ts@@ -0,0 +1,15 @@+import type {+ ArchivedObject,+ ArchivedObjectVersion,+} from '@/data/storage/versioning/archived-objects-query'++export interface ArchivedVersionRow extends ArchivedObjectVersion {+ /** Deleting this one promotes the version behind it, so its actions differ. */+ wasCurrentAtArchive: boolean+}++/** Newest first: the version live at archive time, then the rest. */+export const getMergedArchivedVersions = (object: ArchivedObject): ArchivedVersionRow[] => [+ { ...object.currentVersion, wasCurrentAtArchive: true },+ ...object.noncurrentVersions.map((version) => ({ ...version, wasCurrentAtArchive: false })),+]diff --git a/apps/studio/data/storage/keys.ts b/apps/studio/data/storage/keys.tsindex e7052aa12e6..13257248024 100644--- a/apps/studio/data/storage/keys.ts+++ b/apps/studio/data/storage/keys.ts@@ -97,6 +97,8 @@ export const storageKeys = {path,...(versionId === undefined ? [] : [versionId]),] as const,+ archivedObjects: (projectRef: string | undefined, bucketId: string | undefined) =>+ ['projects', projectRef, 'buckets', bucketId, 'archived-objects'] as const,icebergNamespaces: ({ projectRef, warehouse }: { projectRef?: string; warehouse?: string }) =>[projectRef, 'warehouse', warehouse, 'namespaces'] as const,icebergNamespace: ({diff --git a/apps/studio/data/storage/versioning/archived-object-purge-mutation.test.tsx b/apps/studio/data/storage/versioning/archived-object-purge-mutation.test.tsxnew file mode 100644index 00000000000..3c8b4522484--- /dev/null+++ b/apps/studio/data/storage/versioning/archived-object-purge-mutation.test.tsx@@ -0,0 +1,96 @@+import { waitFor } from '@testing-library/react'+import { beforeEach, describe, expect, it } from 'vitest'++import { useArchivedObjectPurgeMutation } from './archived-object-purge-mutation'+import { customRenderHook } from '@/tests/lib/custom-render'+import { addAPIMock } from '@/tests/lib/msw'++type ListRow = {+ name: string+ version: string+ created_at: string+ archived_at?: string | null+ is_delete_marker?: boolean+}++const PATH = 'images/gone.png'+const MARKER = 'v-marker'++const row = (version: string, overrides: Partial<ListRow> = {}): ListRow => ({+ name: PATH,+ version,+ created_at: '2026-01-01T00:00:00Z',+ archived_at: '2026-02-01T00:00:00Z',+ ...overrides,+})++const marker = (version = MARKER) =>+ row(version, { archived_at: null, is_delete_marker: true, created_at: '2026-02-01T00:00:00Z' })++/** Successive responses from the list endpoint, one per round the purge runs. */+const mockListPages = (pages: ListRow[][]) => {+ let call = 0+ addAPIMock({+ method: 'post',+ path: '/platform/storage/:ref/buckets/:id/objects/list',+ response: () => Response.json(pages[Math.min(call++, pages.length - 1)]),+ })+}++const purge = () =>+ customRenderHook(() => useArchivedObjectPurgeMutation()).result.current.mutateAsync({+ projectRef: 'abcdef',+ bucketId: 'my-bucket',+ archivedObjectId: MARKER,+ path: PATH,+ })++describe('useArchivedObjectPurgeMutation', () => {+ let deleted: string[][] = []++ beforeEach(() => {+ deleted = []+ addAPIMock({+ method: 'delete',+ path: '/platform/storage/:ref/buckets/:id/objects',+ response: async ({ request }) => {+ const body = (await request.json()) as { paths: { versionId: string }[] }+ deleted.push(body.paths.map((entry) => entry.versionId))+ return Response.json({})+ },+ })+ })++ it('keeps listing until the history is gone, since one page is capped at 1000 rows', async () => {+ mockListPages([[marker(), row('v2'), row('v1')], [row('v1')], []])++ await purge()++ await waitFor(() => expect(deleted).toHaveLength(2))+ expect(deleted[0]).toEqual([MARKER, 'v2', 'v1'])+ expect(deleted[1]).toEqual(['v1'])+ })++ it('refuses to delete anything once the file has been restored', async () => {+ // No delete marker on top: something un-archived the path after the dialog opened.+ mockListPages([[row('v2', { archived_at: null }), row('v1')]])++ await expect(purge()).rejects.toThrow(/no longer archived/)+ expect(deleted).toEqual([])+ })++ it('stops rather than delete a version that went live mid-purge', async () => {+ // The first round clears the history; by the second, the path has been written again.+ mockListPages([[marker(), row('v2')], [row('v-new', { archived_at: null })]])++ await expect(purge()).rejects.toThrow(/restored or replaced/)+ expect(deleted).toEqual([[MARKER, 'v2']])+ })++ it('gives up rather than spin when a round deletes nothing', async () => {+ mockListPages([[marker(), row('v1')]])++ await expect(purge()).rejects.toThrow(/could not be deleted/)+ expect(deleted).toHaveLength(1)+ })+})diff --git a/apps/studio/data/storage/versioning/archived-object-purge-mutation.ts b/apps/studio/data/storage/versioning/archived-object-purge-mutation.tsnew file mode 100644index 00000000000..277bc43c107--- /dev/null+++ b/apps/studio/data/storage/versioning/archived-object-purge-mutation.ts@@ -0,0 +1,101 @@+import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query'+import { toast } from 'sonner'++import { storageKeys } from '../keys'+import { objectVersionsQueryOptions, type ObjectVersion } from './object-versions-query'+import { del, handleError } from '@/data/fetchers'+import type { ResponseError } from '@/types'++export type ArchivedObjectPurgeVariables = {+ projectRef: string+ bucketId: string+ archivedObjectId: string+ path: string+}++export const useArchivedObjectPurgeMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<void, ResponseError, ArchivedObjectPurgeVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ /** Every retained version goes, the delete marker included. */+ const purgeArchivedObject = async ({+ projectRef,+ bucketId,+ archivedObjectId,+ path,+ }: ArchivedObjectPurgeVariables) => {+ if (!projectRef) throw new Error('projectRef is required')+ if (!bucketId) throw new Error('bucketId is required')+ if (!archivedObjectId) throw new Error('archivedObjectId is required')+ if (!path) throw new Error('path is required')++ const listVersions = () =>+ queryClient.fetchQuery({+ ...objectVersionsQueryOptions({ projectRef, bucketId, path }),+ // Each round has to see what the last one left behind, not the cached first page.+ staleTime: 0,+ })++ const deleteVersions = async (versions: ObjectVersion[]) => {+ const { error } = await del('/platform/storage/{ref}/buckets/{id}/objects', {+ params: { path: { ref: projectRef, id: bucketId } },+ body: { paths: versions.map((version) => ({ path, versionId: version.versionId })) },+ })++ if (error) handleError(error)+ }++ let versions = await listVersions()++ // Versions are deleted by id, the current one included, so a restore between opening the+ // dialog and confirming would hand this a live file to destroy. Re-reading the marker+ // immediately before the first delete is as close as the client can get; only Storage can+ // make the check and the delete one operation.+ const current = versions.find((version) => version.isCurrent)+ if (current?.action !== 'delete marker' || current.versionId !== archivedObjectId) {+ throw new Error(`${path} is no longer archived`)+ }++ // The list endpoint returns one capped page, so a longer history takes several rounds.+ // Stopping after the first would report a purge that left versions behind — and with the+ // marker gone, one of the survivors would become current again.+ while (versions.length > 0) {+ await deleteVersions(versions)++ const remaining = await listVersions()+ // Deleting the marker promotes nothing, so nothing here should be live. One that is+ // arrived while the purge was running — a restore, or a new upload to the same path —+ // and belongs to the user, not to the archive the next round would hand to `del`.+ const live = remaining.find((version) => version.isCurrent)+ if (live !== undefined && live.versionId !== archivedObjectId) {+ throw new Error(`${path} was restored or replaced while it was being deleted`)+ }+ // Nothing went away, so another round would spin rather than make progress.+ if (remaining.length >= versions.length) {+ throw new Error(`Some versions of ${path} could not be deleted`)+ }+ versions = remaining+ }+ }++ return useMutation<void, ResponseError, ArchivedObjectPurgeVariables>({+ mutationFn: purgeArchivedObject,+ async onSuccess(data, variables, context) {+ await queryClient.invalidateQueries({+ queryKey: storageKeys.archivedObjects(variables.projectRef, variables.bucketId),+ })+ await onSuccess?.(data, variables, context)+ },+ async onError(error, variables, context) {+ if (onError === undefined) toast.error(`Failed to delete file: ${error.message}`)+ else onError(error, variables, context)+ },+ ...options,+ })+}diff --git a/apps/studio/data/storage/versioning/archived-object-restore-mutation.ts b/apps/studio/data/storage/versioning/archived-object-restore-mutation.tsnew file mode 100644index 00000000000..89ef0658d60--- /dev/null+++ b/apps/studio/data/storage/versioning/archived-object-restore-mutation.ts@@ -0,0 +1,60 @@+import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query'+import { toast } from 'sonner'++import { storageKeys } from '../keys'+import { del, handleError } from '@/data/fetchers'+import type { ResponseError } from '@/types'++export type ArchivedObjectRestoreVariables = {+ projectRef: string+ bucketId: string+ /** The delete marker's version id, which is what identifies an archived object. */+ archivedObjectId: string+ path: string+}++/** Removing the delete marker promotes the version underneath; nothing is copied. */+async function restoreArchivedObject({+ projectRef,+ bucketId,+ archivedObjectId,+ path,+}: ArchivedObjectRestoreVariables) {+ if (!projectRef) throw new Error('projectRef is required')+ if (!bucketId) throw new Error('bucketId is required')+ if (!archivedObjectId) throw new Error('archivedObjectId is required')+ if (!path) throw new Error('path is required')++ const { error } = await del('/platform/storage/{ref}/buckets/{id}/objects', {+ params: { path: { ref: projectRef, id: bucketId } },+ body: { paths: [{ path, versionId: archivedObjectId }] },+ })++ if (error) handleError(error)+}++export const useArchivedObjectRestoreMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<void, ResponseError, ArchivedObjectRestoreVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<void, ResponseError, ArchivedObjectRestoreVariables>({+ mutationFn: restoreArchivedObject,+ async onSuccess(data, variables, context) {+ await queryClient.invalidateQueries({+ queryKey: storageKeys.archivedObjects(variables.projectRef, variables.bucketId),+ })+ await onSuccess?.(data, variables, context)+ },+ async onError(error, variables, context) {+ if (onError === undefined) toast.error(`Failed to restore file: ${error.message}`)+ else onError(error, variables, context)+ },+ ...options,+ })+}diff --git a/apps/studio/data/storage/versioning/archived-object-version-delete-mutation.ts b/apps/studio/data/storage/versioning/archived-object-version-delete-mutation.tsnew file mode 100644index 00000000000..1850bae9f9e--- /dev/null+++ b/apps/studio/data/storage/versioning/archived-object-version-delete-mutation.ts@@ -0,0 +1,63 @@+import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query'+import { toast } from 'sonner'++import { storageKeys } from '../keys'+import { del, handleError } from '@/data/fetchers'+import type { ResponseError } from '@/types'++export type ArchivedObjectVersionDeleteVariables = {+ projectRef: string+ bucketId: string+ archivedObjectId: string+ path: string+ versionId: string+ /** Deleting the version live at archive time promotes the next one, or removes the object. */+ wasCurrentAtArchive: boolean+}++async function deleteArchivedObjectVersion({+ projectRef,+ bucketId,+ archivedObjectId,+ path,+ versionId,+}: ArchivedObjectVersionDeleteVariables) {+ if (!projectRef) throw new Error('projectRef is required')+ if (!bucketId) throw new Error('bucketId is required')+ if (!archivedObjectId) throw new Error('archivedObjectId is required')+ if (!path) throw new Error('path is required')+ if (!versionId) throw new Error('versionId is required')++ const { error } = await del('/platform/storage/{ref}/buckets/{id}/objects', {+ params: { path: { ref: projectRef, id: bucketId } },+ body: { paths: [{ path, versionId }] },+ })++ if (error) handleError(error)+}++export const useArchivedObjectVersionDeleteMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<void, ResponseError, ArchivedObjectVersionDeleteVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<void, ResponseError, ArchivedObjectVersionDeleteVariables>({+ mutationFn: deleteArchivedObjectVersion,+ async onSuccess(data, variables, context) {+ await queryClient.invalidateQueries({+ queryKey: storageKeys.archivedObjects(variables.projectRef, variables.bucketId),+ })+ await onSuccess?.(data, variables, context)+ },+ async onError(error, variables, context) {+ if (onError === undefined) toast.error(`Failed to delete version: ${error.message}`)+ else onError(error, variables, context)+ },+ ...options,+ })+}diff --git a/apps/studio/data/storage/versioning/archived-objects-query.test.ts b/apps/studio/data/storage/versioning/archived-objects-query.test.tsnew file mode 100644index 00000000000..e12f2a45ec6--- /dev/null+++ b/apps/studio/data/storage/versioning/archived-objects-query.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from 'vitest'++import { dropPartialTrailingPath, toArchivedObjects } from './archived-objects-query'++type StorageObjectV2 = Parameters<typeof toArchivedObjects>[0][number]++const row = (overrides: Partial<StorageObjectV2>): StorageObjectV2 => ({+ name: 'folder/photo.jpg',+ id: 'id',+ updated_at: '2026-01-01T00:00:00Z',+ created_at: '2026-01-01T00:00:00Z',+ last_accessed_at: '2026-01-01T00:00:00Z',+ metadata: { size: 100, mimetype: 'image/jpeg' },+ ...overrides,+})++describe('toArchivedObjects', () => {+ it('treats an object whose top row is a delete marker as archived', () => {+ const archived = toArchivedObjects([+ row({ version: 'v1', created_at: '2026-01-01T00:00:00Z', archived_at: '2026-02-01' }),+ row({+ version: 'marker',+ created_at: '2026-02-01T00:00:00Z',+ is_delete_marker: true,+ metadata: null,+ }),+ ])++ expect(archived).toHaveLength(1)+ expect(archived[0].id).toBe('marker')+ expect(archived[0].path).toBe('folder/photo.jpg')+ expect(archived[0].archivedAt).toBe('2026-02-01T00:00:00Z')+ expect(archived[0].currentVersion.versionId).toBe('v1')+ // The preview needs it to decide what to render.+ expect(archived[0].currentVersion.mimeType).toBe('image/jpeg')+ })++ it('ignores a live object', () => {+ expect(+ toArchivedObjects([+ row({ version: 'v1', created_at: '2026-01-01T00:00:00Z', archived_at: '2026-02-01' }),+ row({ version: 'v2', created_at: '2026-02-01T00:00:00Z' }),+ ])+ ).toEqual([])+ })++ it('surfaces the version live at archive time, with the rest behind it newest first', () => {+ const archived = toArchivedObjects([+ row({ version: 'oldest', created_at: '2026-01-01T00:00:00Z', archived_at: '2026-02-01' }),+ row({ version: 'middle', created_at: '2026-02-01T00:00:00Z', archived_at: '2026-03-01' }),+ row({ version: 'newest', created_at: '2026-03-01T00:00:00Z', archived_at: '2026-04-01' }),+ row({+ version: 'marker',+ created_at: '2026-04-01T00:00:00Z',+ is_delete_marker: true,+ metadata: null,+ }),+ ])++ expect(archived[0].currentVersion.versionId).toBe('newest')+ expect(archived[0].noncurrentVersions.map((v) => v.versionId)).toEqual(['middle', 'oldest'])+ expect(archived[0].noncurrentVersions.map((v) => v.action)).toEqual([+ 'overwrite',+ 'initial upload',+ ])+ })++ it('skips a delete marker with nothing retained under it', () => {+ expect(+ toArchivedObjects([+ row({+ version: 'marker',+ created_at: '2026-02-01T00:00:00Z',+ is_delete_marker: true,+ metadata: null,+ }),+ ])+ ).toEqual([])+ })++ it('groups rows by path and returns the most recently archived first', () => {+ const archived = toArchivedObjects([+ row({ name: 'a.txt', version: 'a1', created_at: '2026-01-01T00:00:00Z', archived_at: 'x' }),+ row({+ name: 'a.txt',+ version: 'a-marker',+ created_at: '2026-02-01T00:00:00Z',+ is_delete_marker: true,+ }),+ row({+ name: 'deep/b.txt',+ version: 'b1',+ created_at: '2026-01-01T00:00:00Z',+ archived_at: 'x',+ }),+ row({+ name: 'deep/b.txt',+ version: 'b-marker',+ created_at: '2026-03-01T00:00:00Z',+ is_delete_marker: true,+ }),+ ])++ expect(archived.map((object) => object.path)).toEqual(['deep/b.txt', 'a.txt'])+ })++ it('drops rows the API returned without a version id', () => {+ expect(toArchivedObjects([row({ is_delete_marker: true })])).toEqual([])+ })+})++describe('dropPartialTrailingPath', () => {+ it('drops every row of the path the listing stopped on', () => {+ const kept = dropPartialTrailingPath([+ row({ name: 'a.txt', version: 'a1' }),+ row({ name: 'b.txt', version: 'b1' }),+ row({ name: 'b.txt', version: 'b2' }),+ ])++ expect(kept.map((object) => object.name)).toEqual(['a.txt'])+ })++ it('leaves an empty listing alone', () => {+ expect(dropPartialTrailingPath([])).toEqual([])+ })+})diff --git a/apps/studio/data/storage/versioning/archived-objects-query.ts b/apps/studio/data/storage/versioning/archived-objects-query.tsnew file mode 100644index 00000000000..6dbc9913bf9--- /dev/null+++ b/apps/studio/data/storage/versioning/archived-objects-query.ts@@ -0,0 +1,151 @@+import { queryOptions } from '@tanstack/react-query'+import { components } from 'api-types'++import { storageKeys } from '../keys'+import type { ObjectVersionAction } from './object-versions-query'+import { handleError, post } from '@/data/fetchers'+import { IS_PLATFORM } from '@/lib/constants'+import type { ResponseError } from '@/types'++type StorageObjectV2 = components['schemas']['StorageListResponseV2_Output']['objects'][number]++export interface ArchivedObjectVersion {+ versionId: string+ size: number+ createdAt: string+ action: ObjectVersionAction+ /** What the preview renders from. A delete marker carries no metadata. */+ mimeType?: string+}++export interface ArchivedObject {+ id: string+ /** Full path including the file name. Only `getArchivedSegments` splits it. */+ path: string+ archivedAt: string+ /** The version live when the object was archived, i.e. the one under the delete marker. */+ currentVersion: ArchivedObjectVersion+ /** Newest first. */+ noncurrentVersions: ArchivedObjectVersion[]+}++export interface ArchivedObjectsResult {+ objects: ArchivedObject[]+ /** The bucket holds more rows than one listing run can carry, so `objects` is incomplete. */+ isTruncated: boolean+}++export type ArchivedObjectsVariables = {+ projectRef?: string+ bucketId?: string+}++export type ArchivedObjectsError = ResponseError++const PAGE_SIZE = 1000+// Bounded so a pathological bucket can't page forever.+const MAX_PAGES = 20++const toVersion = (object: StorageObjectV2, action: ObjectVersionAction) => ({+ versionId: object.version as string,+ size: Number(object.metadata?.size ?? 0),+ createdAt: object.created_at ?? object.updated_at ?? '',+ action,+ mimeType: object.metadata?.mimetype ?? undefined,+})++/** An object is archived when the row currently at its path is a delete marker. */+export const toArchivedObjects = (objects: StorageObjectV2[]): ArchivedObject[] => {+ const byPath = new Map<string, StorageObjectV2[]>()+ for (const object of objects) {+ if (!object.version) continue+ const rows = byPath.get(object.name) ?? []+ rows.push(object)+ byPath.set(object.name, rows)+ }++ const archived: ArchivedObject[] = []++ for (const [path, rows] of byPath) {+ const sorted = [...rows].sort((a, b) => (b.created_at ?? '').localeCompare(a.created_at ?? ''))+ const current = sorted.find((row) => !row.archived_at)+ if (!current?.is_delete_marker) continue++ const retained = sorted.filter((row) => row !== current && !row.is_delete_marker)+ const [liveAtArchive, ...rest] = retained+ if (liveAtArchive === undefined) continue++ archived.push({+ id: current.version as string,+ path,+ archivedAt: current.created_at ?? current.updated_at ?? '',+ currentVersion: toVersion(liveAtArchive, rest.length === 0 ? 'initial upload' : 'overwrite'),+ noncurrentVersions: rest.map((row, index) =>+ toVersion(row, index === rest.length - 1 ? 'initial upload' : 'overwrite')+ ),+ })+ }++ return archived.sort((a, b) => b.archivedAt.localeCompare(a.archivedAt))+}++/**+ * The listing is ordered by name, so a page cap can cut a path's rows in half. `toArchivedObjects`+ * would then group a fragment: a missing delete marker reads as a live object, and missing retained+ * versions drop an archived one. Discard the trailing path rather than classify it on partial rows.+ */+export const dropPartialTrailingPath = (objects: StorageObjectV2[]): StorageObjectV2[] => {+ const partialPath = objects.at(-1)?.name+ if (partialPath === undefined) return objects++ const kept = [...objects]+ while (kept.length > 0 && kept[kept.length - 1].name === partialPath) kept.pop()+ return kept+}++async function getArchivedObjects(+ { projectRef, bucketId }: ArchivedObjectsVariables,+ signal?: AbortSignal+): Promise<ArchivedObjectsResult> {+ if (!projectRef) throw new Error('projectRef is required')+ if (!bucketId) throw new Error('bucketId is required')++ let objects: StorageObjectV2[] = []+ let cursor: string | undefined+ let isTruncated = false++ for (let page = 0; page < MAX_PAGES; page++) {+ const { data, error } = await post('/platform/storage/{ref}/buckets/{id}/objects/list-v2', {+ params: { path: { ref: projectRef, id: bucketId } },+ body: {+ limit: PAGE_SIZE,+ cursor,+ // Flat: the overlay synthesizes folders from full paths, so it needs the whole bucket.+ with_delimiter: false,+ noncurrentVersions: 'include',+ deleteMarkers: 'include',+ },+ signal,+ })++ if (error) handleError(error)+ objects.push(...(data?.objects ?? []))++ if (!data?.hasNext || !data.nextCursor) break+ cursor = data.nextCursor+ isTruncated = page === MAX_PAGES - 1+ }++ if (isTruncated) objects = dropPartialTrailingPath(objects)++ return { objects: toArchivedObjects(objects), isTruncated }+}++export type ArchivedObjectsData = Awaited<ReturnType<typeof getArchivedObjects>>++export const archivedObjectsQueryOptions = ({ projectRef, bucketId }: ArchivedObjectsVariables) =>+ queryOptions({+ queryKey: storageKeys.archivedObjects(projectRef, bucketId),+ queryFn: ({ signal }) => getArchivedObjects({ projectRef, bucketId }, signal),+ enabled: IS_PLATFORM && typeof projectRef !== 'undefined' && typeof bucketId !== 'undefined',+ })diff --git a/knip.jsonc b/knip.jsoncindex ced31dc07a5..aedbe4db165 100644--- a/knip.jsonc+++ b/knip.jsonc@@ -77,6 +77,11 @@// alongside the rest of the Warehouse work so the values stay in one// place until the project-creation surface that consumes them lands."components/interfaces/ProjectCreation/WarehouseFdwCustomImage.constants.ts": ["files"],+ // Storage object versioning: the archived explorer rows are the first+ // consumer of these two, and that PR drops the entry.+ "data/storage/versioning/archived-object-{purge,restore}-mutation.ts": ["files"],+ // Consumed by the archived file preview pane, one PR further up.+ "data/storage/versioning/archived-object-version-delete-mutation.ts": ["files"],},// `vercel` is a globally installed CLI used by the `deploy:staging` script"ignoreBinaries": ["vercel"],