formedible-parser

Advanced Form Parser

A sophisticated 1700+ line parser for Formedible form definitions with advanced security sanitization, complex Zod expression parsing, AI-friendly error reporting, automatic schema inference, and support for all 24+ field types with location-aware debugging.

Installation

npx shadcn@latest add https://formedible.dev/r/formedible-parser.json

Key Features

Advanced Security Sanitization
Removes eval, Function, setTimeout, dangerous patterns and protects against code injection
Complex Zod Expression Parsing
Handles nested parentheses, chained methods like z.string().min(1).max(50), and complex validations
AI-Friendly Error Reporting
Detailed error messages with fixes, examples, and suggestions specifically designed for AI integrations
Automatic Schema Inference
Infers Zod schemas from field configurations with confidence scoring and validation
24+ Field Type Support
Complete support for all Formedible field types with complex configurations (array, object, phone, rating, etc.)
Multiple Input Formats
Parses JSON, JavaScript object literals, and Zod expressions with intelligent format detection

Getting Started

Main Parsing API
Parse form definitions with automatic security sanitization and enhanced error reporting
import { FormedibleParser } from '@/components/formedible-parser';
// Main parsing method - supports JSON, JS objects, and Zod expressions
const formDefinition = `{
title: "Advanced Contact Form",
fields: [
{
name: "email",
type: "email",
label: "Email Address",
required: true
},
{
name: "rating",
type: "rating",
label: "Service Rating",
ratingConfig: { max: 5, allowHalf: true, icon: "star" }
},
{
name: "feedback",
type: "textarea",
label: "Detailed Feedback",
textareaConfig: { rows: 4, maxLength: 500, showWordCount: true }
}
],
schema: "z.object({ email: z.string().email(), rating: z.number().optional(), feedback: z.string().optional() })"
}`;
try {
// Parse with default options
const parsedConfig = FormedibleParser.parse(formDefinition);
console.log('Parsed successfully:', parsedConfig);
} catch (error) {
console.error('Enhanced error info:', error.message);
// Shows detailed AI-friendly error messages with fixes
}
Complex Field Configurations
Handle nested object and array fields with comprehensive validation and type checking
// Complex field configurations with nested objects
const complexFormConfig = `{
title: "Team Registration Form",
fields: [
{
name: "teamLead",
type: "object",
label: "Team Lead Information",
objectConfig: {
title: "Team Lead Details",
collapsible: true,
layout: "vertical",
fields: [
{ name: "name", type: "text", label: "Full Name", required: true },
{ name: "email", type: "email", label: "Email", required: true },
{ name: "phone", type: "phone", label: "Phone Number", phoneConfig: { defaultCountry: "US" } }
]
}
},
{
name: "teamMembers",
type: "array",
label: "Team Members",
arrayConfig: {
itemType: "object",
itemLabel: "Team Member",
minItems: 1,
maxItems: 10,
sortable: true,
objectConfig: {
fields: [
{ name: "name", type: "text", label: "Name", required: true },
{ name: "role", type: "select", label: "Role", options: ["Developer", "Designer", "Manager"] },
{ name: "skills", type: "multiSelect", label: "Skills", options: ["React", "TypeScript", "Node.js", "Python"] }
]
}
}
}
]
}`;
const parsedConfig = FormedibleParser.parse(complexFormConfig);
Advanced Zod Expression Parsing
Parse complex chained Zod expressions, nested parentheses, and cross-field validation rules
// Advanced Zod parsing with nested expressions and chained methods
const zodFormConfig = `{
title: "User Registration with Complex Validation",
fields: [
{
name: "email",
type: "email",
label: "Email Address",
required: true
},
{
name: "password",
type: "password",
label: "Password",
passwordConfig: { showToggle: true, strengthMeter: true }
},
{
name: "confirmPassword",
type: "password",
label: "Confirm Password"
}
],
// Complex chained Zod expressions are parsed correctly
schema: "z.object({
email: z.string().email().min(1, 'Required'),
password: z.string().min(8).regex(/[A-Z]/, 'Must contain uppercase').regex(/[0-9]/, 'Must contain number'),
confirmPassword: z.string()
}).refine(data => data.password === data.confirmPassword, { message: 'Passwords must match', path: ['confirmPassword'] })",
crossFieldValidation: [
{
fields: ["password", "confirmPassword"],
validator: "passwords-match",
message: "Passwords must match exactly"
}
]
}`;
const parsedConfig = FormedibleParser.parse(zodFormConfig);

Advanced Features

