or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

analysis-metrics.mdapi-definition-reduction.mdextensions-customization.mdindex.mdopenapi-definition-management.mdoperation-discovery-analysis.mdparameter-handling-json-schema.mdrequest-response-management.mdschema-dereferencing-references.mdsecurity-authentication.mdserver-url-management.mdutils.md

openapi-definition-management.mddocs/

0

# OpenAPI Definition Management

1

2

Core functionality for loading, parsing, and accessing OpenAPI definitions with full OpenAPI 3.0/3.1 support.

3

4

## Capabilities

5

6

### Oas Constructor

7

8

Initialize an Oas instance with an OpenAPI definition and optional user context.

9

10

```typescript { .api }

11

/**

12

* Create a new Oas instance

13

* @param oas - OpenAPI definition as object or JSON string

14

* @param user - Optional user information for auth token extraction

15

*/

16

constructor(oas: OASDocument | string, user?: User);

17

```

18

19

**Usage Examples:**

20

21

```typescript

22

import Oas from "oas";

23

24

// From object

25

const oas = new Oas({

26

openapi: "3.1.0",

27

info: { title: "My API", version: "1.0.0" },

28

paths: {}

29

});

30

31

// From JSON string

32

const oasFromString = new Oas('{"openapi":"3.1.0","info":{"title":"API","version":"1.0.0"},"paths":{}}');

33

34

// With user context

35

const oasWithUser = new Oas(definition, {

36

apiKey: "secret-key",

37

keys: [{ name: "my-app", user: "user123", pass: "pass456" }]

38

});

39

```

40

41

### Static Initialization

42

43

Force-type a JSON object to an OpenAPI definition for TypeScript compatibility.

44

45

```typescript { .api }

46

/**

47

* Initialize a new Oas instance with type forcing

48

* @param oas - OpenAPI definition or untyped JSON object

49

* @param user - Optional user information for auth token extraction

50

* @returns New Oas instance

51

*/

52

static init(oas: OASDocument | Record<string, unknown>, user?: User): Oas;

53

```

54

55

**Usage Examples:**

56

57

```typescript

58

// Type-force an untyped object

59

const untypedApi = JSON.parse(apiJsonString);

60

const oas = Oas.init(untypedApi);

61

62

// With user context

63

const oasWithUser = Oas.init(untypedApi, { apiKey: "secret" });

64

```

65

66

### Get OpenAPI Version

67

68

Retrieve the OpenAPI specification version of the current definition.

69

70

```typescript { .api }

71

/**

72

* Get the OpenAPI version string from the definition

73

* @returns OpenAPI version (e.g., "3.0.3", "3.1.0")

74

* @throws Error if version cannot be determined

75

*/

76

getVersion(): string;

77

```

78

79

**Usage Examples:**

80

81

```typescript

82

const version = oas.getVersion(); // "3.1.0"

83

84

// Handle version-specific logic

85

if (version.startsWith("3.1")) {

86

// OpenAPI 3.1 specific features

87

console.log("Supports webhooks and JSON Schema draft 2020-12");

88

}

89

```

90

91

### Check Operation ID Existence

92

93

Statically check if an operation object has an operationId defined.

94

95

```typescript { .api }

96

/**

97

* Check if an operation object has an operationId

98

* @param schema - Operation object to check

99

* @returns True if operationId is defined and non-empty

100

*/

101

static hasOperationId(schema: OperationObject): boolean;

102

```

103

104

**Usage Examples:**

105

106

```typescript

107

const operationSchema = {

108

summary: "Get user",

109

operationId: "getUser",

110

responses: { "200": { description: "Success" } }

111

};

112

113

const hasId = Oas.hasOperationId(operationSchema); // true

114

115

const operationWithoutId = {

116

summary: "List users",

117

responses: { "200": { description: "Success" } }

118

};

119

120

const hasId2 = Oas.hasOperationId(operationWithoutId); // false

121

```

122

123

### Generate Operation ID

124

125

Statically generate an operationId for an operation based on path and method.

126

127

```typescript { .api }

128

/**

129

* Generate an operationId for an operation

130

* @param path - API path (e.g., "/users/{id}")

131

* @param method - HTTP method

132

* @param schema - Operation object

133

* @param opts - Generation options

134

* @returns Generated operationId string

135

*/

136

static getOperationId(

137

path: string,

138

method: string,

139

schema: OperationObject,

140

opts?: OperationIDGeneratorOptions

141

): string;

142

```

143

144

**Usage Examples:**

145

146

