Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 | 10x 10x 10x 10x 1x 1x 1x 1x 1x 1x 30x 6x 15x 15x 15x 12x 36x 36x 15x 14x 14x 14x 14x 9x 5x 5x 5x 5x 9x 8x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 21x 21x 21x 21x 21x 8x 8x 8x 8x 1x 4x 6x 15x 15x 14x 15x 14x 14x 16x 16x 2x 2x 2x 1x 1x 2x 2x 7x 5x 2x 1x 4x 4x 4x | /**
* @fds-uif/schema - Validation Utilities
*
* Provides AJV-based validation for UIF foundation and system definitions.
*
* @see RFC: https://github.com/salesforce-ux/design-system/rfcs/text/1150-uif-and-gen-components/uif-schema-spec.md
*/
import { Ajv, type ErrorObject } from 'ajv';
import type { UifFoundation } from './types/foundation.js';
import type { UifSystem } from './types/system.js';
import foundationSchema from './schemas/foundation.schema.json' with { type: 'json' };
import sharedSchema from './schemas/shared.schema.json' with { type: 'json' };
import systemSchema from './schemas/system.schema.json' with { type: 'json' };
// ============================================================================
// Constants
// ============================================================================
/**
* Canonical schema URLs as defined in the UIF RFC.
*
* These URLs serve as schema identifiers for validation and IDE support.
* Note: These URLs do not resolve to hosted endpoints (yet). For local development,
* VS Code workspace settings map UIF files to local schema files.
*/
export const SCHEMA_URLS = {
shared: 'https://slds.lightningdesignsystem.com/schemas/uif-shared.v1.json',
foundation: 'https://slds.lightningdesignsystem.com/schemas/uif-foundation.v1.json',
system: 'https://slds.lightningdesignsystem.com/schemas/uif-system.v1.json',
} as const;
/** JSON Schema validation keywords we handle specially */
const KEYWORD = {
ADDITIONAL_PROPERTIES: 'additionalProperties',
PATTERN: 'pattern',
REQUIRED: 'required',
TYPE: 'type',
} as const;
/** Regex to test if a string is a numeric array index */
const NUMERIC_INDEX_REGEX = /^\d+$/;
// ============================================================================
// Types
// ============================================================================
/**
* Validation result with typed errors.
*/
export interface ValidationResult<T> {
/** Whether the validation passed */
valid: boolean;
/** The validated data (only present if valid) */
data?: T;
/** Validation errors (only present if invalid) */
errors?: ValidationError[];
}
/**
* Structured validation error.
*/
export interface ValidationError {
/** JSON pointer to the error location */
path: string;
/** Human-readable error message */
message: string;
/** The JSON Schema keyword that failed */
keyword: string;
/** Additional parameters from the validation */
params?: Record<string, unknown>;
}
// ============================================================================
// AJV Instance Management
// ============================================================================
let ajvInstance: Ajv | null = null;
/**
* Create a configured AJV instance with all UIF schemas.
* Schemas are registered with their canonical URLs for proper $ref resolution.
*/
function createAjvInstance(): Ajv {
const ajv = new Ajv({
allErrors: true,
strict: false,
verbose: true,
});
// Register schemas in dependency order (shared first)
ajv.addSchema(sharedSchema, SCHEMA_URLS.shared);
ajv.addSchema(foundationSchema, SCHEMA_URLS.foundation);
ajv.addSchema(systemSchema, SCHEMA_URLS.system);
return ajv;
}
function getAjv(): Ajv {
if (!ajvInstance) {
ajvInstance = createAjvInstance();
}
return ajvInstance;
}
// ============================================================================
// Path Parsing & Formatting
// ============================================================================
interface ParsedPath {
/** Original JSON pointer (e.g., "/structure/children/0") */
raw: string;
/** Path segments without empty strings */
segments: string[];
/** Human-readable format (e.g., "structure > children[0]") */
friendly: string;
/** Last non-numeric segment (e.g., "children") */
locationName: string;
}
/**
* Parse a JSON pointer path into multiple useful formats.
* Computes all path representations in a single pass.
*/
function parsePath(path: string): ParsedPath {
if (!path || path === '/') {
return { raw: '/', segments: [], friendly: 'root', locationName: 'root' };
}
const segments = path.split('/').filter(Boolean);
const formatted: string[] = [];
let locationName = 'root';
for (const segment of segments) {
if (NUMERIC_INDEX_REGEX.test(segment)) {
// Numeric index - append to previous segment as [n]
if (formatted.length > 0) {
formatted[formatted.length - 1] += `[${segment}]`;
} else {
formatted.push(`[${segment}]`);
}
} else {
formatted.push(segment);
locationName = segment;
}
}
return {
raw: path,
segments,
friendly: formatted.join(' > '),
locationName,
};
}
// ============================================================================
// Value Formatting for Error Display
// ============================================================================
/**
* Format a value for display in error messages.
* Shows a readable preview without overwhelming detail.
*/
function formatFoundValue(value: unknown, maxLength = 80): string {
Iif (value === undefined) return 'undefined';
Iif (value === null) return 'null';
const formatted = formatValueByType(value);
return formatted.length > maxLength
? formatted.substring(0, maxLength - 3) + '...'
: formatted;
}
function formatValueByType(value: unknown): string {
if (typeof value === 'string') {
return `"${value}"`;
}
if (Array.isArray(value)) {
return formatArrayPreview(value);
}
if (typeof value === 'object' && value !== null) {
return formatObjectPreview(value as Record<string, unknown>);
}
return String(value);
}
function formatArrayPreview(arr: unknown[]): string {
if (arr.length === 0) return '[]';
const firstItem = JSON.stringify(arr[0]);
const itemCount = arr.length;
const itemWord = itemCount === 1 ? 'item' : 'items';
if (firstItem.length > 40) {
return `[{ ... }] (array with ${itemCount} ${itemWord})`;
}
return itemCount > 1
? `[${firstItem}, ... (${itemCount} items)]`
: `[${firstItem}]`;
}
function formatObjectPreview(obj: Record<string, unknown>): string {
const keys = Object.keys(obj);
Iif (keys.length === 0) return '{}';
if (keys.length <= 3) {
return `{ ${keys.map(k => `"${k}": ...`).join(', ')} }`;
}
return `{ "${keys[0]}": ..., "${keys[1]}": ..., ... (${keys.length} keys) }`;
}
// ============================================================================
// Error Message Enhancement
// ============================================================================
type ErrorParams = Record<string, unknown>;
/**
* Extract typed parameter from AJV error params.
*/
function getParam<T>(params: ErrorParams | undefined, key: string): T | undefined {
return params?.[key] as T | undefined;
}
/**
* Enhance an "additionalProperties" error with helpful context.
*/
function enhanceAdditionalPropertiesError(params: ErrorParams | undefined, locationName: string): string {
const prop = getParam<string>(params, 'additionalProperty');
if (!prop) return 'Unknown property';
if (prop === '$extends') {
return `Unknown property "$extends". Did you mean "extends" (without the $)?`;
}
if (prop === '$schema' && locationName !== 'root') {
return `"$schema" is only allowed at the root level, not inside "${locationName}"`;
}
return `Unknown property "${prop}"`;
}
/**
* Enhance a "pattern" error for identifier fields.
*/
function enhancePatternError(path: string, value: unknown): string | null {
const isIdentifierField =
path.endsWith('/name') &&
(path.includes('/modifiers/') || path.includes('/variants/') || path.includes('/states/'));
if (isIdentifierField) {
return `Invalid name "${value}". Use letters, numbers, underscores, or hyphens (e.g., "brand", "outline-brand")`;
}
if (path.endsWith('/state') && path.includes('/stateClasses/')) {
return `Invalid state name "${value}". Use letters, numbers, underscores, or hyphens`;
}
return null;
}
/**
* Enhance a "type" error with context-specific guidance.
*/
function enhanceTypeError(params: ErrorParams | undefined, data: unknown, locationName: string): string {
const expectedType = getParam<string>(params, 'type');
Iif (!expectedType) return 'Type mismatch';
const actualType = Array.isArray(data) ? 'array' : typeof data;
const article = expectedType === 'object' || expectedType === 'array' ? 'an' : 'a';
const baseMessage = `Expected ${article} ${expectedType}, but got ${actualType}`;
// Provide specific guidance for common mistakes
const guidance = getTypeErrorGuidance(expectedType, actualType, locationName);
return guidance || baseMessage;
}
/**
* Get specific Wrong/Right guidance for common type mismatches.
*/
function getTypeErrorGuidance(expectedType: string, actualType: string, locationName: string): string | null {
if (expectedType === 'object' && actualType === 'array') {
return getObjectExpectedGuidance(locationName);
}
if (expectedType === 'array' && actualType === 'object') {
return getArrayExpectedGuidance(locationName);
}
return null;
}
function getObjectExpectedGuidance(locationName: string): string | null {
const guidance: Record<string, string> = {
conditional: `"conditional" must be an object, not an array
Wrong: "conditional": [{ "attribute": "aria-current", ... }]
Right: "conditional": { "aria-current": { "when": "...", "value": "..." } }`,
bound: `"bound" must be an object, not an array
Wrong: "bound": [{ "attribute": "href", "prop": "href" }]
Right: "bound": { "href": { "prop": "href" } }`,
static: `"static" must be an object, not an array
Wrong: "static": [{ "class": "my-class" }]
Right: "static": { "class": "my-class" }`,
};
return guidance[locationName] || null;
}
function getArrayExpectedGuidance(locationName: string): string | null {
const arrayFields = ['children', 'states', 'modifiers', 'variants'];
if (arrayFields.includes(locationName)) {
return `"${locationName}" must be an array, not an object
Wrong: "${locationName}": { "name": "..." }
Right: "${locationName}": [{ "name": "..." }]`;
}
return null;
}
/**
* Convert AJV errors to structured ValidationError format with enhanced messages.
*/
function formatErrors(errors: ErrorObject[] | null | undefined): ValidationError[] {
Iif (!errors) return [];
return errors.map((error) => {
const parsed = parsePath(error.instancePath || '/');
const message = enhanceErrorMessage(error, parsed);
const finalMessage = buildFinalMessage(message, parsed, error.data);
return {
path: parsed.raw,
message: finalMessage,
keyword: error.keyword,
params: error.params as ErrorParams,
};
});
}
/**
* Enhance the error message based on the error keyword.
*/
function enhanceErrorMessage(error: ErrorObject, parsed: ParsedPath): string {
const defaultMessage = error.message || 'Unknown validation error';
switch (error.keyword) {
case KEYWORD.ADDITIONAL_PROPERTIES:
return enhanceAdditionalPropertiesError(error.params as ErrorParams, parsed.locationName);
case KEYWORD.PATTERN: {
const enhanced = enhancePatternError(parsed.raw, error.data);
return enhanced || defaultMessage;
}
case KEYWORD.REQUIRED: {
const prop = getParam<string>(error.params as ErrorParams, 'missingProperty');
return prop ? `Missing required property "${prop}"` : defaultMessage;
}
case KEYWORD.TYPE:
return enhanceTypeError(error.params as ErrorParams, error.data, parsed.locationName);
default:
return defaultMessage;
}
}
/**
* Build the final error message with path and found value context.
*/
function buildFinalMessage(message: string, parsed: ParsedPath, data: unknown): string {
if (parsed.raw === '/') {
return message;
}
let result = `${message}\n\n Path: ${parsed.friendly}`;
// Add "Found:" for errors without specific Wrong/Right guidance
const hasGuidance = message.includes('Wrong:') || message.includes('Right:');
if (!hasGuidance && data !== undefined) {
result += `\n Found: ${formatFoundValue(data)}`;
}
return result;
}
// ============================================================================
// Public Validation Functions
// ============================================================================
/**
* Validate a UIF foundation definition.
*
* @param data - The data to validate
* @returns Validation result with typed data or errors
*
* @example
* ```ts
* const result = validateFoundation(data);
* if (result.valid) {
* console.log(result.data.name);
* } else {
* console.error(result.errors);
* }
* ```
*/
export function validateFoundation(data: unknown): ValidationResult<UifFoundation> {
const validate = getAjv().getSchema(SCHEMA_URLS.foundation);
if (!validate) {
throw new Error('Foundation schema not found');
}
return validate(data)
? { valid: true, data: data as UifFoundation }
: { valid: false, errors: formatErrors(validate.errors) };
}
/**
* Validate a UIF system definition.
*
* @param data - The data to validate
* @returns Validation result with typed data or errors
*
* @example
* ```ts
* const result = validateSystem(data);
* if (result.valid) {
* console.log(result.data.extends);
* } else {
* console.error(result.errors);
* }
* ```
*/
export function validateSystem(data: unknown): ValidationResult<UifSystem> {
const validate = getAjv().getSchema(SCHEMA_URLS.system);
if (!validate) {
throw new Error('System schema not found');
}
return validate(data)
? { valid: true, data: data as UifSystem }
: { valid: false, errors: formatErrors(validate.errors) };
}
/**
* Validate a UIF file, auto-detecting whether it's a foundation or system.
*
* Detection is based on the presence of schema-specific properties:
* - Foundation: states, accessibility, behavior, composition, dateAdded, genReady
* - System: extends, styleApi, stateClasses
*
* @param data - The data to validate
* @returns Validation result with type indicator
*
* @example
* ```ts
* const result = validateUif(data);
* if (result.valid) {
* console.log(`Valid ${result.type} UIF`);
* }
* ```
*/
export function validateUif(
data: unknown,
): ValidationResult<UifFoundation | UifSystem> & { type?: 'foundation' | 'system' } {
if (typeof data !== 'object' || data === null) {
return {
valid: false,
errors: [{ path: '/', message: 'UIF must be an object', keyword: 'type', params: { type: 'object' } }],
};
}
const obj = data as Record<string, unknown>;
const detectedType = detectUifType(obj);
if (detectedType === 'foundation') {
return { ...validateFoundation(data), type: 'foundation' };
}
if (detectedType === 'system') {
return { ...validateSystem(data), type: 'system' };
}
// Ambiguous - try both and return first valid, or foundation errors
return validateAmbiguous(data);
}
type UifType = 'foundation' | 'system' | 'ambiguous';
/**
* Detect UIF type based on schema-specific properties.
*/
function detectUifType(obj: Record<string, unknown>): UifType {
const foundationOnlyProps = ['states', 'accessibility', 'behavior', 'composition', 'dateAdded', 'genReady'];
const systemOnlyProps = ['extends', '$extends', 'styleApi', 'stateClasses'];
const hasFoundationProps = foundationOnlyProps.some(prop => prop in obj);
const hasSystemProps = systemOnlyProps.some(prop => prop in obj);
if (hasFoundationProps && !hasSystemProps) return 'foundation';
Eif (hasSystemProps) return 'system';
return 'ambiguous';
}
/**
* Handle ambiguous UIF type by trying both validators.
*/
function validateAmbiguous(
data: unknown,
): ValidationResult<UifFoundation | UifSystem> & { type?: 'foundation' | 'system' } {
const foundationResult = validateFoundation(data);
if (foundationResult.valid) {
return { ...foundationResult, type: 'foundation' };
}
const systemResult = validateSystem(data);
if (systemResult.valid) {
return { ...systemResult, type: 'system' };
}
// Both failed - return foundation errors as default
return { ...foundationResult, type: 'foundation' };
}
// ============================================================================
// File Type Detection Utilities
// ============================================================================
/**
* Check if a file path appears to be a foundation UIF.
*/
export function isFoundationFile(filePath: string): boolean {
return filePath.endsWith('.foundation.uif.json');
}
/**
* Check if a file path appears to be a system UIF.
*/
export function isSystemFile(filePath: string): boolean {
const normalized = filePath.toLowerCase();
return normalized.endsWith('.uif.json') && !normalized.endsWith('.foundation.uif.json');
}
|