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

supabase / storage / 29833087191

21 Jul 2026 01:08PM UTC coverage: 79.882% (+0.004%) from 79.878%
29833087191

Pull #1215

github

web-flow
Merge f192ed10f into 6b7f85dbb
Pull Request #1215: fix: improve generated OpenAPI spec quality for SDK generation

5570 of 7534 branches covered (73.93%)

Branch coverage included in aggregate %.

80 of 82 new or added lines in 7 files covered. (97.56%)

18 existing lines in 2 files now uncovered.

10726 of 12866 relevant lines covered (83.37%)

437.49 hits per line

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

94.29
/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}`
5!
17
}
18

19
const WILDCARD_PARAM = '*'
36✔
20
const WILDCARD_DOC_NAME = 'wildcard'
36✔
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)) {
134✔
35
    return { schema, url }
94✔
36
  }
37

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

43
  const params = schema.params as
40✔
44
    | { properties?: Record<string, unknown>; required?: string[] }
45
    | undefined
46
  if (!params?.properties?.[WILDCARD_PARAM]) {
40✔
47
    return { schema, url: renamedUrl }
14✔
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 }
134✔
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
150✔
73
  return (schema?.tags?.includes('s3') ?? false) && !operation
150✔
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')
183✔
84
  return parts
59✔
85
    .map((part) =>
86
      part
130✔
87
        .split('_')
88
        .filter(Boolean)
89
        .map((word, i) => (i === 0 ? word : word[0].toUpperCase() + word.slice(1)))
176✔
90
        .join('')
91
    )
92
    .map((part, i) => (i === 0 ? part : part[0].toUpperCase() + part.slice(1)))
130✔
93
    .join('')
94
}
95

96
/**
97
 * Every route can end up hitting setErrorHandler and getting back a {statusCode, error,
98
 * message, code} body (or, for a subtree with its own formatter, whatever that subtree
99
 * documents instead) - default the doc to that shape for any otherwise-undocumented 4xx.
100
 * Doc-only on purpose: several handlers reply with an ad-hoc, partial error body directly
101
 * (`reply.status(400).send({message: '...'})`, bypassing the formatter entirely), and an
102
 * earlier version of this defaulted via a real onRoute hook that made Fastify enforce
103
 * errorSchema's `required` fields during response *serialization* - which threw on exactly
104
 * those ad-hoc replies (fast-json-stringify errors on a missing required property rather
105
 * than dropping it). A transform can't affect request handling, so it can't cause that.
106
 */
107
function defaultErrorResponse(schema: FastifySchema | undefined): FastifySchema {
108
  const response = schema?.response as Record<string, unknown> | undefined
134✔
109
  if (schema && response && Object.keys(response).some((status) => /^4xx$/i.test(status))) {
209✔
110
    return schema
42✔
111
  }
112

113
  return {
92✔
114
    ...schema,
115
    response: {
116
      ...(response ? undefined : { 200: { description: 'Default Response' } }),
92✔
117
      '4xx': { description: 'Error response', $ref: 'errorSchema#' },
118
      ...response,
119
    },
120
  }
121
}
122

123
/**
124
 * OpenAPI requires operationId to be unique across the whole document. `exposeHeadRoutes`
125
 * auto-derives a HEAD operation from every GET route re-using the same `config.operation`,
126
 * so the id needs a per-method suffix to stay unique when that happens.
127
 * Returns a fresh transform bound to its own dedup state, so main/admin specs don't
128
 * leak collisions into each other when generated in the same process (see export-docs.ts).
129
 */
130
export function createOpenApiTransform() {
131
  const seenIds = new Set<string>()
2✔
132

133
  return function transformOpenApiSchema({
2✔
134
    schema,
135
    url,
136
    route,
137
  }: {
138
    schema: FastifySchema
139
    url: string
140
    route: RouteOptions
141
  }): { schema: FastifySchema; url: string } {
142
    if (isS3ProtocolCatchAll(schema, route)) {
150✔
143
      return { schema: { ...schema, hide: true }, url }
16✔
144
    }
145

146
    ;({ schema, url } = renameWildcardParam(schema, url))
134✔
147
    schema = defaultErrorResponse(schema)
134✔
148

149
    const operation = (route.config as { operation?: string } | undefined)?.operation
134✔
150

151
    if (!operation || (schema as { operationId?: string }).operationId) {
150✔
152
      return { schema, url }
75✔
153
    }
154

155
    const baseId = operationToId(operation)
59✔
156
    let operationId = baseId
59✔
157
    if (seenIds.has(operationId)) {
59✔
158
      const method = Array.isArray(route.method) ? route.method[0] : route.method
19!
159
      operationId = baseId + method[0].toUpperCase() + method.slice(1).toLowerCase()
19✔
160
    }
161
    for (let suffix = 2; seenIds.has(operationId); suffix++) {
59✔
162
      operationId = baseId + suffix
2✔
163
    }
164
    seenIds.add(operationId)
59✔
165

166
    return {
59✔
167
      schema: { ...schema, operationId },
168
      url,
169
    }
170
  }
171
}
172

173
/**
174
 * A handful of paths are reachable both with and without a trailing slash - either because
175
 * Fastify's own `exposeHeadRoutes` derives a HEAD route from the un-prefixed path (e.g.
176
 * /health vs /health/) or because a route is explicitly registered both ways (the S3
177
 * protocol surface). Both forms genuinely work at runtime, but documenting them as two
178
 * unrelated paths just doubles the number of operations a generated SDK has to deal with
179
 * for the same endpoint. Keep the slash-less form and fold the other one's methods into it.
180
 */
181
export const dedupeTrailingSlashPaths: SwaggerTransformObject = (documentObject) => {
36✔
182
  if (!('openapiObject' in documentObject)) {
2!
NEW
183
    return documentObject.swaggerObject
×
184
  }
185

186
  const { openapiObject } = documentObject
2✔
187
  const paths = openapiObject.paths as Record<string, Record<string, unknown>> | undefined
2✔
188
  if (!paths) {
2!
NEW
189
    return openapiObject
×
190
  }
191

192
  for (const url of Object.keys(paths)) {
2✔
193
    if (url === '/' || !url.endsWith('/')) {
52✔
194
      continue
46✔
195
    }
196

197
    const canonicalUrl = url.slice(0, -1)
6✔
198
    const canonicalPathItem = paths[canonicalUrl]
6✔
199
    if (!canonicalPathItem) {
6✔
200
      continue
3✔
201
    }
202

203
    for (const [method, operation] of Object.entries(paths[url])) {
3✔
204
      canonicalPathItem[method] ??= operation
7✔
205
    }
206
    delete paths[url]
3✔
207
  }
208

209
  return openapiObject
2✔
210
}
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