```typescript

147

const operationSchema = {

148

summary: "Get user by ID",

149

responses: { "200": { description: "User found" } }

150

};

151

152

// Generate camelCase operationId

153

const operationId = Oas.getOperationId("/users/{id}", "get", operationSchema, {

154

camelCase: true

155

}); // "getUsersById"

156

157

// Use existing operationId if present

158

const schemaWithId = {

159

operationId: "fetchUser",

160

responses: { "200": { description: "Success" } }

161

};

162

163

const existingId = Oas.getOperationId("/users/{id}", "get", schemaWithId, {

164

onlyUseExistingOperationIds: true

165

}); // "fetchUser"

166

```

167

168

### Get Definition

169

170

Retrieve the complete OpenAPI definition object.

171

172

```typescript { .api }

173

/**

174

* Get the current OpenAPI definition

175

* @returns Complete OpenAPI definition object

176

*/

177

getDefinition(): OASDocument;

178

```

179

180

**Usage Examples:**

181

182

```typescript

183

const definition = oas.getDefinition();

184

185

// Access definition properties

186

console.log(definition.info.title);

187

console.log(definition.servers?.[0]?.url);

188

console.log(Object.keys(definition.paths));

189

190

// Serialize back to JSON

191

const jsonString = JSON.stringify(definition, null, 2);

192

```

193

194

### Get All Paths

195

196

Get all paths in the API definition as Operation instances for easy manipulation.

197

198

```typescript { .api }

199

/**

200

* Get all paths with their operations as Operation instances

201

* @returns Record of paths to HTTP methods to Operation instances

202

*/

203

getPaths(): Record<string, Record<HttpMethods, Operation | Webhook>>;

204

```

205

206

**Usage Examples:**

207

208

```typescript

209

const paths = oas.getPaths();

210

211

// Iterate through all operations

212

Object.entries(paths).forEach(([path, operations]) => {

213

Object.entries(operations).forEach(([method, operation]) => {

214

console.log(`${method.toUpperCase()} ${path}: ${operation.getSummary()}`);

215

});

216

});

217

218

// Find all GET operations

219

const getOperations = Object.entries(paths)

220

.flatMap(([path, ops]) =>

221

Object.entries(ops)

222

.filter(([method]) => method === "get")

223

.map(([, operation]) => ({ path, operation }))

224

);

225

```

226

227

### Get All Webhooks

228

229

Get all webhooks (OpenAPI 3.1 only) as Webhook instances.

230

231

```typescript { .api }

232

/**

233

* Get all webhooks as Webhook instances (OpenAPI 3.1 only)

234

* @returns Record of webhook IDs to HTTP methods to Webhook instances

235

*/

236

getWebhooks(): Record<string, Record<HttpMethods, Webhook>>;

237

```

238

239

**Usage Examples:**

240

241

```typescript

242

const webhooks = oas.getWebhooks();

243

244

// Process all webhooks

245

Object.entries(webhooks).forEach(([webhookId, methods]) => {

246

Object.entries(methods).forEach(([method, webhook]) => {

247

console.log(`Webhook ${webhookId} ${method}: ${webhook.getSummary()}`);

248

});

249

});

250

```

251

252

### Get All Tags

253

254

Get all tag names from the API definition with optional path fallback.

255

256

```typescript { .api }

257

/**

258

* Get all tag names that exist in the API definition

259

* @param setIfMissing - If true, adds path names for operations without tags

260

* @returns Array of tag names, sorted by definition order

261

*/

262

getTags(setIfMissing?: boolean): string[];

263

```

264

265

**Usage Examples:**

266

267

```typescript

268

// Get defined tags only

269

const tags = oas.getTags(); // ["users", "orders", "products"]

270

271

// Include paths for untagged operations

272

const allTags = oas.getTags(true); // ["users", "orders", "/health", "/metrics"]

273

274

// Group operations by tag

275

const operationsByTag = tags.reduce((acc, tag) => {

276

acc[tag] = Object.values(oas.getPaths())

277

.flatMap(ops => Object.values(ops))

278

.filter(op => op.getTags().some(t => t.name === tag));

279

return acc;

280

}, {} as Record<string, Operation[]>);

281

```

282

283

## Error Handling

284

285

The Oas constructor and methods handle various error conditions:

286

287

- **Invalid JSON**: Constructor throws for malformed JSON strings

288

- **Missing Version**: `getVersion()` throws if `openapi` field is missing or invalid

289

- **Empty Definitions**: Methods gracefully handle empty or minimal definitions

290

- **Invalid References**: Dereferencing handles broken `$ref` pointers

291

292

```typescript

293

try {

294

const oas = new Oas(invalidJsonString);

295

} catch (error) {

296

console.error("Invalid OpenAPI definition:", error.message);

297

}

298

299

try {

300

const version = oas.getVersion();

301

} catch (error) {

302

console.error("Cannot determine OpenAPI version:", error.message);

303

}

304

```