or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-construction.mdexecution.mdhelpers.mdhttp-client.mdindex.mdrequest-building.mdresolution.md

helpers.mddocs/

0

# Helper Utilities and Spec Analysis

1

2

Utility functions for working with OpenAPI specifications, operations, and generating identifiers.

3

4

## Capabilities

5

6

### Spec Analysis Utilities

7

8

Utilities for analyzing and working with OpenAPI specifications.

9

10

```javascript { .api }

11

/**

12

* Iterate over all operations in a specification

13

* @param spec - OpenAPI specification object

14

* @param callback - Function called for each operation

15

* @param find - If true, stops iterating when callback returns truthy value

16

* @returns Operation object if find=true and match found, undefined otherwise

17

*/

18

function eachOperation(spec: object, callback: OperationCallback, find?: boolean): OperationInfo | undefined;

19

20

interface OperationCallback {

21

(operationInfo: OperationInfo): any;

22

}

23

24

interface OperationInfo {

25

/** Path name (e.g., "/users/{id}") */

26

pathName: string;

27

/** HTTP method (e.g., "get", "post") */

28

method: string;

29

/** Operation object from spec */

30

operation: OperationObject;

31

}

32

33

/**

34

* Find operation matching a predicate function

35

* @param spec - OpenAPI specification object

36

* @param predicate - Function to test each operation

37

* @returns First matching operation or undefined

38

*/

39

function findOperation(spec: object, predicate: OperationPredicate): OperationInfo | undefined;

40

41

interface OperationPredicate {

42

(operationInfo: OperationInfo): boolean;

43

}

44

45

/**

46

* Get raw operation object by operation ID

47

* @param spec - OpenAPI specification object

48

* @param operationId - Operation ID to find

49

* @returns Raw operation info or undefined

50

*/

51

function getOperationRaw(spec: object, operationId: string): OperationInfo | undefined;

52

```

53

54

**Usage Examples:**

55

56

```javascript

57

import { eachOperation, findOperation, getOperationRaw } from "swagger-client";

58

59

// Iterate over all operations

60

eachOperation(openApiSpec, ({ pathName, method, operation }) => {

61

console.log(`${method.toUpperCase()} ${pathName}: ${operation.operationId}`);

62

});

63

64

// Find operation by criteria

65

const operation = findOperation(openApiSpec, ({ operation }) => {

66

return operation.tags && operation.tags.includes("users");

67

});

68

69

// Get specific operation

70

const operation = getOperationRaw(openApiSpec, "getUserById");

71

if (operation) {

72

console.log(`Found operation: ${operation.method} ${operation.pathName}`);

73

}

74

75

// Count operations by tag

76

const tagCounts = {};

77

eachOperation(openApiSpec, ({ operation }) => {

78

const tags = operation.tags || ["untagged"];

79

tags.forEach(tag => {

80

tagCounts[tag] = (tagCounts[tag] || 0) + 1;

81

});

82

});

83

```

84

85

### Operation ID Generation

86

87

Generate operation IDs from operations and paths.

88

89

```javascript { .api }

90

/**

91

* Generate operation ID from operation details

92

* @param operation - Operation object

93

* @param pathName - Path name

94

* @param method - HTTP method

95

* @param options - Generation options

96

* @returns Generated operation ID

97

*/

98

function opId(

99

operation: OperationObject,

100

pathName: string,

101

method: string,

102

options?: OpIdOptions

103

): string;

104

105

interface OpIdOptions {

106

/** Use v2 compatibility mode */

107

v2OperationIdCompatibilityMode?: boolean;

108

}

109

110

/**

111

* Generate operation ID from path and method (current algorithm)

112

* @param pathName - Path name

113

* @param method - HTTP method

114

* @returns Generated operation ID

115

*/

116

function idFromPathMethod(pathName: string, method: string): string;

117

118

/**

119

* Generate operation ID from path and method (legacy algorithm)

120

* @param pathName - Path name

121

* @param method - HTTP method

122

* @returns Generated operation ID

123

*/

124

function idFromPathMethodLegacy(pathName: string, method: string): string;

125

```

126

127

**Usage Examples:**

128

129

```javascript

130

import { opId, idFromPathMethod, idFromPathMethodLegacy } from "swagger-client";

131

132

// Generate ID from operation (prefers existing operationId)

133

const operation = {

134

operationId: "createUser",

135

summary: "Create a new user"

136

};

137

const id = opId(operation, "/users", "post");

138

console.log(id); // "createUser"

139

140

// Generate ID when no operationId exists

141

const operation = {

142

summary: "Get user by ID"

143

};

144

const id = opId(operation, "/users/{id}", "get");

145

console.log(id); // "getUsersById" (generated)

146

147

// Generate ID from path and method

148

const id = idFromPathMethod("/users/{id}/posts", "get");

149

console.log(id); // "getUsersIdPosts"

150

151

// Legacy ID generation (for backward compatibility)

152

const id = idFromPathMethodLegacy("/api/v1/users/{userId}", "post");

153

console.log(id); // "postApiV1UsersUserId"

154

155

// V2 compatibility mode

156

const id = opId(operation, "/users/{id}", "get", {

157

v2OperationIdCompatibilityMode: true

158

});

159

```

160

161

### URL Validation

162

163

Validate and check URL formats.

164

165

```javascript { .api }

166

/**

167

* Check if string is a valid HTTP/HTTPS URL

168

* @param url - String to validate

169

* @returns Whether string is valid HTTP URL

170

*/

171

function isHttpUrl(url: string): boolean;

172

```

