or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-cleaning.mdindex.mdschema-definition.mdschema-introspection.mdutility-functions.mdvalidation-context.mdvalidation.md

schema-definition.mddocs/

0

# Schema Definition

1

2

Core schema creation and manipulation functionality including field definitions, type constraints, and schema composition.

3

4

## Capabilities

5

6

### SimpleSchema Constructor

7

8

Creates a new SimpleSchema instance with field definitions and optional configuration.

9

10

```typescript { .api }

11

/**

12

* Creates a new SimpleSchema instance

13

* @param definition - Schema field definitions with optional shorthand syntax

14

* @param options - Optional configuration for the schema

15

*/

16

constructor(

17

definition: SchemaDefinitionWithShorthand,

18

options?: SimpleSchemaOptions

19

);

20

21

interface SimpleSchemaOptions {

22

/** Clean options to apply by default when cleaning objects */

23

clean?: CleanOptions;

24

/** Default label to use for fields that don't have a label */

25

defaultLabel?: string;

26

/** Function to get custom error messages for validation errors */

27

getErrorMessage?: GetErrorMessageFn;

28

/** Whether to automatically humanize field names for labels */

29

humanizeAutoLabels?: boolean;

30

/** Whether to keep the raw definition for debugging purposes */

31

keepRawDefinition?: boolean;

32

/** Whether fields are required by default (default: false) */

33

requiredByDefault?: boolean;

34

}

35

```

36

37

### Schema Field Definitions

38

39

Define schema fields using shorthand or longhand syntax with type constraints and validation rules.

40

41

```typescript { .api }

42

// Shorthand definition types

43

type SchemaDefinitionWithShorthand = Record<string, SchemaKeyDefinitionWithShorthand>;

44

type SchemaKeyDefinitionWithShorthand =

45

| StandardSchemaKeyDefinition

46

| SchemaKeyDefinitionWithOneType

47

| SupportedTypes

48

| RegExpConstructor

49

| SimpleSchemaGroup

50

| SupportedTypes[];

51

52

// Complete field definition interface

53

interface SchemaKeyDefinitionBase {

54

/** Function to automatically set field value */

55

autoValue?: AutoValueFunction;

56

/** Default value for the field */

57

defaultValue?: any;

58

/** Human-readable label for the field */

59

label?: string | ((this: FunctionOptionContext) => string);

60

/** Whether the field is optional */

61

optional?: boolean | (() => boolean);

62

/** Whether the field is required */

63

required?: boolean | (() => boolean);

64

65

// Type validation properties

66

/** Array or Set of allowed values */

67

allowedValues?: AllowedValues | (() => AllowedValues);

68

/** Whether to treat the field as a blackbox (skip validation of contents) */

69

blackbox?: boolean;

70

/** Custom validation function */

71

custom?: ValidatorFunction;

72

/** Whether max value is exclusive */

73

exclusiveMax?: boolean;

74

/** Whether min value is exclusive */

75

exclusiveMin?: boolean;

76

/** Maximum number of array items */

77

maxCount?: number;

78

/** Maximum value for numbers/dates or maximum length for strings */

79

max?: number | Date | (() => number | Date);

80

/** Minimum number of array items */

81

minCount?: number;

82

/** Minimum value for numbers/dates or minimum length for strings */

83

min?: number | Date | (() => number | Date);

84

/** Regular expression(s) for string validation */

85

regEx?: RegExp | RegExp[];

86

/** Skip regex validation for empty strings */

87

skipRegExCheckForEmptyStrings?: boolean;

88

/** Whether to trim string values during cleaning */

89

trim?: boolean;

90

}

91

92

interface SchemaKeyDefinitionWithOneType extends SchemaKeyDefinitionBase {

93

type: SupportedTypes;

94

}

95

```

96

97

**Usage Examples:**

98

99

```typescript

100

import SimpleSchema from "simpl-schema";

101

102

// Shorthand definitions

103

const shorthandSchema = new SimpleSchema({

104

name: String, // String type

105

age: Number, // Number type

106

isActive: Boolean, // Boolean type

107

tags: [String], // Array of strings

108

profile: Object // Object type

109

});

110

111

// Longhand definitions with constraints

112

const detailedSchema = new SimpleSchema({

113

name: {

114

type: String,

115

min: 1,

116

max: 100,

117

label: "Full Name",

118

trim: true

119

},

120

email: {

121

type: String,

122

regEx: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,

123

label: "Email Address"

124

},

125

age: {

126

type: SimpleSchema.Integer,

127

min: 0,

128

max: 120,

129

optional: true

130

},

131

tags: {

132

type: Array,

133

minCount: 0,

134

maxCount: 10

135

},

136

'tags.$': {

137

type: String,

138

min: 1,

139

max: 50

140

}

141

});

142

143

// Mixed shorthand and longhand

144

const mixedSchema = new SimpleSchema({

145

title: String, // Shorthand

146

description: { // Longhand

147

type: String,

148

max: 1000,

149

optional: true

150

},

151

priority: [String] // Shorthand array

152

});

153

```

154

155

### Supported Types

156

157

All JavaScript constructor types plus special SimpleSchema types.

158

159

```typescript { .api }

160

type SupportedTypes =

161

| ArrayConstructor // Array

162

| BooleanConstructor // Boolean

163

| DateConstructor // Date

164

| NumberConstructor // Number

165

| StringConstructor // String

166

| ObjectConstructor // Object

167

| '___Any___' // Any type (SimpleSchema.Any)

168

| typeof SimpleSchema.Integer // Integer numbers only

169

| SimpleSchema // Nested schema

170

| AnyClass // Any class constructor

171

| RegExp; // Regular expression

172

173

// Special type constants

174

static Any: '___Any___'; // Allows any type

175

static Integer: 'SimpleSchema.Integer'; // Integer numbers only

176

```

