or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# OpenAPI Sampler

1

2

OpenAPI Sampler is a tool for generating sample data based on OpenAPI payload and response schemas. It provides deterministic sample generation with comprehensive support for JSON Schema features including compound keywords (allOf, oneOf, anyOf, if/then/else), additionalProperties, array operations, string validation, number constraints, and various string formats. The library prioritizes using const, examples, enum, and default values where available, supports $ref resolving for complex schemas, and includes basic JSON Schema draft 7 compatibility.

3

4

## Package Information

5

6

- **Package Name**: openapi-sampler

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install openapi-sampler`

10

11

## Core Imports

12

13

ES Modules:

14

15

```javascript

16

import { sample, inferType, _registerSampler } from "openapi-sampler";

17

```

18

19

CommonJS:

20

21

```javascript

22

const { sample, inferType, _registerSampler } = require("openapi-sampler");

23

```

24

25

## Basic Usage

26

27

```javascript

28

import { sample } from "openapi-sampler";

29

30

// Simple schema sampling

31

const schema = {

32

type: "object",

33

properties: {

34

name: { type: "string", minLength: 5 },

35

age: { type: "integer", minimum: 18 },

36

email: { type: "string", format: "email" }

37

},

38

required: ["name", "age"]

39

};

40

41

const sampleData = sample(schema);

42

// Result: { name: "string", age: 18, email: "user@example.com" }

43

44

// With options

45

const options = {

46

skipNonRequired: true,

47

format: "json"

48

};

49

50

const sampleDataMinimal = sample(schema, options);

51

// Result: { name: "string", age: 18 }

52

53

// With $ref resolution

54

const spec = {

55

components: {

56

schemas: {

57

User: {

58

type: "object",

59

properties: {

60

id: { type: "string", format: "uuid" },

61

profile: { $ref: "#/components/schemas/Profile" }

62

}

63

},

64

Profile: {

65

type: "object",

66

properties: {

67

name: { type: "string" },

68

bio: { type: "string", maxLength: 100 }

69

}

70

}

71

}

72

}

73

};

74

75

const userSchema = { $ref: "#/components/schemas/User" };

76

const userData = sample(userSchema, {}, spec);

77

```

78

79

## Capabilities

80

81

### Sample Generation

82

83

Main function for generating sample data from JSON Schema or OpenAPI schemas.

84

85

```typescript { .api }

86

/**

87

* Generate sample data from a JSON Schema

88

* @param schema - JSON Schema object to generate sample from

89

* @param options - Optional configuration options

90

* @param document - Optional full OpenAPI specification for $ref resolution

91

* @returns Generated sample data (object, array, or primitive)

92

*/

93

function sample(schema: JSONSchema7, options?: Options, document?: object): unknown;

94

95

/**

96

* Register a custom sampler for a specific type

97

* @param type - The JSON Schema type to register a sampler for

98

* @param sampler - The sampler function to use for this type

99

*/

100

function _registerSampler(type: string, sampler: Function): void;

101

102

interface Options {

103

readonly skipNonRequired?: boolean; // Don't include non-required object properties not specified in required array

104

readonly skipReadOnly?: boolean; // Don't include readOnly object properties

105

readonly skipWriteOnly?: boolean; // Don't include writeOnly object properties

106

readonly quiet?: boolean; // Don't log console warning messages

107

readonly enablePatterns?: boolean; // Enable regex pattern sampling for strings

108

readonly format?: 'json' | 'xml'; // Output format (defaults to 'json')

109

}

110

111

type JSONSchema7 = import('@types/json-schema').JSONSchema7;

112

```

113

114

**Key Features:**

115

- Supports all JSON Schema types (object, array, string, number, integer, boolean)

116

- Handles compound schemas (allOf, oneOf, anyOf, if/then/else)

117

- Resolves $ref references when full spec is provided

118

- Prioritizes explicit values (const, examples, enum, default)

119

- Generates deterministic output for consistent testing

120

- Supports XML format output with proper element naming and attributes

121

122

**Usage Examples:**

123

124

```javascript

