The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(storage): add object versions data layer (#49207)
Francesco Sansalvadore2d0bd7af690e
diff --git a/apps/studio/components/interfaces/Storage/BroomSparklesIcon.tsx b/apps/studio/components/interfaces/Storage/BroomSparklesIcon.tsxnew file mode 100644index 00000000000..820726f23e0--- /dev/null+++ b/apps/studio/components/interfaces/Storage/BroomSparklesIcon.tsx@@ -0,0 +1,40 @@+import { forwardRef, type SVGAttributes } from 'react'++interface BroomSparklesIconProps extends Omit<SVGAttributes<SVGSVGElement>, 'children'> {+ size?: number | string+}++/**+ * Inline copy of Lucide's `broom-sparkles`, which the pinned `lucide-react` predates.+ * Takes a `size` prop and strokes in `currentColor`, so it drops in like any Lucide icon.+ */+export const BroomSparklesIcon = forwardRef<SVGSVGElement, BroomSparklesIconProps>(+ ({ size = 16, className, ...props }, ref) => (+ <svg+ ref={ref}+ xmlns="http://www.w3.org/2000/svg"+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth={2}+ strokeLinecap="round"+ strokeLinejoin="round"+ className={className}+ {...props}+ >+ <path d="M11 2v2" />+ <path d="M12 3h-2" />+ <path d="M13.5 10.5 22 2" />+ <path d="M14.734 13.841a2 2 0 00-.314-2.42L12.58 9.58a2 2 0 00-2.421-.314l-7.657 4.461A1 1 0 002.3 15.3l6.403 6.403a1 1 0 001.571-.204z" />+ <path d="M20 15v4" />+ <path d="M22 17h-4" />+ <path d="M4 4v4" />+ <path d="m5 18 2-2" />+ <path d="M6 6H2" />+ <path d="m7.699 10.7 5.602 5.601" />+ </svg>+ )+)+BroomSparklesIcon.displayName = 'BroomSparklesIcon'diff --git a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.lifecycle.ts b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.lifecycle.tsindex 81707395739..c95d6e213d1 100644--- a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.lifecycle.ts+++ b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.lifecycle.ts@@ -11,7 +11,7 @@ export const COUNT_RULE_ID = 'supabase-noncurrent-count'* S3 honors `newer_noncurrent_versions` only alongside `noncurrent_days`, so "either* condition" becomes two rules, the second pinned at the shortest age the API accepts.*/-const MIN_NONCURRENT_DAYS = 1+export const MIN_NONCURRENT_DAYS = 1export interface LifecycleFormPolicy {versionExpiryDays: number | nulldiff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.test.tsnew file mode 100644index 00000000000..c8cef66e836--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.test.ts@@ -0,0 +1,135 @@+import { describe, expect, it } from 'vitest'++import { computeVersionFate } from './VersionHistory.utils'++describe('computeVersionFate', () => {+ it('returns retained when no policy is configured', () => {+ expect(+ computeVersionFate({+ daysOld: 90,+ chronoIndex: 0,+ noncurrentCount: 1,+ expiryDays: null,+ cap: null,+ mode: 'and',+ })+ ).toEqual({ type: 'retained' })+ })++ it('treats a zero bound as "condition not set" rather than "expire immediately"', () => {+ // Reading a 0 as an active bound would label every version as expiring.+ expect(+ computeVersionFate({+ daysOld: 90,+ chronoIndex: 0,+ noncurrentCount: 3,+ expiryDays: 0,+ cap: 0,+ mode: 'or',+ })+ ).toEqual({ type: 'retained' })+ })++ describe('age only', () => {+ const base = {+ chronoIndex: 0,+ noncurrentCount: 3,+ expiryDays: 30,+ cap: null,+ mode: 'and' as const,+ }++ it('gives every version a determined countdown', () => {+ expect(computeVersionFate({ ...base, daysOld: 3 })).toEqual({ type: 'expires-in', days: 27 })+ expect(computeVersionFate({ ...base, daysOld: 28 })).toEqual({ type: 'expires-in', days: 2 })+ })++ it('flips to expiry-due once the window has passed', () => {+ expect(computeVersionFate({ ...base, daysOld: 31 })).toEqual({ type: 'expiry-due' })+ })+ })++ it('ignores a cap that has no expiration age alongside it', () => {+ // Not a reachable policy: S3 requires NoncurrentDays on any expiration rule.+ const base = { expiryDays: null, cap: 3, mode: 'and' as const }++ expect(computeVersionFate({ ...base, daysOld: 3, chronoIndex: 2, noncurrentCount: 3 })).toEqual(+ {+ type: 'retained',+ }+ )++ expect(+ computeVersionFate({ ...base, daysOld: 216, chronoIndex: 0, noncurrentCount: 3 })+ ).toEqual({ type: 'retained' })+ })++ describe('both — AND', () => {+ const base = { expiryDays: 30, cap: 3, mode: 'and' as const }++ it('retains every version under the cap regardless of age', () => {+ expect(+ computeVersionFate({ ...base, daysOld: 45, chronoIndex: 1, noncurrentCount: 2 })+ ).toEqual({ type: 'retained' })+ expect(+ computeVersionFate({ ...base, daysOld: 70, chronoIndex: 0, noncurrentCount: 2 })+ ).toEqual({ type: 'retained' })+ })++ it('gives a countdown only once the cap is exceeded, since age is then the sole gate', () => {+ expect(+ computeVersionFate({ ...base, daysOld: 12, chronoIndex: 0, noncurrentCount: 4 })+ ).toEqual({ type: 'expires-in', days: 18 })+ })++ it('is expiry-due once both conditions are met', () => {+ expect(+ computeVersionFate({ ...base, daysOld: 34, chronoIndex: 0, noncurrentCount: 4 })+ ).toEqual({ type: 'expiry-due' })+ // Still within the cap: retained even though very old — AND needs both.+ expect(+ computeVersionFate({ ...base, daysOld: 28, chronoIndex: 1, noncurrentCount: 4 })+ ).toEqual({ type: 'retained' })+ })+ })++ describe('either — OR', () => {+ const base = { expiryDays: 30, cap: 3, mode: 'or' as const }++ it('lets age alone trigger removal, even well under the cap', () => {+ expect(+ computeVersionFate({ ...base, daysOld: 12, chronoIndex: 1, noncurrentCount: 2 })+ ).toEqual({ type: 'expires-in', days: 18 })+ expect(+ computeVersionFate({ ...base, daysOld: 34, chronoIndex: 0, noncurrentCount: 2 })+ ).toEqual({ type: 'expiry-due' })+ })++ it("lets the cap alone trigger removal, once past the cap rule's own day floor", () => {+ expect(+ computeVersionFate({ ...base, daysOld: 1, chronoIndex: 3, noncurrentCount: 4 })+ ).toEqual({ type: 'expires-in', days: 29 })+ expect(+ computeVersionFate({ ...base, daysOld: 3, chronoIndex: 2, noncurrentCount: 4 })+ ).toEqual({ type: 'expires-in', days: 27 })+ expect(+ computeVersionFate({ ...base, daysOld: 6, chronoIndex: 1, noncurrentCount: 4 })+ ).toEqual({ type: 'expires-on-next-upload', daysRemaining: 24 })+ expect(+ computeVersionFate({ ...base, daysOld: 9, chronoIndex: 0, noncurrentCount: 4 })+ ).toEqual({ type: 'expiry-due' })+ })++ it("waits out the cap rule's day floor before calling a version due", () => {+ // Beyond the cap but written today: the cap rule carries `noncurrent_days: 1`,+ // so nothing removes it until tomorrow.+ expect(+ computeVersionFate({ ...base, daysOld: 0, chronoIndex: 0, noncurrentCount: 5 })+ ).toEqual({ type: 'expires-in', days: 1 })++ expect(+ computeVersionFate({ ...base, daysOld: 1, chronoIndex: 0, noncurrentCount: 5 })+ ).toEqual({ type: 'expiry-due' })+ })+ })+})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.tsnew file mode 100644index 00000000000..3b9a599471f--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.ts@@ -0,0 +1,61 @@+import { MIN_NONCURRENT_DAYS } from '../FilesBuckets/BucketVersioningFields/BucketVersioningFields.lifecycle'+import type { ExpirationMode } from '../StorageVersioning.constants'++export type VersionFate =+ | { type: 'retained' }+ | { type: 'expires-in'; days: number }+ | { type: 'expires-on-next-upload'; daysRemaining: number }+ | { type: 'expiry-due' }++export interface ComputeVersionFateOptions {+ daysOld: number+ chronoIndex: number+ noncurrentCount: number+ expiryDays: number | null+ cap: number | null+ mode: ExpirationMode+}++const toActiveBound = (value: number | null) => (value !== null && value > 0 ? value : null)++/** A row gets a countdown only once every other condition is already satisfied. */+export const computeVersionFate = ({+ daysOld,+ chronoIndex,+ noncurrentCount,+ expiryDays,+ cap,+ mode,+}: ComputeVersionFateOptions): VersionFate => {+ const activeExpiryDays = toActiveBound(expiryDays)+ const activeCap = toActiveBound(cap)++ // S3 requires NoncurrentDays, so a cap with no age isn't expressible.+ if (activeExpiryDays === null) return { type: 'retained' }++ const isAgeExceeded = daysOld >= activeExpiryDays+ const daysRemaining = activeExpiryDays - daysOld++ if (activeCap === null) {+ return isAgeExceeded ? { type: 'expiry-due' } : { type: 'expires-in', days: daysRemaining }+ }++ const isCapExceeded = chronoIndex < noncurrentCount - activeCap+ const isAtCapBoundary = chronoIndex === noncurrentCount - activeCap++ if (mode === 'and') {+ if (!isCapExceeded) return { type: 'retained' }+ return isAgeExceeded ? { type: 'expiry-due' } : { type: 'expires-in', days: daysRemaining }+ }++ if (isAgeExceeded) return { type: 'expiry-due' }+ // The cap rule carries its own `noncurrent_days` floor, so exceeding the cap is not+ // enough on its own — the version has to be old enough for that rule to touch it.+ if (isCapExceeded) {+ return daysOld >= MIN_NONCURRENT_DAYS+ ? { type: 'expiry-due' }+ : { type: 'expires-in', days: MIN_NONCURRENT_DAYS - daysOld }+ }+ if (isAtCapBoundary) return { type: 'expires-on-next-upload', daysRemaining }+ return { type: 'expires-in', days: daysRemaining }+}diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/useFetchFileUrlQuery.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/useFetchFileUrlQuery.tsxindex 7304736dd5a..42ee7334534 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/useFetchFileUrlQuery.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/useFetchFileUrlQuery.tsx@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query'import { getPublicUrlForBucketObject } from '@/data/storage/bucket-object-get-public-url-mutation'import { signBucketObject } from '@/data/storage/bucket-object-sign-mutation'import { Bucket } from '@/data/storage/buckets-query'+import { storageKeys } from '@/data/storage/keys'import type { ResponseError, UseCustomQueryOptions } from '@/types'const DEFAULT_EXPIRY = 7 * 24 * 60 * 60 // in seconds, default to 1 week@@ -43,7 +44,12 @@ export const useFetchFileUrlQuery = ({ ...options }: UseCustomQueryOptions<string, ResponseError> = {}) => {return useQuery<string, ResponseError, string>({- queryKey: [projectRef, 'buckets', bucket.public, bucket.id, 'file', path],+ queryKey: storageKeys.fileUrl({+ projectRef,+ isBucketPublic: bucket.public,+ bucketId: bucket.id,+ path,+ }),queryFn: () => fetchFileUrl(path, projectRef, bucket.id, bucket.public, DEFAULT_EXPIRY),staleTime: DEFAULT_EXPIRY * 1000,...options,diff --git a/apps/studio/data/storage/keys.ts b/apps/studio/data/storage/keys.tsindex 4da7604208c..e7052aa12e6 100644--- a/apps/studio/data/storage/keys.ts+++ b/apps/studio/data/storage/keys.ts@@ -58,6 +58,45 @@ export const storageKeys = {['projects', projectRef, 'buckets', bucketId, 'folders'] as const,bucketLifecycle: (projectRef: string | undefined, bucketId: string | undefined) =>['projects', projectRef, 'buckets', bucketId, 'lifecycle'] as const,+ /** The policy is part of the key: the API derives each version's expiry from it. */+ objectVersions: (+ projectRef: string | undefined,+ bucketId: string | undefined,+ objectName: string | undefined,+ lifecyclePolicy?: { expiryDays: number | null; maxVersions: number | null }+ ) =>+ [+ 'projects',+ projectRef,+ 'buckets',+ bucketId,+ 'object-versions',+ objectName,+ ...(lifecyclePolicy ? [lifecyclePolicy] : []),+ ] as const,+ /** Omit `versionId` for a prefix that matches every version's URL for one object. */+ fileUrl: ({+ projectRef,+ isBucketPublic,+ bucketId,+ path,+ versionId,+ }: {+ projectRef?: string+ isBucketPublic?: boolean+ bucketId?: string+ path: string+ versionId?: string+ }) =>+ [+ projectRef,+ 'buckets',+ isBucketPublic,+ bucketId,+ 'file',+ path,+ ...(versionId === undefined ? [] : [versionId]),+ ] as const,icebergNamespaces: ({ projectRef, warehouse }: { projectRef?: string; warehouse?: string }) =>[projectRef, 'warehouse', warehouse, 'namespaces'] as const,icebergNamespace: ({diff --git a/apps/studio/data/storage/versioning/object-purge-mutation.ts b/apps/studio/data/storage/versioning/object-purge-mutation.tsnew file mode 100644index 00000000000..5da31817e68--- /dev/null+++ b/apps/studio/data/storage/versioning/object-purge-mutation.ts@@ -0,0 +1,89 @@+import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query'+import { toast } from 'sonner'++import { storageKeys } from '../keys'+import { objectVersionsQueryOptions } from './object-versions-query'+import { del, handleError } from '@/data/fetchers'+import type { ResponseError } from '@/types'++export type ObjectPurgeVariables = {+ projectRef: string+ bucketId: string+ /** The object's full path within the bucket, not just its leaf name. */+ path: string+}++/**+ * No single endpoint does this: a bare path only hides what is current, so the history+ * is read first and every version deleted by id, delete markers included.+ */+export const useObjectPurgeMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<UseMutationOptions<void, ResponseError, ObjectPurgeVariables>, 'mutationFn'> = {}) => {+ const queryClient = useQueryClient()++ const purgeObject = async ({ projectRef, bucketId, path }: ObjectPurgeVariables) => {+ if (!projectRef) throw new Error('projectRef is required')+ if (!bucketId) throw new Error('bucketId 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 (paths: ({ path: string; versionId: string } | string)[]) => {+ const { error } = await del('/platform/storage/{ref}/buckets/{id}/objects', {+ params: { path: { ref: projectRef, id: bucketId } },+ body: { paths },+ })++ if (error) handleError(error)+ }++ let versions = await listVersions()++ // A never-versioned bucket has no version ids, so the bare path is the only address.+ if (versions.length === 0) {+ await deleteVersions([path])+ return+ }++ // The list endpoint returns one capped page, so a longer history takes several rounds.+ // Deleting only the first would report a purge that left versions behind.+ while (versions.length > 0) {+ await deleteVersions(versions.map((version) => ({ path, versionId: version.versionId })))++ const remaining = await listVersions()+ // 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, ObjectPurgeVariables>({+ mutationFn: purgeObject,+ async onSuccess(data, variables, context) {+ // The object list lives in the explorer's state, not React Query.+ await queryClient.invalidateQueries({+ queryKey: storageKeys.objectVersions(+ variables.projectRef,+ variables.bucketId,+ variables.path+ ),+ })+ await onSuccess?.(data, variables, context)+ },+ async onError(error, variables, context) {+ if (onError === undefined) toast.error(`Failed to delete object: ${error.message}`)+ else onError(error, variables, context)+ },+ ...options,+ })+}diff --git a/apps/studio/data/storage/versioning/object-version-delete-mutation.ts b/apps/studio/data/storage/versioning/object-version-delete-mutation.tsnew file mode 100644index 00000000000..9b994040e6a--- /dev/null+++ b/apps/studio/data/storage/versioning/object-version-delete-mutation.ts@@ -0,0 +1,64 @@+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 ObjectVersionDeleteVariables = {+ projectRef: string+ bucketId: string+ /** The object's full path within the bucket, not just its leaf name. */+ path: string+ versionId: string+}++/** Addressing a version explicitly is a hard delete even on a versioned bucket. */+async function deleteObjectVersion({+ projectRef,+ bucketId,+ path,+ versionId,+}: ObjectVersionDeleteVariables) {+ if (!projectRef) throw new Error('projectRef is required')+ if (!bucketId) throw new Error('bucketId 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 useObjectVersionDeleteMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<void, ResponseError, ObjectVersionDeleteVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<void, ResponseError, ObjectVersionDeleteVariables>({+ mutationFn: deleteObjectVersion,+ async onSuccess(data, variables, context) {+ await queryClient.invalidateQueries({+ queryKey: storageKeys.objectVersions(+ variables.projectRef,+ variables.bucketId,+ variables.path+ ),+ })+ 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/object-version-restore-mutation.ts b/apps/studio/data/storage/versioning/object-version-restore-mutation.tsnew file mode 100644index 00000000000..5b999b6bb9c--- /dev/null+++ b/apps/studio/data/storage/versioning/object-version-restore-mutation.ts@@ -0,0 +1,64 @@+import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query'+import { toast } from 'sonner'++import { storageKeys } from '../keys'+import { handleError, post } from '@/data/fetchers'+import type { ResponseError } from '@/types'++export type ObjectVersionRestoreVariables = {+ projectRef: string+ bucketId: string+ /** The object's full path within the bucket, not just its leaf name. */+ path: string+ versionId: string+}++/** A move onto the object's own path: Storage consumes the source rather than copying it. */+async function restoreObjectVersion({+ projectRef,+ bucketId,+ path,+ versionId,+}: ObjectVersionRestoreVariables) {+ if (!projectRef) throw new Error('projectRef is required')+ if (!bucketId) throw new Error('bucketId is required')+ if (!path) throw new Error('path is required')+ if (!versionId) throw new Error('versionId is required')++ const { error } = await post('/platform/storage/{ref}/buckets/{id}/objects/move', {+ params: { path: { ref: projectRef, id: bucketId } },+ body: { from: path, to: path, sourceVersionId: versionId },+ })++ if (error) handleError(error)+}++export const useObjectVersionRestoreMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<void, ResponseError, ObjectVersionRestoreVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<void, ResponseError, ObjectVersionRestoreVariables>({+ mutationFn: restoreObjectVersion,+ async onSuccess(data, variables, context) {+ await queryClient.invalidateQueries({+ queryKey: storageKeys.objectVersions(+ variables.projectRef,+ variables.bucketId,+ variables.path+ ),+ })+ await onSuccess?.(data, variables, context)+ },+ async onError(error, variables, context) {+ if (onError === undefined) toast.error(`Failed to restore version: ${error.message}`)+ else onError(error, variables, context)+ },+ ...options,+ })+}diff --git a/apps/studio/data/storage/versioning/object-versions-query.test.ts b/apps/studio/data/storage/versioning/object-versions-query.test.tsnew file mode 100644index 00000000000..bf9571691b0--- /dev/null+++ b/apps/studio/data/storage/versioning/object-versions-query.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from 'vitest'++import { toObjectVersions } from './object-versions-query'++type StorageObject = Parameters<typeof toObjectVersions>[0][number]++const object = (overrides: Partial<StorageObject>): StorageObject => ({+ name: 'folder/photo.jpg',+ id: null,+ updated_at: null,+ created_at: null,+ last_accessed_at: null,+ metadata: { size: 100 },+ ...overrides,+})++describe('toObjectVersions', () => {+ it('returns newest first', () => {+ const versions = toObjectVersions([+ object({ version: 'old', created_at: '2026-01-01T00:00:00Z', archived_at: '2026-02-01' }),+ object({ version: 'new', created_at: '2026-03-01T00:00:00Z' }),+ object({ version: 'mid', created_at: '2026-02-01T00:00:00Z', archived_at: '2026-03-01' }),+ ])++ expect(versions.map((version) => version.versionId)).toEqual(['new', 'mid', 'old'])+ })++ it('treats a row with no archived_at as the current version', () => {+ const versions = toObjectVersions([+ object({ version: 'a', created_at: '2026-01-01T00:00:00Z' }),+ object({ version: 'b', created_at: '2026-02-01T00:00:00Z', archived_at: '2026-03-01' }),+ ])++ expect(versions.find((version) => version.versionId === 'a')?.isCurrent).toBe(true)+ expect(versions.find((version) => version.versionId === 'b')?.isCurrent).toBe(false)+ })++ it('labels the oldest upload and treats the rest as overwrites', () => {+ const versions = toObjectVersions([+ object({ version: 'a', created_at: '2026-01-01T00:00:00Z' }),+ object({ version: 'b', created_at: '2026-02-01T00:00:00Z' }),+ object({ version: 'c', created_at: '2026-03-01T00:00:00Z' }),+ ])++ expect(versions.map((version) => version.action)).toEqual([+ 'overwrite',+ 'overwrite',+ 'initial upload',+ ])+ })++ it('labels delete markers and does not count them as the initial upload', () => {+ const versions = toObjectVersions([+ object({ version: 'upload', created_at: '2026-01-01T00:00:00Z' }),+ object({+ version: 'marker',+ created_at: '2026-02-01T00:00:00Z',+ is_delete_marker: true,+ metadata: null,+ }),+ ])++ expect(versions.map((version) => version.action)).toEqual(['delete marker', 'initial upload'])+ })++ it('reads the size off the metadata, defaulting to zero', () => {+ const versions = toObjectVersions([+ object({ version: 'a', created_at: '2026-01-01T00:00:00Z', metadata: { size: 2048 } }),+ object({ version: 'b', created_at: '2026-02-01T00:00:00Z', metadata: null }),+ ])++ expect(versions.find((version) => version.versionId === 'a')?.size).toBe(2048)+ expect(versions.find((version) => version.versionId === 'b')?.size).toBe(0)+ })++ it('keeps each version its own mime type, since an overwrite can change it', () => {+ const versions = toObjectVersions([+ object({+ version: 'a',+ created_at: '2026-01-01T00:00:00Z',+ metadata: { mimetype: 'image/png' },+ }),+ object({ version: 'b', created_at: '2026-02-01T00:00:00Z', metadata: { size: 1 } }),+ ])++ expect(versions.find((version) => version.versionId === 'a')?.mimeType).toBe('image/png')+ expect(versions.find((version) => version.versionId === 'b')?.mimeType).toBeUndefined()+ })++ it('drops rows the API returned without a version id', () => {+ expect(toObjectVersions([object({ created_at: '2026-01-01T00:00:00Z' })])).toEqual([])+ })+})diff --git a/apps/studio/data/storage/versioning/object-versions-query.ts b/apps/studio/data/storage/versioning/object-versions-query.tsnew file mode 100644index 00000000000..b22b56aaf88--- /dev/null+++ b/apps/studio/data/storage/versioning/object-versions-query.ts@@ -0,0 +1,120 @@+import { queryOptions } from '@tanstack/react-query'+import { components } from 'api-types'++import { storageKeys } from '../keys'+import { handleError, post } from '@/data/fetchers'+import { IS_PLATFORM } from '@/lib/constants'+import type { ResponseError } from '@/types'++type StorageObject = components['schemas']['StorageObject_Output']++/**+ * A `delete marker` can outlive the delete, so a live file's history can contain them.+ * Restores read as overwrites: the list endpoint carries no provenance field.+ */+export type ObjectVersionAction = 'initial upload' | 'overwrite' | 'delete marker'++export interface ObjectVersion {+ versionId: string+ size: number+ /** An overwrite can change the type, so each version carries its own. */+ mimeType?: string+ createdAt: string+ isCurrent: boolean+ action: ObjectVersionAction+}++export interface LifecyclePolicy {+ /** `null` when no age condition is set. */+ expiryDays: number | null+ /** `null` when no version cap is set. */+ maxVersions: number | null+}++export type ObjectVersionsVariables = {+ projectRef?: string+ bucketId?: string+ /** The object's full path within the bucket, not just its leaf name. */+ path?: string+ lifecyclePolicy?: LifecyclePolicy+}++export type ObjectVersionsError = ResponseError++// The ceiling the list endpoint accepts.+const MAX_VERSIONS = 1000++/** Newest first. The oldest surviving row is labelled the initial upload; there is no flag for it. */+export const toObjectVersions = (objects: StorageObject[]): ObjectVersion[] => {+ const versions = objects+ .filter((object) => !!object.version)+ .map((object) => ({+ versionId: object.version as string,+ size: Number(object.metadata?.size ?? 0),+ // `metadata` is an untyped bag, so narrow rather than trust it.+ mimeType:+ typeof object.metadata?.mimetype === 'string' ? object.metadata.mimetype : undefined,+ createdAt: object.created_at ?? object.updated_at ?? '',+ isCurrent: !object.archived_at,+ isDeleteMarker: !!object.is_delete_marker,+ }))+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt))++ const oldestUploadIndex = versions.reduce(+ (oldest, version, index) => (version.isDeleteMarker ? oldest : index),+ -1+ )++ return versions.map(({ isDeleteMarker, ...version }, index) => {+ if (isDeleteMarker) return { ...version, action: 'delete marker' as const }+ return {+ ...version,+ action: index === oldestUploadIndex ? ('initial upload' as const) : ('overwrite' as const),+ }+ })+}++async function getObjectVersions(+ { projectRef, bucketId, path }: ObjectVersionsVariables,+ signal?: AbortSignal+) {+ if (!projectRef) throw new Error('projectRef is required')+ if (!bucketId) throw new Error('bucketId is required')+ if (!path) throw new Error('path is required')++ const { data, error } = await post('/platform/storage/{ref}/buckets/{id}/objects/list', {+ params: { path: { ref: projectRef, id: bucketId } },+ body: {+ path,+ options: {+ limit: MAX_VERSIONS,+ // Without `exactMatch` the path reads as a folder prefix, returning every sibling.+ exactMatch: true,+ noncurrentVersions: 'include',+ deleteMarkers: 'include',+ },+ },+ signal,+ })++ if (error) handleError(error)+ return toObjectVersions(data ?? [])+}++export type ObjectVersionsData = Awaited<ReturnType<typeof getObjectVersions>>++export const objectVersionsQueryOptions = ({+ projectRef,+ bucketId,+ path,+ lifecyclePolicy,+}: ObjectVersionsVariables) =>+ queryOptions({+ queryKey: storageKeys.objectVersions(projectRef, bucketId, path, lifecyclePolicy),+ queryFn: ({ signal }) => getObjectVersions({ projectRef, bucketId, path }, signal),+ enabled:+ IS_PLATFORM &&+ typeof projectRef !== 'undefined' &&+ typeof bucketId !== 'undefined' &&+ typeof path !== 'undefined',+ })diff --git a/knip.jsonc b/knip.jsoncindex 4d34cdb5830..fb2517a84b7 100644--- a/knip.jsonc+++ b/knip.jsonc@@ -82,6 +82,12 @@// 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 file preview panel that calls these+ // lands in the next PR of the stack, which drops both entries.+ "components/interfaces/Storage/BroomSparklesIcon.tsx": ["files"],+ "data/storage/versioning/object-{purge,version-delete,version-restore}-mutation.ts": [+ "files",+ ],},// `vercel` is a globally installed CLI used by the `deploy:staging` script"ignoreBinaries": ["vercel"],