177

178

### Schema Extension

179

180

Extend existing schemas with additional fields or override existing field definitions.

181

182

```typescript { .api }

183

/**

184

* Creates a new schema by extending this schema with additional fields

185

* @param schema - Schema or definition to extend with

186

* @returns New SimpleSchema instance with combined definitions

187

*/

188

extend(schema: SimpleSchema | PartialSchemaDefinitionWithShorthand): SimpleSchema;

189

```

190

191

**Usage Examples:**

192

193

```typescript

194

const baseSchema = new SimpleSchema({

195

name: String,

196

email: String

197

});

198

199

const extendedSchema = baseSchema.extend({

200

age: Number,

201

phone: {

202

type: String,

203

optional: true

204

}

205

});

206

207

// Override existing fields

208

const modifiedSchema = baseSchema.extend({

209

email: {

210

type: String,

211

regEx: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,

212

label: "Email Address"

213

}

214

});

215

```

216

217

### Schema Cloning

218

219

Create an exact copy of a schema for modification without affecting the original.

220

221

```typescript { .api }

222

/**

223

* Creates a deep copy of the schema

224

* @returns New SimpleSchema instance with same definition

225

*/

226

clone(): SimpleSchema;

227

```

228

229

### Schema Filtering

230

231

Create new schemas with only specified fields or excluding specified fields.

232

233

```typescript { .api }

234

/**

235

* Creates a new schema with only the specified fields

236

* @param fields - Field names to include

237

* @returns New SimpleSchema with only specified fields

238

*/

239

pick(...fields: string[]): SimpleSchema;

240

241

/**

242

* Creates a new schema excluding the specified fields

243

* @param fields - Field names to exclude

244

* @returns New SimpleSchema without specified fields

245

*/

246

omit(...fields: string[]): SimpleSchema;

247

```

248

249

**Usage Examples:**

250

251

```typescript

252

const fullSchema = new SimpleSchema({

253

name: String,

254

email: String,

255

age: Number,

256

phone: String,

257

address: String

258

});

259

260

// Create schema with only specific fields

261

const contactSchema = fullSchema.pick('name', 'email', 'phone');

262

263

// Create schema excluding specific fields

264

const publicSchema = fullSchema.omit('age', 'address');

265

```

266

267

### Schema Groups and Union Types

268

269

Create union types that allow multiple type options for a single field.

270

271

```typescript { .api }

272

/**

273

* Creates a schema group representing a union of multiple types

274

* @param definitions - Array of type definitions to allow

275

* @returns SimpleSchemaGroup instance

276

*/

277

static oneOf(...definitions): SimpleSchemaGroup;

278

279

class SimpleSchemaGroup {

280

/** Array of type definitions in this group */

281

definitions: SchemaKeyDefinitionWithOneType[];

282

/** First type in the definitions (getter) */

283

singleType: SupportedTypes;

284

285

/** Creates a copy of the schema group */

286

clone(): SimpleSchemaGroup;

287

/** Extends this group with definitions from another group */

288

extend(otherGroup: SimpleSchemaGroup): void;

289

}

290

```

291

292

**Usage Examples:**

293

294

```typescript

295

const userSchema = new SimpleSchema({

296

name: String,

297

identifier: SimpleSchema.oneOf(String, Number), // Can be string or number

298

contact: SimpleSchema.oneOf(

299

{ type: String, regEx: SimpleSchema.RegEx.Email }, // Email

300

{ type: String, regEx: /^\+?[1-9]\d{1,14}$/ } // Phone

301

)

302

});

303

```

304

305

### Nested Schemas and Subschemas

306

307

Use SimpleSchema instances as types for nested object validation.

308

309

```typescript { .api }

310

// Use SimpleSchema instance as a type

311

const addressSchema = new SimpleSchema({

312

street: String,

313

city: String,

314

state: String,

315

zipCode: String

316

});

317

318

const userSchema = new SimpleSchema({

319

name: String,

320

address: addressSchema, // Nested schema

321

workAddress: { // Optional nested schema

322

type: addressSchema,

323

optional: true

324

}

325

});

326

```

327

328

### Function-Based Properties

329

330

Define dynamic field properties using functions for conditional validation.

331

332

```typescript { .api }

333

interface FunctionOptionContext {

334

key?: string | null;

335

[prop: string]: unknown;

336

}

337

338

// Properties that can be functions

339

interface DynamicProperties {

340

allowedValues?: AllowedValues | (() => AllowedValues);

341

exclusiveMax?: boolean | (() => boolean);

342

exclusiveMin?: boolean | (() => boolean);

343

label?: string | ((this: FunctionOptionContext) => string);

344

max?: number | Date | (() => number | Date);

345

maxCount?: number | (() => number);

346

min?: number | Date | (() => number | Date);

347

minCount?: number | (() => number);

348

optional?: boolean | (() => boolean);

349

regEx?: RegExp | RegExp[] | (() => RegExp | RegExp[]);

350

skipRegExCheckForEmptyStrings?: boolean | (() => boolean);

351

}

352

```

353

354

**Usage Examples:**

355

356

```typescript

357

const conditionalSchema = new SimpleSchema({

358

userType: {

359

type: String,

360

allowedValues: ['admin', 'user', 'guest']

361

},

362

permissions: {

363

type: Array,

364

minCount: function() {

365

return this.field('userType').value === 'admin' ? 1 : 0;

366

}

367

},

368

'permissions.$': String

369

});

370

```