• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

supabase / storage / 30382005254

28 Jul 2026 05:14PM UTC coverage: 59.206% (-21.1%) from 80.307%
30382005254

Pull #1270

github

web-flow
Merge 66b88da12 into 20927735c
Pull Request #1270: fix(storage): document 200 responses for vector bucket CRUD endpoints

3676 of 7083 branches covered (51.9%)

Branch coverage included in aggregate %.

10 of 70 new or added lines in 3 files covered. (14.29%)

2445 existing lines in 105 files now uncovered.

7649 of 12045 relevant lines covered (63.5%)

363.74 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

3.42
/src/http/routes/openapi-transform.ts
1
import { SwaggerTransformObject } from '@fastify/swagger'
2
import { FastifySchema, RouteOptions } from 'fastify'
3

4
/**
5
 * @fastify/swagger names every de-duplicated component schema `def-0`, `def-1`, ... by
6
 * default, even for schemas registered with a meaningful `$id` (bucketSchema, errorSchema).
7
 * Use the `$id` as the component name instead, falling back to the default `def-N` for
8
 * anonymous schemas so unrelated inline schemas don't collide.
9
 */
10
export function nameSchemaByDollarId(
11
  json: { $id?: string },
12
  _baseUri: unknown,
13
  _fragment: unknown,
14
  i: number
15
) {
NEW
16
  return json.$id || `def-${i}`
×
17
}
18

19
const WILDCARD_PARAM = '*'
19✔
20
const WILDCARD_DOC_NAME = 'wildcard'
19✔
21

22
/**
23
 * Fastify's catch-all route segment is `*`, and its request params are keyed by the
24
 * literal `*` character (`request.params['*']`). @fastify/swagger mirrors that straight
25
 * into the OpenAPI doc as a path template `{*}` with a parameter named `*`, which isn't a
26
 * legal parameter/identifier name for any code generator. Rewrite it to a readable name for
27
 * docs only - the raw url string returned here still goes through Fastify's own `:name`
28
 * path-param formatting, and `route.schema` (the live validation schema) is never mutated.
29
 */
30
function renameWildcardParam(
31
  schema: FastifySchema,
32
  url: string
33
): { schema: FastifySchema; url: string } {
NEW
34
  if (!url.split('/').includes(WILDCARD_PARAM)) {
×
NEW
35
    return { schema, url }
×
36
  }
37

NEW
38
  const renamedUrl = url
×
39
    .split('/')
NEW
40
    .map((segment) => (segment === WILDCARD_PARAM ? `:${WILDCARD_DOC_NAME}` : segment))
×
41
    .join('/')
42

NEW
43
  const params = schema.params as
×
44
    | { properties?: Record<string, unknown>; required?: string[] }
45
    | undefined
NEW
46
  if (!params?.properties?.[WILDCARD_PARAM]) {
×
NEW
47
    return { schema, url: renamedUrl }
×
48
  }
49

NEW
50
  const { [WILDCARD_PARAM]: wildcardProperty, ...otherProperties } = params.properties
×
NEW
51
  const renamedParams = {
×
52
    ...params,
53
    properties: { ...otherProperties, [WILDCARD_DOC_NAME]: wildcardProperty },
NEW
54
    required: params.required?.map((name) => (name === WILDCARD_PARAM ? WILDCARD_DOC_NAME : name)),
×
55
  }
56

NEW
57
  return { schema: { ...schema, params: renamedParams }, url: renamedUrl }
×
58
}
59

60
/**
61
 * The S3-compatible surface dispatches ~18 real commands (PutObject, ListObjects,
62
 * CreateMultipartUpload, ...) from a handful of generic Fastify routes based on query
63
 * string/header matching done entirely inside the internal `s3/router.ts` Router - see
64
 * `s3/index.ts`. Fastify (and therefore @fastify/swagger) only ever sees the outer
65
 * catch-all route with no request/response schema, since OpenAPI has no way to express
66
 * "N distinct operations, same path and method, picked by a query parameter". Documenting
67
 * that catch-all as-is would give SDK generators a single method with an untyped body and
68
 * an untyped response for a request that's actually the whole S3 API - worse than nothing.
69
 * Hide it instead; the real per-command schemas remain the source of truth in s3/commands/*.
70
 */
