Skip to content
← Public packages

@kody/openapi

Bind an OpenAPI spec and call selected operations with saved integration or secret names.

tests/openapi.test.ts

75 lines · 1.9 KB · TypeScript
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { parseOpenApiSpec } from '../src/parse-spec-lib.ts'
import { resolveOpenApiSelection } from '../src/selection.ts'
import { assertPinnedToApiBaseUrl, buildOperationUrl } from '../src/url.ts'

const spec = {
	openapi: '3.0.3',
	info: { title: 'Demo', version: '1' },
	paths: {
		'/ping': {
			get: {
				operationId: 'ping',
				tags: ['health'],
				responses: { '200': { description: 'ok' } },
			},
		},
		'/items/{id}': {
			delete: {
				operationId: 'delete_item',
				tags: ['items'],
				parameters: [
					{
						name: 'id',
						in: 'path',
						required: true,
						schema: { type: 'string' },
					},
				],
				responses: { '204': { description: 'gone' } },
			},
		},
	},
}

test('selection keeps GET and drops DELETE unless includeDestructive', () => {
	const parsed = parseOpenApiSpec(JSON.stringify(spec))
	const safe = resolveOpenApiSelection({
		operations: parsed.operations,
		selection: { tags: ['health', 'items'] },
		includeDestructive: false,
	})
	assert.deepEqual(
		safe.operations.map((operation) => operation.slug),
		['ping'],
	)

	const destructive = resolveOpenApiSelection({
		operations: parsed.operations,
		selection: { tags: ['items'] },
		includeDestructive: true,
	})
	assert.equal(destructive.operations[0]?.slug, 'delete_item')
})

test('operation URL stays pinned to the binding host', () => {
	const url = buildOperationUrl({
		apiBaseUrl: 'https://api.example.com/v1',
		path: '/items/{id}',
		params: { id: 'a b' },
		query: { limit: 2 },
	})
	assert.equal(url.toString(), 'https://api.example.com/v1/items/a%20b?limit=2')
	assertPinnedToApiBaseUrl(url, 'https://api.example.com/v1')
	assert.throws(
		() =>
			buildOperationUrl({
				apiBaseUrl: 'https://api.example.com',
				path: 'https://evil.example/x',
				params: {},
				query: {},
			}),
		/must be relative/,
	)
})