Repository navigation
Expand file tree
/
Copy pathgenerator.test.ts
More file actions
414 lines (389 loc) · 13.4 KB
/
Copy pathgenerator.test.ts
File metadata and controls
414 lines (389 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import { describe, expect, it } from 'vitest'
import { z } from 'zod'
import { defineRouteContract } from '../../apps/sim/lib/api/contracts/types'
import {
defineOpenApiDocument,
defineOpenApiRoute,
type OpenApiOperationMetadata,
type OpenApiRouteDefinition,
} from '../../apps/sim/lib/api/openapi/types'
import { generateOpenApiDocument } from './generator'
type JsonObject = Record<string, unknown>
type OpenApiDocument = Parameters<typeof generateOpenApiDocument>[0]
const generatedDocuments = new Map<OpenApiDocument, JsonObject>()
function _generatedDocument(document: OpenApiDocument): JsonObject {
const cached = generatedDocuments.get(document)
if (cached) return cached
const generated = generateOpenApiDocument(document)
generatedDocuments.set(document, generated)
return generated
}
const ERROR_SCHEMA = z
.object({
error: z
.object({
code: z.string().describe('Machine-readable error code.'),
message: z.string().describe('Human-readable error message.'),
})
.describe('Canonical error details.'),
})
.meta({
id: 'TestError',
title: 'Test error',
description: 'Canonical test error envelope.',
})
const LOCATION_HEADER_SCHEMA = z.string().meta({
id: 'LocationHeader',
title: 'Location',
description: 'Redirect target URL.',
})
function operation(
operationId: string,
success: OpenApiOperationMetadata['success']
): OpenApiOperationMetadata {
return {
operationId,
applicationOperation: { id: operationId },
summary: `Summary for ${operationId}`,
description: `Description for ${operationId}.`,
tags: ['Tests'],
errors: ['Unauthorized', 'RateLimited'],
success,
}
}
/** A minimal route, for assertions about document-level output rather than the route itself. */
function simpleRoute(): OpenApiRouteDefinition {
const response = z.object({ ok: z.boolean().describe('Whether the call succeeded.') }).meta({
id: 'SimpleResponse',
title: 'Simple response',
description: 'Response body.',
})
return defineOpenApiRoute(
defineRouteContract({
method: 'GET',
path: '/simple',
response: { mode: 'json', schema: response },
}),
operation('simple', { description: 'Simple.' }),
{ response }
)
}
function document(routes: readonly OpenApiRouteDefinition[]) {
return defineOpenApiDocument({
output: 'unused.json',
info: {
title: 'Generator test',
description: 'Generator test document.',
version: '1.0.0',
},
servers: [{ url: 'https://example.com', description: 'Test' }],
tags: [{ name: 'Tests', description: 'Generator test operations.' }],
security: [{ apiKey: [] }],
securitySchemes: {
apiKey: {
type: 'apiKey',
in: 'header',
name: 'X-API-Key',
description: 'Test API key.',
},
},
headers: { Location: { schema: LOCATION_HEADER_SCHEMA } },
errorSchema: ERROR_SCHEMA,
errorResponses: {
Unauthorized: {
status: 401,
description: 'Unauthorized.',
example: { error: { code: 'UNAUTHORIZED', message: 'API key required' } },
},
RateLimited: {
status: 429,
description: 'Rate limited.',
example: { error: { code: 'RATE_LIMITED', message: 'API rate limit exceeded' } },
},
/** Declared but referenced by no operation below, so it must not be published. */
NotFound: {
status: 404,
description: 'Not found.',
example: { error: { code: 'NOT_FOUND', message: 'Not found' } },
},
},
routes,
})
}
function getOperation(spec: JsonObject, path: string, method: string): JsonObject {
const paths = spec.paths as JsonObject
return (paths[path] as JsonObject)[method] as JsonObject
}
describe('OpenAPI generator', () => {
it('uses input schemas for requests and output schemas for responses', () => {
const params = z
.object({ id: z.string().describe('Resource identifier.') })
.meta({ id: 'TransformParams', title: 'Transform params', description: 'Path parameters.' })
const body = z
.object({
value: z
.string()
.transform((value) => value.length)
.describe('String input.'),
})
.meta({ id: 'TransformRequest', title: 'Transform request', description: 'Request body.' })
const response = z
.object({
value: z
.string()
.transform((value) => value.length)
.pipe(z.number())
.describe('Numeric output.'),
})
.meta({
id: 'TransformResponse',
title: 'Transform response',
description: 'Response body.',
deprecated: true,
})
const contract = defineRouteContract({
method: 'POST',
path: '/items/[id]',
params,
body,
response: { mode: 'json', schema: response, status: 201 },
})
const route = defineOpenApiRoute(
contract,
{ ...operation('transformItem', { description: 'Transformed item.' }), deprecated: true },
{ params, body, response }
)
const spec = generateOpenApiDocument(document([route]))
const schemas = (spec.components as JsonObject).schemas as JsonObject
const requestProperties = (schemas.TransformRequest as JsonObject).properties as JsonObject
const responseProperties = (schemas.TransformResponse as JsonObject).properties as JsonObject
expect((requestProperties.value as JsonObject).type).toBe('string')
expect((responseProperties.value as JsonObject).type).toBe('number')
expect(schemas.TransformResponse).toHaveProperty('deprecated', true)
expect(getOperation(spec, '/items/{id}', 'post')).toMatchObject({
deprecated: true,
responses: { '201': expect.any(Object) },
})
})
it('omits feature-flagged enum values from generated schemas', () => {
const columnType = z.enum(['string', 'ttl']).meta({ omitEnumValuesFromOpenApi: ['ttl'] })
const body = z
.object({ type: columnType.describe('Column data type.') })
.meta({ id: 'HiddenEnumRequest', title: 'Hidden enum request', description: 'Request body.' })
const response = z
.object({ ok: z.boolean().describe('Whether the request succeeded.') })
.meta({ id: 'HiddenEnumResponse', title: 'Hidden enum response', description: 'Response.' })
const contract = defineRouteContract({
method: 'POST',
path: '/hidden-enum',
body,
response: { mode: 'json', schema: response },
})
const route = defineOpenApiRoute(
contract,
operation('hiddenEnum', { description: 'Response.' }),
{ body, response }
)
const spec = generateOpenApiDocument(document([route]))
const schemas = (spec.components as JsonObject).schemas as JsonObject
const requestProperties = (schemas.HiddenEnumRequest as JsonObject).properties as JsonObject
const documentedColumnType = requestProperties.type as JsonObject
expect(columnType.safeParse('ttl').success).toBe(true)
expect(documentedColumnType.enum).toEqual(['string'])
expect(documentedColumnType).not.toHaveProperty('omitEnumValuesFromOpenApi')
})
it('handles every route response mode and media type', () => {
const emptyContract = defineRouteContract({
method: 'DELETE',
path: '/empty',
response: { mode: 'empty', status: 204 },
})
const textContract = defineRouteContract({
method: 'GET',
path: '/text',
response: { mode: 'text' },
})
const binaryContract = defineRouteContract({
method: 'GET',
path: '/binary',
response: { mode: 'binary' },
})
const streamContract = defineRouteContract({
method: 'GET',
path: '/stream',
response: { mode: 'stream' },
})
const redirectContract = defineRouteContract({
method: 'GET',
path: '/redirect',
response: { mode: 'redirect', status: 302 },
})
const spec = generateOpenApiDocument(
document([
defineOpenApiRoute(emptyContract, operation('empty', { description: 'No content.' }), {}),
defineOpenApiRoute(
textContract,
operation('text', { description: 'Text.', contentTypes: ['text/plain'] }),
{}
),
defineOpenApiRoute(
binaryContract,
operation('binary', {
description: 'Binary.',
contentTypes: ['application/pdf'],
}),
{}
),
defineOpenApiRoute(
streamContract,
operation('stream', {
description: 'Stream.',
contentTypes: ['text/event-stream'],
}),
{}
),
defineOpenApiRoute(
redirectContract,
operation('redirect', { description: 'Redirect.', headers: ['Location'] }),
{}
),
])
)
const emptyResponse = (getOperation(spec, '/empty', 'delete').responses as JsonObject)[
'204'
] as JsonObject
const textResponse = (getOperation(spec, '/text', 'get').responses as JsonObject)[
'200'
] as JsonObject
const binaryResponse = (getOperation(spec, '/binary', 'get').responses as JsonObject)[
'200'
] as JsonObject
const streamResponse = (getOperation(spec, '/stream', 'get').responses as JsonObject)[
'200'
] as JsonObject
const redirectResponse = (getOperation(spec, '/redirect', 'get').responses as JsonObject)[
'302'
] as JsonObject
expect(emptyResponse.content).toBeUndefined()
expect(textResponse.content).toHaveProperty('text/plain')
expect(binaryResponse.content).toHaveProperty('application/pdf')
expect(streamResponse.content).toHaveProperty('text/event-stream')
expect(redirectResponse.content).toBeUndefined()
expect(redirectResponse.headers).toHaveProperty('Location')
})
it('fails when status-specific metadata drifts from the contract', () => {
const response = z
.object({ ok: z.boolean().describe('Success state.') })
.meta({ id: 'DriftResponse', title: 'Drift response', description: 'Response.' })
const contract = defineRouteContract({
method: 'POST',
path: '/drift',
response: {
mode: 'json',
schema: response,
status: [200, 202],
statusSchemas: { 200: response, 202: response },
},
})
const route = defineOpenApiRoute(
contract,
operation('drift', {
byStatus: { 200: { description: 'Only one documented status.' } },
}),
{ response, responses: { 200: response, 202: response } }
)
expect(() => generateOpenApiDocument(document([route]))).toThrow(
'status-specific responses do not match the contract statuses'
)
})
it('rejects scopes for API key security requirements', () => {
const response = z
.object({ ok: z.boolean().describe('Success state.') })
.meta({ id: 'SecurityResponse', title: 'Security response', description: 'Response.' })
const contract = defineRouteContract({
method: 'GET',
path: '/security',
response: { mode: 'json', schema: response },
})
const route = defineOpenApiRoute(
contract,
{
...operation('security', { description: 'Response.' }),
security: [{ apiKey: ['read'] }],
},
{ response }
)
expect(() => generateOpenApiDocument(document([route]))).toThrow(
'apiKey security requirement must use an empty scope array'
)
})
it('rejects OAuth documentation without canonical scope policy', () => {
expect(() =>
generateOpenApiDocument({
...document([simpleRoute()]),
security: [{ oauthBearer: [] }],
securitySchemes: {
oauthBearer: {
type: 'oauth2',
description: 'OAuth.',
flows: {
authorizationCode: {
authorizationUrl: 'https://example.com/authorize',
tokenUrl: 'https://example.com/token',
scopes: { 'api:read': 'Read.' },
},
},
},
},
})
).toThrow("must declare its canonical application's OAuth scope")
})
it('validates response examples against transformed output schemas', () => {
const response = z
.object({
value: z
.string()
.transform((value) => value.length)
.pipe(z.number())
.describe('Transformed numeric value.'),
})
.meta({
id: 'OutputExampleResponse',
title: 'Output example response',
description: 'Transformed response.',
examples: [{ value: 'not-an-output-number' }],
})
const contract = defineRouteContract({
method: 'GET',
path: '/output-example',
response: { mode: 'json', schema: response },
})
const route = defineOpenApiRoute(
contract,
operation('outputExample', { description: 'Response.' }),
{ response }
)
expect(() => generateOpenApiDocument(document([route]))).toThrow(
'GET /output-example response at <root> example 1 is invalid for the output schema'
)
})
it('rejects an error example that does not fit the error schema', () => {
expect(() =>
generateOpenApiDocument({
...document([simpleRoute()]),
errorResponses: {
Unauthorized: {
status: 401,
description: 'Unauthorized.',
example: { error: { code: 'UNAUTHORIZED' } },
},
RateLimited: {
status: 429,
description: 'Rate limited.',
example: { error: { code: 'RATE_LIMITED', message: 'API rate limit exceeded' } },
},
},
})
).toThrow(/Unauthorized example/)
})
})