71
function isS3ProtocolCatchAll(schema: FastifySchema | undefined, route: RouteOptions): boolean {
NEW
72
  const operation = (route.config as { operation?: string } | undefined)?.operation
×
NEW
73
  return (schema?.tags?.includes('s3') ?? false) && !operation
×
74
}
75

76
/**
77
 * Derives a stable, unique operationId from the route's `config.operation`
78
 * (see ROUTE_OPERATIONS in ./operations.ts), e.g. `storage.object.get_public` -> `objectGetPublic`.
79
 * Routes without a `config.operation` (protocol-level catch-alls like /s3 and /upload/resumable)
80
 * are left without an operationId.
81
 */
82
function operationToId(operation: string): string {
NEW
83
  const parts = operation.split('.').filter((part) => part !== 'storage')
×
NEW
84
  return parts
×
85
    .map((part) =>
NEW
86
      part
×
87
        .split('_')
88
        .filter(Boolean)
NEW
89
        .map((word, i) => (i === 0 ? word : word[0].toUpperCase() + word.slice(1)))
×
90
        .join('')
91
    )
NEW
92
    .map((part, i) => (i === 0 ? part : part[0].toUpperCase() + part.slice(1)))
×
93
    .join('')
94
}
95

96
const NON_STANDARD_ERROR_SHAPE_PATH_PREFIX = '/iceberg'
19✔
97

98
/**
99
 * Every route can end up hitting setErrorHandler and getting back a {statusCode, error,
100
 * message, code} body - default the doc to that shape for any otherwise-undocumented 4xx.
101
 * Doc-only on purpose: several handlers reply with an ad-hoc, partial error body directly
102
 * (`reply.status(400).send({message: '...'})`, bypassing the formatter entirely), and an
103
 * earlier version of this defaulted via a real onRoute hook that made Fastify enforce
104
 * errorSchema's `required` fields during response *serialization* - which threw on exactly
105
 * those ad-hoc replies (fast-json-stringify errors on a missing required property rather
106
 * than dropping it). A transform can't affect request handling, so it can't cause that.
107
 * Skipped entirely for the iceberg subtree: its `setErrorHandler` formatter
108
 * (src/http/routes/iceberg/index.ts) returns `{ error: { message, type, code } }`, not
109
 * errorSchema's flat `{statusCode, error, message, code}` - defaulting to errorSchema there
110
 * would document a shape iceberg never actually sends. Detected by path prefix rather than
111
 * `schema.tags`/`config.operation`, since some iceberg routes (src/http/routes/iceberg/bucket.ts)
112
 * reuse the same tag/operation constants as the unrelated storage-bucket routes. Leaves iceberg
113
 * 4xx responses undocumented for now - real documentation needs its own schema, tracked as
114
 * follow-up work alongside error-handler.ts's formatter-doc pairing.
115
 */
116
function defaultErrorResponse(schema: FastifySchema | undefined, url: string): FastifySchema {
NEW
117
  if (url.startsWith(NON_STANDARD_ERROR_SHAPE_PATH_PREFIX)) {
×
NEW
118
    return schema ?? {}
×
119
  }
120

NEW
121
  const response = schema?.response as Record<string, unknown> | undefined
×
NEW
122
  if (schema && response && Object.keys(response).some((status) => /^4xx$/i.test(status))) {
×
NEW
123
    return schema
×
124
  }
125

NEW
126
  return {
×
127
    ...schema,
128
    response: {
129
      ...(response ? undefined : { 200: { description: 'Default Response' } }),
×
130
      '4xx': { description: 'Error response', $ref: 'errorSchema#' },
131
      ...response,
132
    },
133
  }
134
}
135