125

// Array schema

126

const arraySchema = {

127

type: "array",

128

items: { type: "string", format: "email" },

129

minItems: 2,

130

maxItems: 3

131

};

132

const emails = sample(arraySchema);

133

// Result: ["user@example.com", "user@example.com"]

134

135

// AllOf composition

136

const compositeSchema = {

137

allOf: [

138

{ type: "object", properties: { name: { type: "string" } } },

139

{ type: "object", properties: { age: { type: "integer" } } }

140

]

141

};

142

const person = sample(compositeSchema);

143

// Result: { name: "string", age: 0 }

144

145

// XML format

146

const xmlSchema = {

147

type: "object",

148

properties: {

149

name: { type: "string" },

150

items: {

151

type: "array",

152

items: { type: "string" },

153

xml: { wrapped: true }

154

}

155

},

156

xml: { name: "root" }

157

};

158

const xmlData = sample(xmlSchema, { format: "xml" });

159

// Result: XML string with proper element structure

160

```

161

162

### Type Inference

163

164

Utility function for inferring JSON Schema types from schema objects.

165

166

```typescript { .api }

167

/**

168

* Infer the type of a schema based on its properties and keywords

169

* @param schema - JSON Schema object to analyze

170

* @returns Inferred type (object, array, string, number, integer, boolean) or null

171

*/

172

function inferType(schema: object): string | null;

173

```

174

175

**Usage Examples:**

176

177

```javascript

178

import { inferType } from "openapi-sampler";

179

180

// Explicit type

181

inferType({ type: "string" }); // "string"

182

183

// Inferred from keywords

184

inferType({ properties: {} }); // "object"

185

inferType({ items: {} }); // "array"

186

inferType({ minLength: 5 }); // "string"

187

inferType({ minimum: 0 }); // "number"

188

189

// Array type (takes first)

190

inferType({ type: ["string", "null"] }); // "string"

191

192

// No inference possible

193

inferType({ description: "Some value" }); // null

194

```

195

196

### Custom Samplers

197

198

Register custom sampling functions for specific JSON Schema types.

199

200

```typescript { .api }

201

/**

202

* Register a custom sampler for a specific type

203

* @param type - The JSON Schema type to register a sampler for ('string', 'number', 'object', etc.)

204

* @param sampler - The sampler function that generates values for this type

205

*/

206

function _registerSampler(type: string, sampler: Function): void;

207

```

208

209

**Usage Examples:**

210

211

```typescript

212

import { _registerSampler } from "openapi-sampler";

213

214

// Register a custom string sampler

215

_registerSampler('string', (schema, options, spec, context) => {

216

if (schema.format === 'custom-id') {

217

return 'CUSTOM_' + Math.random().toString(36).substr(2, 9);

218

}

219

// Fallback to default behavior

220

return 'string';

221

});

222

223

// Now schemas with format: 'custom-id' will use the custom sampler

224

const result = sample({

225

type: 'string',

226

format: 'custom-id'

227

});

228

// Result: "CUSTOM_abc123def"

229

```

230

231

## Supported Schema Features

232

233

### String Formats

234

235

OpenAPI Sampler supports extensive string format validation and sample generation:

236

237

- **`email`**: Generates `user@example.com`

238

- **`idn-email`**: Generates internationalized email `пошта@укр.нет`

239

- **`password`**: Generates `pa$$word` (extended to meet minLength)

240

- **`date-time`**: Generates RFC 3339 datetime `2019-08-24T14:15:22.123Z`

241

- **`date`**: Generates date portion `2019-08-24`

242

- **`time`**: Generates time portion `14:15:22.123Z`

243

- **`ipv4`**: Generates `192.168.0.1`

244

- **`ipv6`**: Generates `2001:0db8:85a3:0000:0000:8a2e:0370:7334`

245

- **`hostname`**: Generates `example.com`

246

- **`idn-hostname`**: Generates internationalized hostname `приклад.укр`

247

- **`uri`**: Generates `http://example.com`