173

174

**Usage Examples:**

175

176

```javascript

177

import { isHttpUrl } from "swagger-client";

178

179

// Validate URLs

180

console.log(isHttpUrl("https://api.example.com")); // true

181

console.log(isHttpUrl("http://localhost:3000")); // true

182

console.log(isHttpUrl("ftp://files.example.com")); // false

183

console.log(isHttpUrl("not-a-url")); // false

184

console.log(isHttpUrl("//example.com")); // false

185

186

// Use in validation

187

function validateSpecUrl(spec) {

188

if (spec.host && !isHttpUrl(`https://${spec.host}`)) {

189

throw new Error("Invalid host in specification");

190

}

191

192

if (spec.servers) {

193

spec.servers.forEach(server => {

194

if (!isHttpUrl(server.url) && !server.url.startsWith("/")) {

195

throw new Error(`Invalid server URL: ${server.url}`);

196

}

197

});

198

}

199

}

200

```

201

202

### String Processing Utilities

203

204

Utilities for processing and normalizing strings.

205

206

```javascript { .api }

207

/**

208

* Replace special characters with underscores

209

* @param str - String to process

210

* @returns Processed string with underscores

211

*/

212

function replaceSpecialCharsWithUnderscore(str: string): string;

213

```

214

215

**Usage Examples:**

216

217

```javascript

218

import { replaceSpecialCharsWithUnderscore } from "swagger-client";

219

220

// String normalization for IDs

221

const operationId = replaceSpecialCharsWithUnderscore("get-user-by-id");

222

console.log(operationId); // "get_user_by_id"

223

224

const tagName = replaceSpecialCharsWithUnderscore("User Management");

225

console.log(tagName); // "User_Management"

226

227

// Use in ID generation

228

function normalizeOperationId(pathName, method) {

229

const rawId = `${method}${pathName}`;

230

return replaceSpecialCharsWithUnderscore(rawId);

231

}

232

```

233

234

### Interface Generation Utilities

235

236

Utilities for creating tag-based operation interfaces.

237

238

```javascript { .api }

239

/**

240

* Create bound execute function for operations

241

* @param swaggerClient - SwaggerClient instance

242

* @returns Execute function bound to client

243

*/

244

function makeExecute(swaggerClient: SwaggerClientInstance): ExecuteFunction;

245

246

interface ExecuteFunction {

247

(operationInfo: OperationExecuteInfo): ParameterizedExecuteFunction;

248

}

249

250

interface OperationExecuteInfo {

251

pathName: string;

252

method: string;

253

operationId: string;

254

}

255

256

interface ParameterizedExecuteFunction {

257

(parameters?: ParameterValues, options?: ExecutionOptions): Promise<ResponseObject>;

258

}

259

260

/**

261

* Map operations to tags for organization

262

* @param options - Mapping options

263

* @returns Tag-based operation mapping

264

*/

265

function mapTagOperations(options: MapTagOperationsOptions): TaggedOperations;

266

267

interface MapTagOperationsOptions {

268

spec: object;

269

cb?: OperationCallback;

270

defaultTag?: string;

271

v2OperationIdCompatibilityMode?: boolean;

272

}

273

274

interface TaggedOperations {

275

[tagName: string]: {

276

[operationId: string]: ParameterizedExecuteFunction;

277

};

278

}

279

```

280

281

**Usage Examples:**

282

283

```javascript

284

// Create tag-based interfaces

285

const tagOperations = mapTagOperations({

286

spec: openApiSpec,

287

cb: makeExecute(swaggerClient),

288

defaultTag: "default"

289

});

290

291

// Use generated interfaces

292

const userOps = tagOperations.users;

293

const response = await userOps.getUserById({ userId: "123" });

294

295

// Custom operation callback

296

const tagOperations = mapTagOperations({

297

spec: openApiSpec,

298

cb: ({ operationId, pathName, method }) => {

299

return async (params) => {

300

console.log(`Executing ${operationId}: ${method} ${pathName}`);

301

return execute({

302

spec: openApiSpec,

303

operationId,

304

parameters: params

305

});

306

};

307

}

308

});

309

```

310

311

## Common Types

312

313

```javascript { .api }

314

interface OperationObject {

315

operationId?: string;

316

tags?: string[];

317

summary?: string;

318

description?: string;

319

parameters?: ParameterObject[];

320

requestBody?: RequestBodyObject;

321

responses?: ResponsesObject;

322

security?: SecurityRequirement[];

323

}

324

325

interface OperationInfo {

326

pathName: string;

327

method: string;

328

operation: OperationObject;

329

}

330

331

interface OperationCallback {

332

(operationInfo: OperationInfo): any;

333

}

334

335

interface OperationPredicate {

336

(operationInfo: OperationInfo): boolean;

337

}

338

339

interface SwaggerClientInstance {

340

spec: object;

341

execute(options: ExecutionOptions): Promise<ResponseObject>;

342

}

343

344

interface ParameterValues {

345

[parameterName: string]: any;

346

}

347

348

interface ExecutionOptions {

349

operationId?: string;

350

pathName?: string;

351

method?: string;

352

parameters?: ParameterValues;

353

}

354

355

interface ResponseObject {

356

status: number;

357

statusText: string;

358

headers: Record<string, string>;

359

body: any;

360

text: string;

361

ok: boolean;

362

}

363

```