136
/**
137
 * OpenAPI requires operationId to be unique across the whole document. A route can set
138
 * `config.operationId` to pin its id explicitly (takes precedence over the derived
139
 * `config.operation` id) - do this for any route whose id must stay stable regardless of
140
 * where it's registered, since generated SDK method names key off of it.
141
 * `exposeHeadRoutes` auto-derives a HEAD operation from every GET route re-using the same
142
 * `config.operation`/`config.operationId` - give that specific, deterministic case a `Head`
143
 * suffix. Any other collision (two distinct routes resolving to the same id) is a mistake,
144
 * not something to paper over with a registration-order-dependent suffix - it fails loudly
145
 * so it gets fixed via an explicit `config.operationId` instead.
146
 * Returns a fresh transform bound to its own dedup state, so main/admin specs don't
147
 * leak collisions into each other when generated in the same process (see export-docs.ts).
148
 */
149
export function createOpenApiTransform() {
NEW
150
  const seenIds = new Set<string>()
×
151

NEW
152
  return function transformOpenApiSchema({
×
153
    schema,
154
    url,
155
    route,
156
  }: {
157
    schema: FastifySchema
158
    url: string
159
    route: RouteOptions
160
  }): { schema: FastifySchema; url: string } {
NEW
161
    if (isS3ProtocolCatchAll(schema, route)) {
×
NEW
162
      return { schema: { ...schema, hide: true }, url }
×
163
    }
164

NEW
165
    ;({ schema, url } = renameWildcardParam(schema, url))
×
NEW
166
    schema = defaultErrorResponse(schema, url)
×
167

168
    const baseId =
NEW
169
      route.config?.operationId ??
×
170
      (route.config?.operation && operationToId(route.config.operation))
171

NEW
172
    if (!baseId || (schema as { operationId?: string }).operationId) {
×
NEW
173
      return { schema, url }
×
174
    }
175

NEW
176
    const methods = Array.isArray(route.method) ? route.method : [route.method]
×
NEW
177
    const isAutoHeadRoute = methods.length === 1 && methods[0] === 'HEAD'
×
NEW
178
    const operationId = isAutoHeadRoute ? `${baseId}Head` : baseId
×
179

NEW
180
    if (seenIds.has(operationId)) {
×
NEW
181
      throw new Error(
×
182
        `Duplicate OpenAPI operationId "${operationId}" for ${methods.join(',')} ${url} - ` +
183
          `give this route (or its ROUTE_OPERATIONS entry) a distinct config.operationId.`
184
      )
185
    }
NEW
186
    seenIds.add(operationId)
×
187

NEW
188
    return {
×
189
      schema: { ...schema, operationId },
190
      url,
191
    }
192
  }
193
}
194

195
/**
196
 * A handful of paths are reachable both with and without a trailing slash - either because
197
 * Fastify's own `exposeHeadRoutes` derives a HEAD route from the un-prefixed path (e.g.
198
 * /health vs /health/) or because a route is explicitly registered both ways (the S3
199
 * protocol surface). Both forms genuinely work at runtime, but documenting them as two
200
 * unrelated paths just doubles the number of operations a generated SDK has to deal with
201
 * for the same endpoint. Keep the slash-less form and fold the other one's methods into it.
202
 */
203
export const dedupeTrailingSlashPaths: SwaggerTransformObject = (documentObject) => {
19✔
NEW
204
  if (!('openapiObject' in documentObject)) {
×
NEW
205
    return documentObject.swaggerObject
×
206
  }
207

NEW
208
  const { openapiObject } = documentObject
×
NEW
209
  const paths = openapiObject.paths as Record<string, Record<string, unknown>> | undefined
×
NEW
210
  if (!paths) {
×
NEW
211
    return openapiObject
×
212
  }
213

NEW
214
  for (const url of Object.keys(paths)) {
×
NEW
215
    if (url === '/' || !url.endsWith('/')) {
×
NEW
216
      continue
×
217
    }
218

NEW
219
    const canonicalUrl = url.slice(0, -1)
×
NEW
220
    const canonicalPathItem = paths[canonicalUrl]
×
NEW
221
    if (!canonicalPathItem) {
×
NEW
222
      continue
×
223
    }
224

NEW
225
    for (const [method, operation] of Object.entries(paths[url])) {
×
NEW
226
      canonicalPathItem[method] ??= operation
×
227
    }
NEW
228
    delete paths[url]
×
229
  }
230

NEW
231
  return openapiObject
×
232
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc