Complete API reference for @squaredr/fieldcraft-core.
createEngine
Creates a form engine instance from a schema.
import { createEngine } from "@squaredr/fieldcraft-core";
const engine = createEngine(schema, options?);
EngineOptions
| Option | Type | Description |
|---|
mode | "controlled" | "uncontrolled" | Controlled mode for external state management |
initialValues | Record<string, unknown> | Initial field values |
prefillValues | Record<string, unknown> | Pre-fill from external sources |
adapters | SubmitAdapter | SubmitAdapter[] | Storage adapters |
draftAdapter | DraftAdapter | Draft persistence adapter |
analytics | AnalyticsAdapter | Analytics tracking adapter |
onSubmit | (response: FormResponse) => void | Submit callback |
onStateChange | (state: FormState) => void | State change callback |
onSectionChange | (sectionId: string, index: number) => void | Section navigation callback |
onFieldChange | (fieldId: string, value: unknown) => void | Field change callback |
validators | Record<string, CustomValidator> | Custom sync validators |
asyncValidators | Record<string, AsyncValidator> | Custom async validators |
sessionToken | string | Token for draft persistence |
FormEngine Methods
State
// Get current state snapshot
engine.getState(): FormState
// Subscribe to state changes (returns unsubscribe function)
engine.subscribe(listener: (state: FormState) => void): () => void
Field Manipulation
// Set a single field value
engine.setValue(fieldId: string, value: unknown): void
// Set multiple field values at once
engine.setValues(values: Record<string, unknown>): void
// Mark a field as touched (triggers error display)
engine.touchField(fieldId: string): void
// Clear a field value
engine.clearField(fieldId: string): void
Navigation
// Move to next section
engine.nextSection(): void
// Move to previous section
engine.prevSection(): void
// Jump to a section by ID
engine.jumpTo(sectionId: string): void
Queries
// Get all visible sections (respects showIf)
engine.getVisibleSections(): Section[]
// Get visible fields in a section
engine.getVisibleFields(sectionId: string): Question[]
// Field state queries
engine.isFieldVisible(fieldId: string): boolean
engine.isFieldRequired(fieldId: string): boolean
engine.isFieldDisabled(fieldId: string): boolean
engine.getFieldError(fieldId: string): string[] | undefined
// Schema access
engine.getSchema(): FormEngineSchema
engine.getSectionById(sectionId: string): Section | undefined
engine.getQuestionById(questionId: string): Question | undefined
Validation
// Validate the entire form
engine.validate(): ValidationResult
// Validate a specific section
engine.validateSection(sectionId: string): ValidationResult
// ValidationResult shape:
// {
// valid: boolean;
// errors: Record<string, string[]>;
// firstErrorFieldId?: string;
// firstErrorSectionId?: string;
// }
Submission
// Submit the form (validates first, then runs adapters)
engine.submit(): Promise<SubmitResult>
// SubmitResult shape:
// {
// success: boolean;
// adapterResults: {
// adapterName: string;
// success: boolean;
// error?: string;
// }[];
// }
Draft Persistence
// Save current state as a draft
engine.saveDraft(): Promise<void>
// Load a saved draft (returns true if found)
engine.loadDraft(): Promise<boolean>
// Delete the saved draft
engine.clearDraft(): void
Lifecycle
// Clean up subscriptions and timers
engine.destroy(): void
FormState
type FormState = {
// Values & errors
values: Record<string, unknown>;
errors: Record<string, string[]>;
touched: Record<string, boolean>;
isDirty: boolean;
// Submission
isSubmitting: boolean;
isSubmitted: boolean;
submitError?: string;
submitAttempted: boolean;
// Navigation
currentSectionId: string;
currentSectionIndex: number;
totalVisibleSections: number;
progressPercent: number;
visibleSectionIds: string[];
visitedSectionIds: string[];
canGoNext: boolean;
canGoPrev: boolean;
isCurrentSectionValid: boolean;
// Scoring
scores: Record<string, number>;
totalScore?: number;
// Drafts
hasDraft: boolean;
lastDraftSavedAt?: string;
};
validateSchema
Validates a raw schema object at runtime. Returns a typed FormEngineSchema on success. Throws FormEngineSchemaError on failure.
import { validateSchema, FormEngineSchemaError } from "@squaredr/fieldcraft-core";
try {
const schema = validateSchema(rawData);
// schema is typed FormEngineSchema
} catch (err) {
if (err instanceof FormEngineSchemaError) {
console.error(err.issues); // ZodIssue[]
}
}
createHttpAdapter
Built-in HTTP adapter for posting responses to any endpoint:
import { createHttpAdapter } from "@squaredr/fieldcraft-core";
const adapter = createHttpAdapter({
url: "https://api.example.com/responses",
method: "POST", // default
headers: { Authorization: "Bearer ..." },
timeout: 10000,
transform: (response) => ({ // optional
...response,
extra: "metadata",
}),
});
generateSessionToken
Generates a random session token for draft persistence:
import { generateSessionToken } from "@squaredr/fieldcraft-core";
const token = generateSessionToken(); // e.g. "a1b2c3d4-e5f6-7890-abcd-ef1234567890"