Option Handling and Validation
Relevant source files
The following files were used as context for generating this wiki page:The option handling and validation system is a core part of the avatar generation process. It is responsible for receiving user-defined options, ensuring their validity, merging them with a set of default configurations, and transforming them into a final, comprehensive options object that the rendering engine can use to create the SVG. This process ensures that the createAvatar function is both flexible for the user and robust against invalid or incomplete input.
The system is designed to be extensible, with a base set of options and style-specific options (like those for "Open Peeps") that are combined to provide a wide range of customization. Validation rules are applied early to fail fast on incorrect input, while selector functions translate high-level, user-friendly options (like emotion or gender) into specific component configurations required by the SVG generator.
Overall Flow
When a user calls createAvatar, the provided options go through a multi-step process of validation, building, and merging before the final SVG is rendered.
The diagram below illustrates the high-level data flow for option handling.
Input Validation
Before any processing occurs, the user-provided AvatarOptions are validated by the validateAvatarOptions function. This function performs several checks and throws an Error if any validation rule fails. This ensures that the subsequent processing steps can rely on a baseline of valid data.
Sources: packages/avatar/src/utils/validation.ts, packages/avatar/src/index.ts:14
Validation Rules
The following rules are enforced:
| Property | Rule | Error Message |
|---|---|---|
seed | Must be provided. | seed is required |
emotion | If provided, must be an integer between 1 and 10. | emotion must be between 1 and 10 |
gender | If provided, must be either "male" or "female". | gender must be either "male" or "female" |
Sources: packages/avatar/src/utils/validation.ts:4-14
Implementation
// packages/avatar/src/utils/validation.ts
export function validateAvatarOptions(options: AvatarOptions): void {
if (!options.seed) {
throw new Error('seed is required')
}
if (options.emotion && (options.emotion < 1 || options.emotion > 10)) {
throw new Error('emotion must be between 1 and 10')
}
if (options.gender && !['male', 'female'].includes(options.gender)) {
throw new Error('gender must be either "male" or "female"')
}
}
Sources: packages/avatar/src/utils/validation.ts:3-15
Option Building and Selection
After validation, the buildOptions function transforms the user-friendly AvatarOptions into a more detailed configuration object required by the core avatar generator. This involves using selector functions to map high-level concepts to specific values.
Sources: packages/avatar/src/index.ts:18-29, packages/avatar/src/utils/selectors.ts
AvatarOptions Type
The primary input from the user is the AvatarOptions object.
| Option | Type | Description |
|---|---|---|
seed | string | Required. A string used to seed the random number generator for deterministic output. |
gender | 'male' | 'female' | Optional. Determines the set of components available (e.g., head, facial hair). If not provided, a gender is chosen randomly. |
clothing | 'amber' | 'green' | 'blue' | 'teal' | 'pink' | 'violet' | Optional. Determines the color of the clothing. |
emotion | 1 to 10 | Optional. A number from 1 to 10 that maps to a specific face emotion. |
Sources: packages/avatar/src/types.ts:3-9
Selector Functions
Selector functions are responsible for translating the user's choices into concrete configuration values.
selectGenderConfig(gender): Returns the appropriate configuration object (MALE_CONFIGorFEMALE_CONFIG) based on the gender. If no gender is provided, it randomly selects one.selectFaceEmotion(emotion): Maps a numeric emotion value (1-10) to a specific face component name (e.g.,smile,angryWithFang). If the emotion is invalid or not provided, it returns a list of all possible emotions.selectClothingColor(clothing): Maps a clothing color name to its corresponding hex code.
Sources: packages/avatar/src/utils/selectors.ts:9-28
The sequence diagram below shows how createAvatar orchestrates validation and option building.
Option Merging and Defaults
The core of the configuration system is the merge function, which combines multiple layers of options into a single, final configuration object. This allows for a flexible system with global defaults, style-specific defaults, and user overrides.
The merging hierarchy is as follows (lower levels override higher ones):
- Core schema defaults (
packages/avatar/src/core/schema.ts) - Style schema defaults (
packages/avatar/src/open-peeps/schema.ts) - User-provided options
This process is handled within createBaseAvatar which calls merge.
Sources: packages/avatar/src/core/utils/options.ts:30-43, packages/avatar/src/core/index.ts:11
The diagram below shows the merging logic.
Schema Definitions
The default values are derived from JSON schemas. The open-peeps style defines a rich schema with numerous properties for avatar components.
For example, the schema defines the probability of certain features appearing and the list of available components.
| Property | Type | Default | Description |
|---|---|---|---|
accessoriesProbability | integer | 20 | The probability (0-100) that an accessory will be added. |
facialHairProbability | integer | 10 | The probability (0-100) that facial hair will be added. |
face | array | (list of 30 faces) | The list of possible face components. |
head | array | (list of 47 heads) | The list of possible head/hair components. |
skinColor | array | ['ffdbb4', 'edb98a', ...] | The list of possible skin colors. |
Sources: packages/avatar/src/open-peeps/schema.ts:5-169
A snippet from the schema shows how these defaults are defined:
// packages/avatar/src/open-peeps/schema.ts
{
// ...
"properties": {
"accessoriesProbability": {
"type": "integer",
"minimum": 0,
"maximum": 100,
"default": 20
},
"facialHair": {
"type": "array",
"items": {
"type": "string",
"enum": [
"chin",
"full",
// ...
]
},
"default": [
"chin",
"full",
// ...
]
},
// ...
}
}
Sources: packages/avatar/src/open-peeps/schema.ts:6-10, 81-103
Conclusion
The option handling and validation system is a critical architectural component that provides a clean separation between the user-facing API and the internal rendering logic. Through a clear pipeline of validation, selection, and merging, it robustly processes user input, applies sensible defaults from schemas, and constructs a complete configuration. This layered approach ensures that the avatar generation is both highly customizable and resilient to error, forming the foundation of the library's flexibility.