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

supabase / storage / 30385224947

28 Jul 2026 05:57PM UTC coverage: 80.395% (+0.09%) from 80.307%
30385224947

Pull #1270

github

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

5665 of 7587 branches covered (74.67%)

Branch coverage included in aggregate %.

69 of 71 new or added lines in 3 files covered. (97.18%)

10799 of 12892 relevant lines covered (83.77%)

409.87 hits per line

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

93.22
/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
) {
16
  return json.$id || `def-${i}`
7!
17
}
18

19
const WILDCARD_PARAM = '*'
21✔
20
const WILDCARD_DOC_NAME = 'wildcard'
21✔
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 } {
34
  if (!url.split('/').includes(WILDCARD_PARAM)) {
88✔
35
    return { schema, url }
49✔
36
  }
37

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

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

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

57
  return { schema: { ...schema, params: renamedParams }, url: renamedUrl }
88✔
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 {
72
  const operation = (route.config as { operation?: string } | undefined)?.operation
104✔
73
  return (schema?.tags?.includes('s3') ?? false) && !operation
104✔
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 {
83
  const parts = operation.split('.').filter((part) => part !== 'storage')
214✔
84
  return parts
68✔
85
    .map((part) =>
86
      part
152✔
87
        .split('_')
88
        .filter(Boolean)
89
        .map((word, i) => (i === 0 ? word : word[0].toUpperCase() + word.slice(1)))
203✔
90
        .join('')
91
    )
92
    .map((part, i) => (i === 0 ? part : part[0].toUpperCase() + part.slice(1)))
152✔
93
    .join('')
94
}
95

96
const NON_STANDARD_ERROR_SHAPE_PATH_PREFIX = '/iceberg'
21✔
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 {
117
  if (url.startsWith(NON_STANDARD_ERROR_SHAPE_PATH_PREFIX)) {
88✔
118
    return schema ?? {}
1!
119
  }
120

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

126
  return {
40✔
127
    ...schema,
128
    response: {
129
      ...(response ? undefined : { 200: { description: 'Default Response' } }),
40!
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) means the
144
 * route needs its own `config.operationId` - several pre-existing route families (tus,
145
 * object) already reuse the same ROUTE_OPERATIONS constant across multiple registrations
146
 * (e.g. POST / and POST /*), so this can't hard-fail doc generation for the whole app over
147
 * a pre-existing duplicate it doesn't own. Warn and leave the colliding route without an
148
 * operationId instead - no worse than before this transform existed, and each occurrence
149
 * is a route family that should get its own config.operationId in a follow-up.
150
 * Returns a fresh transform bound to its own dedup state, so main/admin specs don't
151
 * leak collisions into each other when generated in the same process (see export-docs.ts).
152
 */
153
export function createOpenApiTransform() {
154
  const seenIds = new Set<string>()
11✔
155

156
  return function transformOpenApiSchema({
11✔
157
    schema,
158
    url,
159
    route,
160
  }: {
161
    schema: FastifySchema
162
    url: string
163
    route: RouteOptions
164
  }): { schema: FastifySchema; url: string } {
165
    if (isS3ProtocolCatchAll(schema, route)) {
104✔
166
      return { schema: { ...schema, hide: true }, url }
16✔
167
    }
168

169
    ;({ schema, url } = renameWildcardParam(schema, url))
88✔
170
    schema = defaultErrorResponse(schema, url)
88✔
171

172
    const baseId =
173
      route.config?.operationId ??
88✔
174
      (route.config?.operation && operationToId(route.config.operation))
175

176
    if (!baseId || (schema as { operationId?: string }).operationId) {
104✔
177
      return { schema, url }
19✔
178
    }
179

180
    const methods = Array.isArray(route.method) ? route.method : [route.method]
69!
181
    const isAutoHeadRoute = methods.length === 1 && methods[0] === 'HEAD'
104✔
182
    const operationId = isAutoHeadRoute ? `${baseId}Head` : baseId
104✔
183

184
    if (seenIds.has(operationId)) {
104✔
185
      console.warn(
12✔
186
        `[openapi] Duplicate operationId "${operationId}" for ${methods.join(',')} ${url} - ` +
187
          `leaving it undocumented. Give this route (or its ROUTE_OPERATIONS entry) a ` +
188
          `distinct config.operationId to fix.`
189
      )
190
      return { schema, url }
12✔
191
    }
192
    seenIds.add(operationId)
57✔
193

194
    return {
57✔
195
      schema: { ...schema, operationId },
196
      url,
197
    }
198
  }
199
}
200

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

214
  const { openapiObject } = documentObject
1✔
215
  const paths = openapiObject.paths as Record<string, Record<string, unknown>> | undefined
1✔
216
  if (!paths) {
1!
NEW
217
    return openapiObject
×
218
  }
219

220
  for (const url of Object.keys(paths)) {
1✔
221
    if (url === '/' || !url.endsWith('/')) {
31✔
222
      continue
26✔
223
    }
224

225
    const canonicalUrl = url.slice(0, -1)
5✔
226
    const canonicalPathItem = paths[canonicalUrl]
5✔
227
    if (!canonicalPathItem) {
5✔
228
      continue
3✔
229
    }
230

231
    for (const [method, operation] of Object.entries(paths[url])) {
2✔
232
      canonicalPathItem[method] ??= operation
5✔
233
    }
234
    delete paths[url]
2✔
235
  }
236

237
  return openapiObject
1✔
238
}
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