AI-Friendly Error Reporting
Enhanced error messages with detailed fixes, examples, and suggestions designed for AI integrations
// Enhanced error handling with AI-friendly suggestions
const invalidConfig = `{
fields: [
{ name: "email", type: "invalid-type" }, // Invalid field type
{ name: "", type: "text" } // Missing name
]
}`;
try {
const result = FormedibleParser.parse(invalidConfig);
} catch (error) {
if (error.name === 'ParserError') {
console.log('❌ Error Code:', error.code);
console.log('📝 Enhanced message with examples:', error.message);
// Shows detailed fix suggestions like:
// ✅ Supported field types: text, email, password, url, tel, textarea...
// 📝 Example: { name: "email", type: "email", label: "Email Address" }
if (error.fieldIndex !== undefined) {
console.log('🎯 Error in field #:', error.fieldIndex);
}
}
}
// Validation with suggestions - perfect for AI integrations
const validationResult = FormedibleParser.validateWithSuggestions(invalidConfig);
console.log('Is valid:', validationResult.isValid);
console.log('Errors:', validationResult.errors);
console.log('AI suggestions:', validationResult.suggestions);
Schema Inference & Merging
Automatic Zod schema inference, confidence scoring, and advanced schema merging strategies
// Schema inference and merging capabilities
const formDefinition = `{
fields: [
{ name: "email", type: "email", label: "Email" },
{ name: "age", type: "number", label: "Age", min: 18, max: 120 }
]
}`;
// Parse with automatic schema inference
const inferenceResult = FormedibleParser.parseWithSchemaInference(formDefinition, {
enabled: true,
defaultValidation: true,
inferFromValues: true
});
console.log('Parsed config:', inferenceResult.config);
console.log('Inferred schema:', inferenceResult.inferredSchema);
console.log('Confidence score:', inferenceResult.confidence);
// Merge with existing schemas
import { z } from 'zod';
const baseSchema = z.object({
firstName: z.string(),
lastName: z.string()
});
const mergedConfig = FormedibleParser.mergeSchemas(
inferenceResult.config,
baseSchema,
'extend' // 'extend' | 'override' | 'intersect'
);
// Field type validation
console.log('Is valid type:', FormedibleParser.isValidFieldType('email')); // true
console.log('Supported types:', FormedibleParser.getSupportedFieldTypes()); // All 24 types
Security & Sanitization
Advanced security measures protect against code injection and dangerous patterns
// The parser automatically sanitizes dangerous code patterns
const dangerousCode = `{
fields: [
{
name: "email",
type: "email",
validation: "eval('malicious code')", // ❌ Automatically removed
onSubmit: "setTimeout(() => { /* dangerous */ }, 1000)" // ❌ Sanitized
}
],
onSubmit: "fetch('/api/steal-data')" // ❌ Functions not supported in parser mode
}`;
// Security patterns automatically removed:
// - eval, Function, setTimeout, setInterval
// - document, window, global, process
// - __proto__, constructor, prototype
// - Arrow functions and function expressions
// - new keyword usage
const safeConfig = FormedibleParser.parse(dangerousCode);
// Result: Clean configuration object with dangerous patterns removed
// Location-aware error reporting for debugging
try {
FormedibleParser.parse('{ invalid: syntax }');
} catch (error) {
console.log('Error at line:', error.location?.line);
console.log('Error at column:', error.location?.column);
console.log('Field context:', error.location?.field);
}

Complete API Reference

Available Methods
All static methods available in the FormedibleParser class
// ✅ Main API Methods (all static)
FormedibleParser.parse(code, options?) // Main parsing method
FormedibleParser.parseWithSchemaInference(code, options?) // With schema inference
FormedibleParser.validateWithSuggestions(code) // AI-friendly validation
FormedibleParser.mergeSchemas(config, baseSchema, strategy) // Schema merging
FormedibleParser.isValidFieldType(type) // Field type validation
FormedibleParser.getSupportedFieldTypes() // Get all supported types
FormedibleParser.validateConfig(config) // Validate config object
// ✅ Supported merge strategies
'extend' // Add missing fields from base schema
'override' // Replace schema completely
'intersect' // Keep only fields that exist in both
// ✅ All 24 supported field types
const fieldTypes = FormedibleParser.getSupportedFieldTypes();
console.log(fieldTypes);
// ['text', 'email', 'password', 'url', 'tel', 'textarea', 'select',
// 'checkbox', 'switch', 'number', 'date', 'slider', 'file', 'rating',
// 'phone', 'colorPicker', 'location', 'duration', 'multiSelect',
// 'autocomplete', 'masked', 'object', 'array', 'radio']
Supported Field Types
All 24 field types supported by Formedible
textemailpasswordurlteltextareaselectcheckboxswitchnumberdatesliderfileratingphonecolorPickerlocationdurationmultiSelectautocompletemaskedobjectarrayradio

Ready to Parse Forms?

The formedible-parser is a sophisticated 1700+ line implementation with advanced security sanitization, complex Zod expression parsing, schema inference, AI-friendly error reporting, and comprehensive validation for all 24+ field types. Perfect for AI integrations and enterprise applications.