248

- **`uri-reference`**: Generates `../dictionary`

249

- **`uri-template`**: Generates `http://example.com/{endpoint}`

250

- **`iri`**: Generates `http://example.com/entity/1`

251

- **`iri-reference`**: Generates `/entity/1`

252

- **`uuid`**: Generates deterministic UUID based on property name

253

- **`json-pointer`**: Generates `/json/pointer`

254

- **`relative-json-pointer`**: Generates `1/relative/json/pointer`

255

- **`regex`**: Generates `/regex/`

256

257

### Number Constraints

258

259

- **`minimum`** / **`maximum`**: Numeric bounds

260

- **`exclusiveMinimum`** / **`exclusiveMaximum`**: Exclusive bounds

261

- **`multipleOf`**: Generates multiples of specified value

262

- **`format`**: Number formats

263

- `float`: Generates `0.1` instead of `0`

264

- `double`: Generates `0.1` instead of `0`

265

266

### Array Features

267

268

- **`items`**: Schema for array items (single schema or tuple)

269

- **`prefixItems`**: Tuple validation for positional items

270

- **`contains`**: Schema that at least one item must match

271

- **`minItems`** / **`maxItems`**: Array length constraints

272

- **`uniqueItems`**: Uniqueness constraint (informational)

273

274

### Object Features

275

276

- **`properties`**: Object property definitions

277

- **`required`**: Required property names

278

- **`additionalProperties`**: Schema for additional properties

279

- **`minProperties`** / **`maxProperties`**: Property count constraints

280

- **`patternProperties`**: Property name pattern matching

281

282

### Schema Composition

283

284

- **`allOf`**: Merge all schemas (deep merge for objects)

285

- **`oneOf`**: Use first schema (with parent property inheritance)

286

- **`anyOf`**: Use first schema (with parent property inheritance)

287

- **`if`** / **`then`** / **`else`**: Conditional schema application

288

289

### Reference Resolution

290

291

- **`$ref`**: JSON Pointer references within provided specification

292

- Circular reference detection and handling

293

- Caching for performance optimization

294

295

### XML Support

296

297

When `format: "xml"` option is used:

298

299

- **`xml.name`**: Element name override

300

- **`xml.prefix`**: Namespace prefix

301

- **`xml.namespace`**: XML namespace

302

- **`xml.attribute`**: Render as XML attribute

303

- **`xml.wrapped`**: Wrap arrays in container element

304

305

## Error Handling

306

307

The library handles various error conditions gracefully:

308

309

- **Missing $ref specification**: Throws error "Your schema contains $ref. You must provide full specification in the third parameter." when $ref is used without providing full spec

310

- **Circular references**: Automatically detects and returns appropriate empty values (empty object `{}` for object types, empty array `[]` for array types, `undefined` for other types)

311

- **Schema validation warnings**: Outputs warnings for inconsistent schemas (e.g., conflicting types in allOf) unless `quiet: true` option is set

312

- **Format validation**: Warns when minLength/maxLength constraints conflict with format requirements

313

- **Depth limiting**: Prevents infinite recursion with automatic depth limiting (default maximum depth: 15 levels)

314

- **XML format errors**: Throws error "Unknown format output for building XML." when XML conversion fails due to invalid input

315

316

**Example Error Handling:**

317

318

```typescript

319

try {

320

// This will throw an error because $ref is used without spec

321

const result = sample({ $ref: "#/components/schemas/User" });

322

} catch (error) {

323

console.error(error.message);

324

// "Your schema contains $ref. You must provide full specification in the third parameter."

325

}

326

327

// Circular reference handling

328

const circularSchema = {

329

type: 'object',

330

properties: {

331

self: { $ref: '#' } // Self-reference

332

}

333

};

334

335

const spec = { ...circularSchema };

336

const result = sample(circularSchema, {}, spec);

337

// Result: { self: {} } - circular reference resolved to empty object

338

```