Skip to content

Beautiful Open-Source Form Builder

fix(forms): harden definition validation (#1282)

Julien Nahum94d08800baa1
diff --git a/api/app/Console/Commands/AuditFormDefinitions.php b/api/app/Console/Commands/AuditFormDefinitions.php
new file mode 100644
index 000000000..29c2fbc89
--- /dev/null
+++ b/api/app/Console/Commands/AuditFormDefinitions.php
@@ -0,0 +1,164 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Models\Forms\Form;
+use App\Service\Forms\FormDataNormalizer;
+use App\Service\Forms\FormStructureValidator;
+use Illuminate\Console\Command;
+use Illuminate\Support\Facades\DB;
+use RuntimeException;
+
+class AuditFormDefinitions extends Command
+{
+ protected $signature = 'forms:audit-definitions
+ {--limit= : Maximum number of forms to inspect}
+ {--with-trashed : Include soft-deleted forms}
+ {--json : Emit the complete report as JSON}';
+
+ protected $description = 'Audit persisted form fields, computed variables and logic without modifying data';
+
+ public function __construct(
+ private readonly FormDataNormalizer $formDataNormalizer,
+ private readonly FormStructureValidator $formStructureValidator,
+ ) {
+ parent::__construct();
+ }
+
+ public function handle(): int
+ {
+ $report = DB::transaction(function (): array {
+ $readOnly = $this->enableAndVerifyReadOnlyTransaction();
+ $limit = $this->validatedLimit();
+ $query = Form::query()
+ ->select(['id', 'workspace_id', 'slug', 'visibility', 'properties', 'computed_variables'])
+ ->orderBy('id');
+
+ if ($this->option('with-trashed')) {
+ $query->withTrashed();
+ }
+
+ if ($limit !== null) {
+ $query->limit($limit);
+ }
+
+ $forms = 0;
+ $validForms = 0;
+ $autoRepairedForms = 0;
+ $invalidFormsCount = 0;
+ $invalidForms = [];
+ $issuesByCode = [];
+ $includeInvalidFormDetails = (bool) $this->option('json');
+
+ foreach ($query->cursor() as $form) {
+ $forms++;
+ $definition = [
+ 'properties' => $form->properties ?? [],
+ 'computed_variables' => $form->computed_variables ?? [],
+ ];
+ $normalizedDefinition = $this->formDataNormalizer->normalize($definition);
+ if ($normalizedDefinition !== $definition) {
+ $autoRepairedForms++;
+ }
+ $workspace = collect($normalizedDefinition['properties'])
+ ->contains(fn ($property) => is_array($property) && ($property['type'] ?? null) === 'payment')
+ ? $form->workspace()->first()
+ : null;
+ $issues = $this->formStructureValidator->issues($normalizedDefinition, $workspace);
+
+ if ($issues === []) {
+ $validForms++;
+
+ continue;
+ }
+
+ foreach ($issues as $issue) {
+ $issuesByCode[$issue['code']] = ($issuesByCode[$issue['code']] ?? 0) + 1;
+ }
+
+ $invalidFormsCount++;
+ if ($includeInvalidFormDetails) {
+ $invalidForms[] = [
+ 'form_id' => $form->id,
+ 'workspace_id' => $form->workspace_id,
+ 'slug' => $form->slug,
+ 'visibility' => $form->visibility,
+ 'issues' => $issues,
+ ];
+ }
+ }
+
+ ksort($issuesByCode);
+
+ return [
+ 'read_only' => $readOnly,
+ 'forms_checked' => $forms,
+ 'valid_forms' => $validForms,
+ 'auto_repaired_forms' => $autoRepairedForms,
+ 'invalid_forms_count' => $invalidFormsCount,
+ 'issues_by_code' => $issuesByCode,
+ 'invalid_forms' => $invalidForms,
+ ];
+ });
+
+ if ($this->option('json')) {
+ $this->line(json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
+
+ return Command::SUCCESS;
+ }
+
+ $this->info('Read-only form definition audit completed.');
+ $this->table(
+ ['Read only', 'Checked', 'Valid', 'Auto-repaired', 'Invalid'],
+ [[
+ $report['read_only'],
+ $report['forms_checked'],
+ $report['valid_forms'],
+ $report['auto_repaired_forms'],
+ $report['invalid_forms_count'],
+ ]],
+ );
+
+ if ($report['issues_by_code'] !== []) {
+ $this->table(
+ ['Issue code', 'Occurrences'],
+ collect($report['issues_by_code'])->map(fn (int $count, string $code) => [$code, $count])->values()->all(),
+ );
+ $this->warn('Run again with --json to inspect the affected form IDs and exact paths.');
+ }
+
+ return Command::SUCCESS;
+ }
+
+ private function enableAndVerifyReadOnlyTransaction(): string
+ {
+ $connection = DB::connection();
+ if ($connection->getDriverName() !== 'pgsql') {
+ return 'query-only command (database does not support PostgreSQL transaction_read_only)';
+ }
+
+ $connection->statement('SET TRANSACTION READ ONLY');
+ $state = $connection->selectOne('SHOW transaction_read_only');
+ $readOnly = $state->transaction_read_only ?? null;
+
+ if (! in_array($readOnly, ['on', true, 1, '1'], true)) {
+ throw new RuntimeException('The database transaction could not be verified as read-only.');
+ }
+
+ return 'on';
+ }
+
+ private function validatedLimit(): ?int
+ {
+ $limit = $this->option('limit');
+ if ($limit === null) {
+ return null;
+ }
+
+ if (! ctype_digit((string) $limit) || (int) $limit < 1) {
+ throw new RuntimeException('--limit must be a positive integer.');
+ }
+
+ return (int) $limit;
+ }
+}
diff --git a/api/app/Http/Controllers/Forms/FormController.php b/api/app/Http/Controllers/Forms/FormController.php
index 2da51cf08..b7bcba79c 100644
--- a/api/app/Http/Controllers/Forms/FormController.php
+++ b/api/app/Http/Controllers/Forms/FormController.php
@@ -16,6 +16,8 @@ use App\Notifications\Forms\MobileEditorEmail;
use App\Service\Billing\Feature;
use App\Service\Forms\FormCleaner;
use App\Service\Forms\FormCreationService;
+use App\Service\Forms\FormDataNormalizer;
+use App\Service\Forms\FormStructureValidator;
use App\Service\Forms\FormUpdateService;
use App\Service\Storage\FileUploadPathService;
use App\Service\Storage\StorageFileNameParser;
@@ -35,6 +37,8 @@ class FormController extends Controller
public function __construct(
private readonly FormCreationService $formCreation,
private readonly FormUpdateService $formUpdate,
+ private readonly FormDataNormalizer $formDataNormalizer,
+ private readonly FormStructureValidator $formStructureValidator,
) {
$this->middleware('auth', ['except' => ['uploadAsset']]);
$this->formCleaner = new FormCleaner();
@@ -182,6 +186,16 @@ class FormController extends Controller
]);
}
+ public function validateDefinition(UpdateFormRequest $request, Form $form)
+ {
+ $this->authorize('update', $form);
+
+ return $this->success([
+ 'valid' => true,
+ 'message' => 'The form definition is valid.',
+ ]);
+ }
+
public function destroy(Form $form)
{
$this->authorize('delete', $form);
@@ -197,8 +211,16 @@ class FormController extends Controller
{
$this->authorize('update', $form);
+ $normalizedStructure = $this->formDataNormalizer->normalize([
+ 'properties' => $form->properties ?? [],
+ 'computed_variables' => $form->computed_variables ?? [],
+ ]);
+ $this->formStructureValidator->validate($normalizedStructure, $form->workspace);
+
// Create copy
$formCopy = $form->replicate();
+ $formCopy->properties = $normalizedStructure['properties'];
+ $formCopy->computed_variables = $normalizedStructure['computed_variables'];
// generate new slug before changing title
if (Str::isUuid($formCopy->slug)) {
$formCopy->slug = Str::uuid();
diff --git a/api/app/Http/Requests/UpdateFormRequest.php b/api/app/Http/Requests/UpdateFormRequest.php
index 4363d5511..f7bf180b1 100644
--- a/api/app/Http/Requests/UpdateFormRequest.php
+++ b/api/app/Http/Requests/UpdateFormRequest.php
@@ -4,4 +4,10 @@ namespace App\Http\Requests;
class UpdateFormRequest extends UserFormRequest
{
+ public function authorize(): bool
+ {
+ return $this->form !== null
+ && $this->user() !== null
+ && $this->user()->can('update', $this->form);
+ }
}
diff --git a/api/app/Http/Requests/UserFormRequest.php b/api/app/Http/Requests/UserFormRequest.php
index 216525b2a..2ca31184d 100644
--- a/api/app/Http/Requests/UserFormRequest.php
+++ b/api/app/Http/Requests/UserFormRequest.php
@@ -14,6 +14,8 @@ use Illuminate\Validation\Rule;
use Illuminate\Http\Request;
use App\Rules\CssOnlyRule;
use App\Service\Forms\FormDataNormalizer;
+use App\Service\Forms\FormStructureValidator;
+use App\Service\Forms\FormValidationIssueMapper;
/**
* Abstract class to validate create/update forms
@@ -58,14 +60,21 @@ abstract class UserFormRequest extends \Illuminate\Foundation\Http\FormRequest
];
// Log to both default channel and Slack
- if (!app()->environment('testing')) {
+ if (! app()->environment('testing') && ! $this->routeIs('open.forms.validate-definition')) {
Log::channel('slack_errors')->warning(
'Frontend validation bypass detected in form submission',
$logData
);
}
- throw new ValidationException($validator);
+ $issueMapper = app(FormValidationIssueMapper::class);
+ $issues = $issueMapper->fromErrors($errors);
+
+ throw new ValidationException($validator, response()->json([
+ 'message' => $issueMapper->summary($issueMapper->count($errors)),
+ 'errors' => $errors,
+ 'issues' => $issues,
+ ], 422));
}
/**
@@ -175,7 +184,7 @@ abstract class UserFormRequest extends \Illuminate\Foundation\Http\FormRequest
// Properties - Single-pass validation for performance
// Replaces ~35 wildcard rules (properties.*) with one efficient rule
- 'properties' => ['required', 'array', new FormPropertiesRule($workspace)],
+ 'properties' => ['required', 'array', 'max:'.FormStructureValidator::MAX_PROPERTY_COUNT, new FormPropertiesRule($workspace)],
// Computed Variables - Single-pass validation with formula syntax checking
'computed_variables' => ['nullable', 'array', new ComputedVariablesRule()],
diff --git a/api/app/Http/Resources/FormResource.php b/api/app/Http/Resources/FormResource.php
index 807485603..b89cec43d 100644
--- a/api/app/Http/Resources/FormResource.php
+++ b/api/app/Http/Resources/FormResource.php
@@ -169,7 +169,7 @@ class FormResource extends JsonResource
private function hasPaymentBlock()
{
return array_filter($this->properties, function ($property) {
- return $property['type'] === 'payment';
+ return is_array($property) && ($property['type'] ?? null) === 'payment';
});
}
diff --git a/api/app/Mcp/Tools/PatchFormDraftTool.php b/api/app/Mcp/Tools/PatchFormDraftTool.php
index 3197f2bb9..131f8c2bc 100644
--- a/api/app/Mcp/Tools/PatchFormDraftTool.php
+++ b/api/app/Mcp/Tools/PatchFormDraftTool.php
@@ -4,6 +4,7 @@ namespace App\Mcp\Tools;
use App\Mcp\Support\McpOutputSchema;
use App\Models\Forms\Form;
+use App\Rules\PropertyValidators\LogicPropertyValidator;
use App\Service\Forms\AgentFormFieldCatalog;
use App\Service\Forms\AgentFormDraftService;
use Illuminate\Contracts\JsonSchema\JsonSchema;
@@ -75,15 +76,26 @@ class PatchFormDraftTool extends GuestDraftMcpTool
'show_progress_bar' => $schema->boolean(),
'submit_button_text' => $schema->string(),
'settings' => $schema->object(),
- ])->description('Top-level form values for set_form_values. Do not put properties here.'),
+ 'computed_variables' => $schema->array()
+ ->items($schema->object([
+ 'id' => $schema->string()->description('Unique technical ID beginning with cv_.')->required(),
+ 'name' => $schema->string()->description('Unique human-readable variable name.')->required(),
+ 'formula' => $schema->string()->description('Formula using brace references such as {budget} * 1.2.')->required(),
+ 'result_type' => $schema->string()->enum(['number', 'text', 'auto']),
+ ]))
+ ->max(500)
+ ->description('Complete replacement list of computed variables. Use [] to remove all variables.'),
+ ])->description('Top-level form values for set_form_values, including computed_variables. Do not put properties here.'),
'block' => $schema->object([
'name' => $schema->string()->required(),
'type' => $schema->string()->enum(AgentFormFieldCatalog::types())->required(),
'content' => $schema->string()->description('For nf-text blocks: sanitized HTML, never Markdown.'),
'placeholder' => $schema->string()->nullable(),
'help' => $schema->string()->nullable(),
+ 'hidden' => $schema->boolean(),
'required' => $schema->boolean(),
'width' => $schema->string()->enum(['full', '1/2', '1/3', '2/3', '1/4', '3/4']),
+ 'logic' => $this->logicSchema($schema)->nullable(),
])->description('Complete block for add_block. Use type nf-page-break only in classic mode.'),
'patch' => $schema->object([
'name' => $schema->string(),
@@ -91,8 +103,10 @@ class PatchFormDraftTool extends GuestDraftMcpTool
'content' => $schema->string()->description('For nf-text blocks: sanitized HTML, never Markdown.'),
'placeholder' => $schema->string()->nullable(),
'help' => $schema->string()->nullable(),
+ 'hidden' => $schema->boolean(),
'required' => $schema->boolean(),
'width' => $schema->string()->enum(['full', '1/2', '1/3', '2/3', '1/4', '3/4']),
+ 'logic' => $this->logicSchema($schema)->nullable(),
])->description('Fields to merge into the selected block for update_block. Block id cannot change.'),
'block_id' => $schema->string()->description('Stable block id from the latest draft.'),
'index' => $schema->integer()->description('Zero-based block index. For add_block, insertion at the final count is allowed.')->min(0),
@@ -104,6 +118,31 @@ class PatchFormDraftTool extends GuestDraftMcpTool
];
}
+ private function logicSchema(JsonSchema $schema): mixed
+ {
+ return $schema->object([
+ 'conditions' => $schema->object([
+ 'operatorIdentifier' => $schema->string()->enum(['and', 'or']),
+ 'children' => $schema->array()->items($schema->object()),
+ 'identifier' => $schema->string()->description('Referenced field or computed-variable ID.'),
+ 'value' => $schema->object([
+ 'operator' => $schema->string()->enum(AgentFormFieldCatalog::logicOperators()),
+ 'property_meta' => $schema->object([
+ 'id' => $schema->string()->description('Referenced field or computed-variable ID.'),
+ 'type' => $schema->string()
+ ->enum(array_keys(AgentFormFieldCatalog::logicOperatorsByReferenceType()))
+ ->description('Use computed for a computed-variable reference.'),
+ ]),
+ 'value' => $schema->union(['string', 'number', 'boolean', 'object', 'array', 'null'])
+ ->description('Comparison value. Omit it for operators that do not take a value, such as is_empty or is_checked.'),
+ ]),
+ ])->description('A condition leaf or a nested and/or group. See opnform://schemas/agent-form-definition/v1 for the recursive shape.'),
+ 'actions' => $schema->array()
+ ->items($schema->string()->enum(LogicPropertyValidator::ACTIONS_VALUES))
+ ->min(1),
+ ])->description('Conditional behavior for the target block. Empty or safely invalid logic is removed during normalization.');
+ }
+
public function outputSchema(JsonSchema $schema): array
{
return [
diff --git a/api/app/Rules/ComputedVariablesRule.php b/api/app/Rules/ComputedVariablesRule.php
index 718cca5f3..af342d255 100644
--- a/api/app/Rules/ComputedVariablesRule.php
+++ b/api/app/Rules/ComputedVariablesRule.php
@@ -8,6 +8,7 @@ use Closure;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
+use Illuminate\Support\Str;
use Illuminate\Validation\Validator;
/**
@@ -16,6 +17,8 @@ use Illuminate\Validation\Validator;
*/
class ComputedVariablesRule implements ValidationRule, ValidatorAwareRule, DataAwareRule
{
+ public const MAX_VARIABLE_COUNT = 500;
+
private const MAX_CHAIN_DEPTH = 20;
private const VALID_RESULT_TYPES = ['number', 'text', 'auto'];
@@ -62,28 +65,39 @@ class ComputedVariablesRule implements ValidationRule, ValidatorAwareRule, DataA
return;
}
+ if (count($value) > self::MAX_VARIABLE_COUNT) {
+ $fail('A form cannot contain more than '.self::MAX_VARIABLE_COUNT.' computed variables.');
+
+ return;
+ }
+
$allErrors = [];
$seenNames = [];
$seenIds = [];
// Get form properties for field reference validation
- $properties = $this->data['properties'] ?? [];
+ $properties = is_array($this->data['properties'] ?? null)
+ ? $this->data['properties']
+ : [];
$availableFields = $this->buildAvailableFields($properties);
+ $fieldIds = array_fill_keys(array_column($availableFields, 'id'), true);
foreach ($value as $index => $variable) {
- $errors = $this->validateVariable($variable, $index, $availableFields, $value, $seenNames, $seenIds);
+ $errors = $this->validateVariable($variable, $index, $availableFields, $value, $seenNames, $seenIds, $fieldIds);
- foreach ($errors as $field => $message) {
+ foreach ($errors as $field => $messages) {
$errorKey = "computed_variables.{$index}.{$field}";
if (! isset($allErrors[$errorKey])) {
$allErrors[$errorKey] = [];
}
- $allErrors[$errorKey][] = $message;
+ foreach ((array) $messages as $message) {
+ $allErrors[$errorKey][] = $message;
+ }
}
// Track seen names and IDs for uniqueness checks
if (isset($variable['name']) && is_string($variable['name'])) {
- $seenNames[strtolower($variable['name'])] = $index;
+ $seenNames[Str::lower($variable['name'])] = $index;
}
if (isset($variable['id']) && is_string($variable['id'])) {
$seenIds[$variable['id']] = $index;
@@ -92,15 +106,18 @@ class ComputedVariablesRule implements ValidationRule, ValidatorAwareRule, DataA
// Check for circular dependencies
$circularErrors = $this->detectCircularDependencies($value);
- foreach ($circularErrors as $error) {
- $allErrors['computed_variables'][] = $error;
+ foreach ($circularErrors as $errorKey => $messages) {
+ foreach ($messages as $message) {
+ $allErrors[$errorKey][] = $message;
+ }
}
// Check for maximum chain depth (only if no cycles)
if (empty($circularErrors)) {
- $chainDepthError = $this->checkChainDepth($value);
- if ($chainDepthError !== null) {
- $allErrors['computed_variables'][] = $chainDepthError;
+ foreach ($this->chainDepthErrors($value) as $errorKey => $messages) {
+ foreach ($messages as $message) {
+ $allErrors[$errorKey][] = $message;
+ }
}
}
@@ -124,7 +141,8 @@ class ComputedVariablesRule implements ValidationRule, ValidatorAwareRule, DataA
array $availableFields,
array $allVariables,
array $seenNames,
- array $seenIds
+ array $seenIds,
+ array $fieldIds,
): array {
$errors = [];
@@ -137,6 +155,8 @@ class ComputedVariablesRule implements ValidationRule, ValidatorAwareRule, DataA
$errors['id'] = 'The computed variable ID is required.';
} elseif (! preg_match('/^cv_/', $variable['id'])) {
$errors['id'] = 'The computed variable ID must start with "cv_".';
+ } elseif (isset($fieldIds[$variable['id']])) {
+ $errors['id'] = "The computed variable ID [{$variable['id']}] is already used by a form field.";
} elseif (isset($seenIds[$variable['id']])) {
$errors['id'] = 'Duplicate computed variable ID.';
}
@@ -144,31 +164,31 @@ class ComputedVariablesRule implements ValidationRule, ValidatorAwareRule, DataA
// Validate name
if (! isset($variable['name']) || ! is_string($variable['name'])) {
$errors['name'] = 'The computed variable name is required.';
- } elseif (strlen($variable['name']) === 0) {
+ } elseif (trim($variable['name']) === '') {
$errors['name'] = 'The computed variable name cannot be empty.';
- } elseif (strlen($variable['name']) > 100) {
+ } elseif (Str::length($variable['name']) > 100) {
$errors['name'] = 'The computed variable name must not exceed 100 characters.';
- } elseif (isset($seenNames[strtolower($variable['name'])])) {
+ } elseif (isset($seenNames[Str::lower($variable['name'])])) {
$errors['name'] = 'Duplicate computed variable name. Variable names must be unique.';
}
// Validate formula
if (! isset($variable['formula']) || ! is_string($variable['formula'])) {
$errors['formula'] = 'The formula is required.';
- } elseif (strlen($variable['formula']) === 0) {
+ } elseif (trim($variable['formula']) === '') {
$errors['formula'] = 'The formula cannot be empty.';
- } elseif (strlen($variable['formula']) > 2000) {
+ } elseif (Str::length($variable['formula']) > 2000) {
$errors['formula'] = 'The formula must not exceed 2000 characters.';
} else {
// Validate formula syntax and field references
$formulaErrors = $this->validateFormula(
$variable['formula'],
- $variable['id'] ?? null,
+ is_string($variable['id'] ?? null) ? $variable['id'] : null,
$availableFields,
$allVariables
);
if (! empty($formulaErrors)) {
- $errors['formula'] = $formulaErrors[0]; // Return first error
+ $errors['formula'] = $formulaErrors;
}
}
@@ -193,7 +213,9 @@ class ComputedVariablesRule implements ValidationRule, ValidatorAwareRule, DataA
): array {
// Build available variables (excluding current one to prevent self-reference)
$availableVariables = collect($allVariables)
- ->filter(fn ($v) => isset($v['id']) && $v['id'] !== $currentVariableId)
+ ->filter(fn ($v) => is_array($v)
+ && is_string($v['id'] ?? null)
+ && $v['id'] !== $currentVariableId)
->map(fn ($v) => ['id' => $v['id'], 'name' => $v['name'] ?? ''])
->values()
->all();
@@ -219,7 +241,9 @@ class ComputedVariablesRule implements ValidationRule, ValidatorAwareRule, DataA
private function buildAvailableFields(array $properties): array
{
return collect($properties)
- ->filter(fn ($p) => isset($p['id']) && isset($p['type']))
+ ->filter(fn ($p) => is_array($p)
+ && is_string($p['id'] ?? null)
+ && is_string($p['type'] ?? null))
->map(fn ($p) => [
'id' => $p['id'],
'name' => $p['name'] ?? '',
@@ -235,37 +259,38 @@ class ComputedVariablesRule implements ValidationRule, ValidatorAwareRule, DataA
private function detectCircularDependencies(array $variables): array
{
$errors = [];
- $graph = [];
- $variableMap = [];
-
- // Build dependency graph
- foreach ($variables as $variable) {
- if (! isset($variable['id']) || ! isset($variable['formula'])) {
- continue;
- }
-
- $variableMap[$variable['id']] = $variable['name'] ?? $variable['id'];
- $dependencies = FormulaValidator::extractFieldReferences($variable['formula']);
-
- // Only keep dependencies that are other computed variables
- $variableDeps = array_filter($dependencies, function ($dep) use ($variables) {
- return collect($variables)->contains('id', $dep);
- });
+ $validVariables = collect($variables)
+ ->filter(fn ($variable) => is_array($variable)
+ && is_string($variable['id'] ?? null)
+ && is_string($variable['formula'] ?? null))
+ ->values()
+ ->all();
- $graph[$variable['id']] = $variableDeps;
+ if ($validVariables === []) {
+ return [];
}
- // DFS to detect cycles
- $visited = [];
- $recursionStack = [];
-
- foreach (array_keys($graph) as $nodeId) {
- $cycle = $this->findCycle($nodeId, $graph, $visited, $recursionStack, []);
- if ($cycle !== null) {
- $cycleNames = array_map(fn ($id) => $variableMap[$id] ?? $id, $cycle);
- $errors[] = 'Circular dependency detected: ' . implode(' → ', $cycleNames);
-
- break; // Report only the first cycle
+ $resolver = DependencyResolver::fromVariables($validVariables);
+ $cycles = $resolver->detectCycles();
+ $variablesById = collect($variables)
+ ->filter(fn ($variable) => is_array($variable) && is_string($variable['id'] ?? null))
+ ->keyBy('id');
+
+ foreach ($cycles as $cycle) {
+ $cycleIds = array_values(array_unique($cycle));
+ $cycleNames = array_map(
+ fn (string $id) => $variablesById->get($id)['name'] ?? $id,
+ $cycleIds,
+ );
+ $message = 'Circular dependency detected: '.implode(' → ', [...$cycleNames, $cycleNames[0]]);
+
+ foreach ($cycleIds as $cycleId) {
+ $variableIndex = collect($variables)->search(
+ fn ($variable) => is_array($variable) && ($variable['id'] ?? null) === $cycleId,
+ );
+ if ($variableIndex !== false) {
+ $errors["computed_variables.{$variableIndex}.formula"][] = $message;
+ }
}
}
@@ -273,56 +298,49 @@ class ComputedVariablesRule implements ValidationRule, ValidatorAwareRule, DataA
}
/**
- * DFS helper to find cycles in the dependency graph.
+ * Check if the dependency chain depth exceeds the maximum.
*/
- private function findCycle(
- string $nodeId,
- array $graph,
- array &$visited,
- array &$recursionStack,
- array $path
- ): ?array {
- if (isset($recursionStack[$nodeId])) {
- // Found a cycle - extract it from the path
- $cycleStart = array_search($nodeId, $path);
-
- return array_merge(array_slice($path, $cycleStart), [$nodeId]);
- }
-
- if (isset($visited[$nodeId])) {
- return null;
- }
+ private function chainDepthErrors(array $variables): array
+ {
+ $variablesById = collect($variables)
+ ->filter(fn ($variable) => is_array($variable)
+ && is_string($variable['id'] ?? null)
+ && is_string($variable['formula'] ?? null))
+ ->keyBy('id');
+ $memo = [];
+
+ $depthFor = function (string $variableId) use (&$depthFor, &$memo, $variablesById): int {
+ if (isset($memo[$variableId])) {
+ return $memo[$variableId];
+ }
- $visited[$nodeId] = true;
- $recursionStack[$nodeId] = true;
- $path[] = $nodeId;
+ $variable = $variablesById->get($variableId);
+ if (! is_array($variable)) {
+ return 0;
+ }
- foreach ($graph[$nodeId] ?? [] as $depId) {
- if (isset($graph[$depId])) {
- $cycle = $this->findCycle($depId, $graph, $visited, $recursionStack, $path);
- if ($cycle !== null) {
- return $cycle;
+ $depth = 1;
+ foreach (FormulaValidator::extractFieldReferences($variable['formula']) as $dependencyId) {
+ if ($variablesById->has($dependencyId)) {
+ $depth = max($depth, 1 + $depthFor($dependencyId));
}
}
- }
-
- unset($recursionStack[$nodeId]);
- return null;
- }
+ return $memo[$variableId] = $depth;
+ };
- /**
- * Check if the dependency chain depth exceeds the maximum.
- */
- private function checkChainDepth(array $variables): ?string
- {
- $resolver = DependencyResolver::fromVariables($variables);
- $depth = $resolver->getMaxChainDepth();
+ $errors = [];
+ foreach ($variables as $index => $variable) {
+ if (! is_array($variable) || ! is_string($variable['id'] ?? null) || ! $variablesById->has($variable['id'])) {
+ continue;
+ }
- if ($depth > self::MAX_CHAIN_DEPTH) {
- return "Variable dependency chain is too deep ({$depth} levels). Maximum allowed is " . self::MAX_CHAIN_DEPTH . '.';
+ $depth = $depthFor($variable['id']);
+ if ($depth > self::MAX_CHAIN_DEPTH) {
+ $errors["computed_variables.{$index}.formula"][] = "Variable dependency chain is too deep ({$depth} levels). Maximum allowed is ".self::MAX_CHAIN_DEPTH.'.';
+ }
}
- return null;
+ return $errors;
}
}
diff --git a/api/app/Rules/FormPropertiesRule.php b/api/app/Rules/FormPropertiesRule.php
index 2013723b2..4c39ff839 100644
--- a/api/app/Rules/FormPropertiesRule.php
+++ b/api/app/Rules/FormPropertiesRule.php
@@ -10,6 +10,7 @@ use App\Rules\PropertyValidators\PropertyValidatorInterface;
use App\Rules\PropertyValidators\SelectOptionsPropertyValidator;
use App\Rules\PropertyValidators\TypePropertyValidator;
use Closure;
+use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Validation\Validator;
@@ -22,7 +23,7 @@ use Illuminate\Validation\Validator;
* This dramatically improves performance for forms with many properties
* by avoiding Laravel's validation framework overhead per property.
*/
-class FormPropertiesRule implements ValidationRule, ValidatorAwareRule
+class FormPropertiesRule implements ValidationRule, ValidatorAwareRule, DataAwareRule
{
/**
* @var PropertyValidatorInterface[]
@@ -33,6 +34,8 @@ class FormPropertiesRule implements ValidationRule, ValidatorAwareRule
private ?Validator $validator = null;
+ private array $data = [];
+
public function __construct(?Workspace $workspace = null)
{
$this->workspace = $workspace;
@@ -56,6 +59,13 @@ class FormPropertiesRule implements ValidationRule, ValidatorAwareRule
return $this;
}
+ public function setData(array $data): static
+ {
+ $this->data = $data;
+
+ return $this;
+ }
+
/**
* Run the validation rule.
*
@@ -71,9 +81,14 @@ class FormPropertiesRule implements ValidationRule, ValidatorAwareRule
$allErrors = [];
$context = [
'properties' => $value,
+ 'computed_variables' => is_array($this->data['computed_variables'] ?? null)
+ ? $this->data['computed_variables']
+ : [],
'workspace' => $this->workspace,
];
+ $seenIds = [];
+
// Single pass through all properties
foreach ($value as $index => $property) {
if (!is_array($property)) {
@@ -81,6 +96,16 @@ class FormPropertiesRule implements ValidationRule, ValidatorAwareRule
continue;
}
+ $propertyId = $property['id'] ?? null;
+ if (is_string($propertyId) && $propertyId !== '') {
+ if (isset($seenIds[$propertyId])) {
+ $firstIndex = $seenIds[$propertyId];
+ $allErrors["properties.{$index}.id"][] = "The field ID [{$propertyId}] is already used by field ".($firstIndex + 1).'.';
+ } else {
+ $seenIds[$propertyId] = $index;
+ }
+ }
+
// Run each validator on this property
foreach ($this->validators as $validator) {
$propertyErrors = $validator->validate($property, $index, $context);
diff --git a/api/app/Rules/PropertyValidators/CorePropertyValidator.php b/api/app/Rules/PropertyValidators/CorePropertyValidator.php
index e38f52eae..3d9214891 100644
--- a/api/app/Rules/PropertyValidators/CorePropertyValidator.php
+++ b/api/app/Rules/PropertyValidators/CorePropertyValidator.php
@@ -2,6 +2,8 @@
namespace App\Rules\PropertyValidators;
+use Illuminate\Support\Str;
+
/**
* Validates core property fields that are common to ALL property types.
*/
@@ -21,16 +23,26 @@ class CorePropertyValidator implements PropertyValidatorInterface
$position = $index + 1; // 1-based for user-friendly messages
// Required fields
- if (!isset($property['id']) || $property['id'] === '' || $property['id'] === null) {
+ if (! isset($property['id']) || $property['id'] === '') {
$errors['id'] = "The form block number {$position} is missing an id.";
+ } elseif (! is_string($property['id'])) {
+ $errors['id'] = "The form block number {$position} id must be a string.";
+ } elseif (Str::length($property['id']) > 255) {
+ $errors['id'] = "The form block number {$position} id must not exceed 255 characters.";
}
- if (!isset($property['name']) || $property['name'] === '' || $property['name'] === null) {
+ if (! isset($property['name']) || $property['name'] === '') {
$errors['name'] = "The form block number {$position} is missing a name.";
+ } elseif (! is_string($property['name'])) {
+ $errors['name'] = "The form block number {$position} name must be a string.";
+ } elseif (Str::length($property['name']) > 500) {
+ $errors['name'] = "The form block number {$position} name must not exceed 500 characters.";
}
- if (!isset($property['type']) || $property['type'] === '' || $property['type'] === null) {
+ if (! isset($property['type']) || $property['type'] === '') {
$errors['type'] = "The form block number {$position} is missing a type.";
+ } elseif (! is_string($property['type'])) {
+ $errors['type'] = "The form block number {$position} type must be a string.";
}
// Boolean fields (nullable)
@@ -64,7 +76,9 @@ class CorePropertyValidator implements PropertyValidatorInterface
}
// Image validation (nested object)
- if (isset($property['image']) && is_array($property['image'])) {
+ if (isset($property['image']) && ! is_array($property['image'])) {
+ $errors['image'] = 'The image configuration must be an object.';
+ } elseif (isset($property['image']) && is_array($property['image'])) {
$image = $property['image'];
if (isset($image['url']) && $image['url'] !== null && !filter_var($image['url'], FILTER_VALIDATE_URL)) {
@@ -72,7 +86,7 @@ class CorePropertyValidator implements PropertyValidatorInterface
}
if (isset($image['alt']) && $image['alt'] !== null) {
- if (!is_string($image['alt']) || strlen($image['alt']) > 125) {
+ if (!is_string($image['alt']) || Str::length($image['alt']) > 125) {
$errors['image.alt'] = "The image alt text must be a string with max 125 characters.";
}
}
@@ -84,7 +98,9 @@ class CorePropertyValidator implements PropertyValidatorInterface
}
// Focal point validation
- if (isset($image['focal_point']) && is_array($image['focal_point'])) {
+ if (isset($image['focal_point']) && ! is_array($image['focal_point'])) {
+ $errors['image.focal_point'] = 'The image focal point must be an object.';
+ } elseif (isset($image['focal_point']) && is_array($image['focal_point'])) {
$focalPoint = $image['focal_point'];
if (isset($focalPoint['x']) && $focalPoint['x'] !== null) {
@@ -101,9 +117,11 @@ class CorePropertyValidator implements PropertyValidatorInterface
}
if (isset($image['brightness']) && $image['brightness'] !== null) {
- if (!is_int($image['brightness']) && !ctype_digit(strval($image['brightness'])) && !preg_match('/^-?\d+$/', strval($image['brightness']))) {
+ $brightness = $image['brightness'];
+ if (! is_int($brightness)
+ && (! is_string($brightness) || preg_match('/^-?\d+$/', $brightness) !== 1)) {
$errors['image.brightness'] = "The image brightness must be an integer.";
- } elseif ((int)$image['brightness'] < -100 || (int)$image['brightness'] > 100) {
+ } elseif ((int) $brightness < -100 || (int) $brightness > 100) {
$errors['image.brightness'] = "The image brightness must be between -100 and 100.";
}
}
diff --git a/api/app/Rules/PropertyValidators/LogicPropertyValidator.php b/api/app/Rules/PropertyValidators/LogicPropertyValidator.php
index d6066917d..7465ed0c8 100644
--- a/api/app/Rules/PropertyValidators/LogicPropertyValidator.php
+++ b/api/app/Rules/PropertyValidators/LogicPropertyValidator.php
@@ -2,12 +2,21 @@
namespace App\Rules\PropertyValidators;
+use App\Service\Forms\FormRegex;
+
/**
- * Validates logic configuration for form properties.
- * Checks that conditions and actions are properly configured.
+ * Validates display logic configuration for form properties.
+ *
+ * Besides validating the condition shape, this validator verifies that every
+ * referenced field or computed variable still exists and has the expected
+ * type. This keeps the browser editor, API and MCP draft validation aligned.
*/
class LogicPropertyValidator implements PropertyValidatorInterface
{
+ public const MAX_CONDITION_DEPTH = 10;
+
+ public const MAX_CONDITION_COUNT = 100;
+
public const ACTIONS_VALUES = [
'show-block',
'hide-block',
@@ -19,12 +28,6 @@ class LogicPropertyValidator implements PropertyValidatorInterface
private static ?array $conditionMappingData = null;
- private bool $isConditionCorrect = true;
- private bool $isActionCorrect = true;
- private array $conditionErrors = [];
- private array $field = [];
- private string $operator = '';
-
public static function getConditionMapping(): array
{
if (self::$conditionMappingData === null) {
@@ -36,227 +39,321 @@ class LogicPropertyValidator implements PropertyValidatorInterface
public function validate(array $property, int $index, array $context): array
{
- $errors = [];
+ if (! array_key_exists('logic', $property) || $property['logic'] === null || $property['logic'] === []) {
+ return [];
+ }
- // Reset state for this validation
- $this->isConditionCorrect = true;
- $this->isActionCorrect = true;
- $this->conditionErrors = [];
- $this->field = $property;
+ if (! is_array($property['logic'])) {
+ return ['logic' => 'The logic configuration must be an object.'];
+ }
- $logic = $property['logic'] ?? null;
+ $logic = $property['logic'];
+ $conditions = $logic['conditions'] ?? null;
+ $actions = $logic['actions'] ?? [];
- // Early bail for empty/null logic
- if (empty($logic) || !is_array($logic)) {
- return $errors;
+ if ($conditions === null && $actions === []) {
+ return [];
}
- // If no conditions, logic is valid (empty logic)
- if (!isset($logic['conditions'])) {
- return $errors;
+ $errors = [];
+ $conditionCount = 0;
+ $references = $this->buildReferenceMap($context);
+
+ if ($conditions === null) {
+ $errors['logic.conditions'] = 'Add at least one condition or remove this logic rule.';
+ } else {
+ $this->validateCondition(
+ $conditions,
+ 'logic.conditions',
+ 1,
+ $conditionCount,
+ $property,
+ $references,
+ $errors,
+ );
}
- // Check conditions
- $this->checkConditions($logic['conditions']);
+ $this->validateActions($actions, $property, $errors);
+
+ return $errors;
+ }
- // Check actions
- $this->checkActions($logic['actions'] ?? null);
+ /**
+ * @param array<string, array{type: string, name: string, kind: string}> $references
+ * @param array<string, string> $errors
+ */
+ private function validateCondition(
+ mixed $condition,
+ string $path,
+ int $depth,
+ int &$conditionCount,
+ array $targetProperty,
+ array $references,
+ array &$errors,
+ ): void {
+ if (! is_array($condition)) {
+ $errors[$path] = 'The condition must be an object.';
- // Build error message if validation failed
- if (!$this->isConditionCorrect || !$this->isActionCorrect) {
- $errors['logic'] = $this->buildErrorMessage($property['name'] ?? 'Unknown');
+ return;
}
- return $errors;
- }
+ $conditionCount++;
+
+ if ($conditionCount > self::MAX_CONDITION_COUNT) {
+ $errors[$path] = 'A logic rule cannot contain more than '.self::MAX_CONDITION_COUNT.' conditions.';
- private function checkBaseCondition(array $condition): void
- {
- if (!isset($condition['value'])) {
- $this->isConditionCorrect = false;
- $this->conditionErrors[] = 'missing condition body';
return;
}
- if (!isset($condition['value']['property_meta'])) {
- $this->isConditionCorrect = false;
- $this->conditionErrors[] = 'missing condition property';
+ if ($depth > self::MAX_CONDITION_DEPTH) {
+ $errors[$path] = 'Condition groups cannot be nested more than '.self::MAX_CONDITION_DEPTH.' levels.';
+
return;
}
- if (!isset($condition['value']['property_meta']['type'])) {
- $this->isConditionCorrect = false;
- $this->conditionErrors[] = 'missing condition property type';
+ if (array_key_exists('operatorIdentifier', $condition)) {
+ $operator = $condition['operatorIdentifier'];
+ if (! in_array($operator, ['and', 'or'], true)) {
+ $errors[$path.'.operatorIdentifier'] = 'The condition group operator must be "and" or "or".';
+ }
+
+ $children = $condition['children'] ?? null;
+ if (! is_array($children) || $children === []) {
+ $errors[$path.'.children'] = 'The condition group must contain at least one condition.';
+
+ return;
+ }
+
+ foreach ($children as $childIndex => $child) {
+ $this->validateCondition(
+ $child,
+ $path.'.children.'.$childIndex,
+ $depth + 1,
+ $conditionCount,
+ $targetProperty,
+ $references,
+ $errors,
+ );
+ }
+
return;
}
- if (!isset($condition['value']['operator'])) {
- $this->isConditionCorrect = false;
- $this->conditionErrors[] = 'missing condition operator';
+ if (! array_key_exists('identifier', $condition)) {
+ $errors[$path] = 'The condition must be a condition group or a field condition.';
+
return;
}
- $typeField = $condition['value']['property_meta']['type'];
- $operator = $condition['value']['operator'];
- $this->operator = $operator;
+ $this->validateLeafCondition($condition, $path, $targetProperty, $references, $errors);
+ }
- // Get mapping once for this check
- $mapping = self::getConditionMapping();
+ /**
+ * @param array<string, array{type: string, name: string, kind: string}> $references
+ * @param array<string, string> $errors
+ */
+ private function validateLeafCondition(
+ array $condition,
+ string $path,
+ array $targetProperty,
+ array $references,
+ array &$errors,
+ ): void {
+ $value = $condition['value'] ?? null;
+ if (! is_array($value)) {
+ $errors[$path.'.value'] = 'The condition body is missing.';
- if (!isset($mapping[$typeField])) {
- $this->isConditionCorrect = false;
- $this->conditionErrors[] = 'configuration not found for condition type';
return;
}
- if (!isset($mapping[$typeField]['comparators'][$operator])) {
- $this->isConditionCorrect = false;
- $this->conditionErrors[] = 'configuration not found for condition operator';
+ $propertyMeta = $value['property_meta'] ?? null;
+ if (! is_array($propertyMeta)) {
+ $errors[$path.'.value.property_meta'] = 'Choose a field or computed variable for this condition.';
+
return;
}
- $comparatorDef = $mapping[$typeField]['comparators'][$operator];
- $needsValue = !empty((array)$comparatorDef);
+ $referenceId = $propertyMeta['id'] ?? null;
+ if (! is_string($referenceId) || $referenceId === '') {
+ $errors[$path.'.value.property_meta.id'] = 'The referenced field or computed variable ID is required.';
+ } elseif ($references !== [] && ($targetProperty['id'] ?? null) === $referenceId) {
+ $errors[$path.'.value.property_meta.id'] = 'A field logic rule cannot reference the same field.';
+ } elseif ($references !== [] && ! isset($references[$referenceId])) {
+ $errors[$path.'.value.property_meta.id'] = "The referenced field or computed variable [{$referenceId}] no longer exists.";
+ }
+
+ $identifier = $condition['identifier'] ?? null;
+ if (! is_string($identifier) || $identifier === '') {
+ $errors[$path.'.identifier'] = 'The condition identifier is required.';
+ } elseif (is_string($referenceId) && $referenceId !== '' && $identifier !== $referenceId) {
+ $errors[$path.'.identifier'] = "The condition identifier must match the referenced item [{$referenceId}].";
+ }
+
+ $referenceType = $propertyMeta['type'] ?? null;
+ if (! is_string($referenceType) || $referenceType === '') {
+ $errors[$path.'.value.property_meta.type'] = 'The referenced field or computed variable type is required.';
- if ($needsValue && !isset($condition['value']['value'])) {
- $this->isConditionCorrect = false;
- $this->conditionErrors[] = 'missing condition value';
return;
}
- if ($needsValue) {
- $type = $comparatorDef['expected_type'] ?? null;
- $value = $condition['value']['value'];
-
- if (is_array($type)) {
- $foundCorrectType = false;
- foreach ($type as $subtype) {
- if ($this->valueHasCorrectType($subtype, $value)) {
- $foundCorrectType = true;
- }
- }
- if (!$foundCorrectType) {
- $this->isConditionCorrect = false;
- $this->conditionErrors[] = 'wrong type of condition value';
- }
- } else {
- if (!$this->valueHasCorrectType($type, $value)) {
- $this->isConditionCorrect = false;
- $this->conditionErrors[] = 'wrong type of condition value';
- }
- }
+ if (is_string($referenceId) && isset($references[$referenceId]) && $references[$referenceId]['type'] !== $referenceType) {
+ $actualType = $references[$referenceId]['type'];
+ $errors[$path.'.value.property_meta.type'] = "The reference type must be [{$actualType}] for [{$referenceId}], not [{$referenceType}].";
}
- }
- private function valueHasCorrectType(?string $type, mixed $value): bool
- {
- if (is_string($value) && str_contains($value, 'mention-field-id')) {
- return true;
+ $mapping = self::getConditionMapping();
+ if (! isset($mapping[$referenceType])) {
+ $errors[$path.'.value.property_meta.type'] = "Logic conditions do not support the reference type [{$referenceType}].";
+
+ return;
}
- if ($type === 'string') {
- $mapping = self::getConditionMapping();
- $fieldType = $this->field['type'] ?? null;
- $format = $mapping[$fieldType]['comparators'][$this->operator]['format'] ?? null;
- if ($format && ($format['type'] ?? null) === 'regex') {
- try {
- preg_match('/' . $value . '/', '');
- return true;
- } catch (\Exception $e) {
- $this->conditionErrors[] = 'invalid regex pattern';
- return false;
- }
- }
+ $operator = $value['operator'] ?? null;
+ if (! is_string($operator) || $operator === '') {
+ $errors[$path.'.value.operator'] = 'Choose an operator for this condition.';
+
+ return;
}
- if (
- ($type === 'string' && gettype($value) !== 'string') ||
- ($type === 'boolean' && !is_bool($value)) ||
- ($type === 'number' && !is_numeric($value)) ||
- ($type === 'object' && !is_array($value))
- ) {
- return false;
+ $comparator = $mapping[$referenceType]['comparators'][$operator] ?? null;
+ if ($comparator === null) {
+ $errors[$path.'.value.operator'] = "The operator [{$operator}] is not available for [{$referenceType}] conditions.";
+
+ return;
}
- return true;
+ if (($comparator['custom_validation_only'] ?? false) === true) {
+ $errors[$path.'.value.operator'] = "The operator [{$operator}] is only available for custom validation rules.";
+
+ return;
+ }
+
+ $needsValue = $comparator !== [];
+ if ($needsValue && ! array_key_exists('value', $value)) {
+ $errors[$path.'.value.value'] = "The operator [{$operator}] requires a comparison value.";
+
+ return;
+ }
+
+ if ($needsValue && ! $this->valueHasCorrectType($comparator, $value['value'])) {
+ $expectedType = $comparator['expected_type'] ?? 'the expected';
+ $expectedType = is_array($expectedType) ? implode(' or ', $expectedType) : $expectedType;
+ $errors[$path.'.value.value'] = "The comparison value for [{$operator}] must be {$expectedType}.";
+ }
}
- private function checkConditions(mixed $conditions): void
+ private function valueHasCorrectType(array $comparator, mixed $value): bool
{
- if (!is_array($conditions)) {
- $this->isConditionCorrect = false;
- $this->conditionErrors[] = 'conditions must be an array';
- return;
+ if (is_string($value) && str_contains($value, 'mention-field-id')) {
+ return true;
}
- if (array_key_exists('operatorIdentifier', $conditions)) {
- if (($conditions['operatorIdentifier'] !== 'and') && ($conditions['operatorIdentifier'] !== 'or')) {
- $this->conditionErrors[] = 'missing operator';
- $this->isConditionCorrect = false;
- return;
- }
+ $expectedTypes = (array) ($comparator['expected_type'] ?? []);
+ if ($expectedTypes === []) {
+ return true;
+ }
- if (isset($conditions['operatorIdentifier']['children'])) {
- $this->conditionErrors[] = 'extra condition';
- $this->isConditionCorrect = false;
- return;
+ foreach ($expectedTypes as $expectedType) {
+ $matches = match ($expectedType) {
+ 'string' => is_string($value),
+ 'boolean' => is_bool($value),
+ 'number' => is_int($value) || is_float($value) || (is_string($value) && is_numeric($value)),
+ 'object' => is_array($value),
+ default => true,
+ };
+
+ if (! $matches) {
+ continue;
}
- if (!isset($conditions['children']) || !is_array($conditions['children'])) {
- $this->conditionErrors[] = 'wrong sub-condition type';
- $this->isConditionCorrect = false;
- return;
+ if (
+ $expectedType === 'string'
+ && ($comparator['format']['type'] ?? null) === 'regex'
+ && ! FormRegex::isValid($value)
+ ) {
+ continue;
}
- foreach ($conditions['children'] as $child) {
- $this->checkConditions($child);
- }
- } elseif (isset($conditions['identifier'])) {
- $this->checkBaseCondition($conditions);
+ return true;
}
+
+ return false;
}
- private function checkActions(mixed $actions): void
+ /** @param array<string, string> $errors */
+ private function validateActions(mixed $actions, array $property, array &$errors): void
{
- if (!is_array($actions) || count($actions) === 0) {
- $this->isActionCorrect = false;
+ if (! is_array($actions) || $actions === []) {
+ $errors['logic.actions'] = 'Choose at least one action for this logic rule.';
+
return;
}
- $layoutBlocks = ['nf-text', 'nf-code', 'nf-page-break', 'nf-divider', 'nf-image', 'nf-video', 'nf-audio'];
- $fieldType = $this->field['type'] ?? null;
- $isHidden = $this->field['hidden'] ?? false;
- $isRequired = $this->field['required'] ?? false;
- $isDisabled = $this->field['disabled'] ?? false;
+ $allowedActions = self::allowedActionsFor($property);
- foreach ($actions as $action) {
- if (
- !in_array($action, self::ACTIONS_VALUES) ||
- (in_array($fieldType, $layoutBlocks) && !in_array($action, ['hide-block', 'show-block'])) ||
- ($isHidden && !in_array($action, ['show-block', 'require-answer'])) ||
- ($isRequired && !in_array($action, ['make-it-optional', 'hide-block', 'disable-block'])) ||
- ($isDisabled && !in_array($action, ['enable-block', 'require-answer', 'make-it-optional']))
- ) {
- $this->isActionCorrect = false;
- break;
+ foreach ($actions as $actionIndex => $action) {
+ $isValid = is_string($action)
+ && in_array($action, self::ACTIONS_VALUES, true)
+ && in_array($action, $allowedActions, true);
+
+ if (! $isValid) {
+ $actionLabel = is_scalar($action) ? (string) $action : 'invalid action';
+ $errors['logic.actions.'.$actionIndex] = "The action [{$actionLabel}] is not valid for this field.";
}
}
}
- private function buildErrorMessage(string $fieldName): string
+ /** @return array<int, string> */
+ public static function allowedActionsFor(array $property): array
+ {
+ $layoutBlocks = ['nf-text', 'nf-code', 'nf-page-break', 'nf-divider', 'nf-image', 'nf-video', 'nf-audio'];
+ $fieldType = $property['type'] ?? null;
+ $isHidden = $property['hidden'] ?? false;
+ $isRequired = $property['required'] ?? false;
+ $isDisabled = $property['disabled'] ?? false;
+
+ return match (true) {
+ in_array($fieldType, $layoutBlocks, true) && $isHidden => ['show-block'],
+ in_array($fieldType, $layoutBlocks, true) => ['hide-block'],
+ $isHidden => ['show-block', 'require-answer'],
+ $isDisabled && $isRequired => ['enable-block', 'make-it-optional'],
+ $isDisabled => ['enable-block', 'require-answer'],
+ $isRequired => ['hide-block', 'disable-block', 'make-it-optional'],
+ default => ['hide-block', 'disable-block', 'require-answer'],
+ };
+ }
+
+ /**
+ * @return array<string, array{type: string, name: string, kind: string}>
+ */
+ private function buildReferenceMap(array $context): array
{
- $message = '';
+ $references = [];
+
+ foreach ($context['properties'] ?? [] as $property) {
+ if (! is_array($property) || ! is_string($property['id'] ?? null) || ! is_string($property['type'] ?? null)) {
+ continue;
+ }
- if (!$this->isConditionCorrect) {
- $message = "The logic conditions for {$fieldName} are not complete.";
- } elseif (!$this->isActionCorrect) {
- $message = "The logic actions for {$fieldName} are not valid.";
+ $references[$property['id']] = [
+ 'type' => $property['type'],
+ 'name' => is_string($property['name'] ?? null) ? $property['name'] : $property['id'],
+ 'kind' => 'field',
+ ];
}
- if (count($this->conditionErrors) > 0) {
- $message .= ' Error detail(s): ' . implode(', ', $this->conditionErrors);
+ foreach ($context['computed_variables'] ?? [] as $variable) {
+ if (! is_array($variable) || ! is_string($variable['id'] ?? null)) {
+ continue;
+ }
+
+ $references[$variable['id']] = [
+ 'type' => 'computed',
+ 'name' => is_string($variable['name'] ?? null) ? $variable['name'] : $variable['id'],
+ 'kind' => 'computed_variable',
+ ];
}
- return $message;
+ return $references;
}
}
diff --git a/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php b/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php
index efe378f42..d4489b9d5 100644
--- a/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php
+++ b/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php
@@ -44,7 +44,7 @@ class PaymentPropertyValidator implements PropertyValidatorInterface
$properties = $context['properties'] ?? [];
$paymentBlockCount = 0;
foreach ($properties as $prop) {
- if (($prop['type'] ?? null) === 'payment') {
+ if (is_array($prop) && ($prop['type'] ?? null) === 'payment') {
$paymentBlockCount++;
}
}
@@ -76,13 +76,15 @@ class PaymentPropertyValidator implements PropertyValidatorInterface
self::$stripeCurrencyCodes = array_column($stripeCurrencies, 'code');
}
- if (!isset($property['currency']) || !in_array(strtoupper($property['currency']), self::$stripeCurrencyCodes)) {
+ if (! is_string($property['currency'] ?? null)
+ || ! in_array(strtoupper($property['currency']), self::$stripeCurrencyCodes, true)) {
$errors['currency'] = 'Currency must be a valid currency';
return $errors;
}
// Stripe account validation
- if (!isset($property['stripe_account_id']) || empty($property['stripe_account_id'])) {
+ $stripeAccountId = $property['stripe_account_id'] ?? null;
+ if ((! is_string($stripeAccountId) && ! is_int($stripeAccountId)) || $stripeAccountId === '') {
$errors['stripe_account_id'] = 'Stripe account is required';
return $errors;
}
@@ -95,7 +97,7 @@ class PaymentPropertyValidator implements PropertyValidatorInterface
}
try {
- $provider = OAuthProvider::find($property['stripe_account_id']);
+ $provider = OAuthProvider::find($stripeAccountId);
if ($provider === null) {
$errors['stripe_account_id'] = 'Failed to validate Stripe account';
return $errors;
@@ -110,10 +112,10 @@ class PaymentPropertyValidator implements PropertyValidatorInterface
$errors['stripe_account_id'] = 'The configured Stripe account is not associated with this workspace';
return $errors;
}
- } catch (\Exception $e) {
+ } catch (\Throwable $e) {
Log::error('Failed to validate Stripe account', [
'error' => $e->getMessage(),
- 'account_id' => $property['stripe_account_id']
+ 'account_id' => $stripeAccountId,
]);
$errors['stripe_account_id'] = 'Failed to validate Stripe account';
return $errors;
diff --git a/api/app/Rules/PropertyValidators/SelectOptionsPropertyValidator.php b/api/app/Rules/PropertyValidators/SelectOptionsPropertyValidator.php
index 91446e24c..9f5909a21 100644
--- a/api/app/Rules/PropertyValidators/SelectOptionsPropertyValidator.php
+++ b/api/app/Rules/PropertyValidators/SelectOptionsPropertyValidator.php
@@ -48,18 +48,20 @@ class SelectOptionsPropertyValidator implements PropertyValidatorInterface
// Validate options array
$options = $property[$type]['options'] ?? null;
-
- if ($options === null) {
- // Options not set - might be using legacy format, skip validation
- return $errors;
- }
+ $allowsCreation = ($property['allow_creation'] ?? false) === true;
if (!is_array($options)) {
- $errors["{$type}.options"] = 'The options must be an array.';
+ if ($allowsCreation && $options === null) {
+ return $errors;
+ }
+
+ $errors["{$type}.options"] = $options === null
+ ? 'At least one option is required.'
+ : 'The options must be an array.';
return $errors;
}
- if (count($options) < 1) {
+ if (count($options) < 1 && ! $allowsCreation) {
$errors["{$type}.options"] = 'At least one option is required.';
return $errors;
}
@@ -89,14 +91,14 @@ class SelectOptionsPropertyValidator implements PropertyValidatorInterface
return $errors;
}
- // Validate option name (always required)
- if (empty($option['name'] ?? null)) {
+ // Option names are the persisted response values and must be usable strings.
+ // In particular, "0" is a valid option name and must not be treated as empty.
+ if (! array_key_exists('name', $option)
+ || $option['name'] === null
+ || (is_string($option['name']) && trim($option['name']) === '')) {
$errors['name'] = 'The option name is required.';
- }
-
- // Validate option id (always required)
- if (empty($option['id'] ?? null)) {
- $errors['id'] = 'The option id is required.';
+ } elseif (!is_string($option['name'])) {
+ $errors['name'] = 'The option name must be a string.';
}
// Validate option image based on display mode
diff --git a/api/app/Rules/PropertyValidators/TypePropertyValidator.php b/api/app/Rules/PropertyValidators/TypePropertyValidator.php
index 02e951539..5d882c819 100644
--- a/api/app/Rules/PropertyValidators/TypePropertyValidator.php
+++ b/api/app/Rules/PropertyValidators/TypePropertyValidator.php
@@ -2,6 +2,8 @@
namespace App\Rules\PropertyValidators;
+use App\Service\Forms\AgentFormFieldCatalog;
+
/**
* Validates type-specific property fields based on the property type.
* Only validates fields that are relevant to each specific type.
@@ -77,10 +79,16 @@ class TypePropertyValidator implements PropertyValidatorInterface
$errors = [];
$type = $property['type'] ?? null;
- if (!$type) {
+ if (! is_string($type) || $type === '') {
return $errors; // Type validation handled by CorePropertyValidator
}
+ if (! in_array($type, AgentFormFieldCatalog::types(), true)) {
+ $errors['type'] = "The field type [{$type}] is not supported.";
+
+ return $errors;
+ }
+
// Skip layout blocks (nf-*) - they have no type-specific rules
if (str_starts_with($type, 'nf-')) {
return $errors;
diff --git a/api/app/Service/Forms/AgentFormDefinition.php b/api/app/Service/Forms/AgentFormDefinition.php
index 5b7c3f9b7..0315128e8 100644
--- a/api/app/Service/Forms/AgentFormDefinition.php
+++ b/api/app/Service/Forms/AgentFormDefinition.php
@@ -70,15 +70,16 @@ class AgentFormDefinition
'analytics',
];
- public function __construct(private readonly FormDataNormalizer $normalizer)
- {
+ public function __construct(
+ private readonly FormDataNormalizer $normalizer,
+ private readonly FormValidationIssueMapper $issueMapper,
+ ) {
}
public function normalizeAndValidate(array $definition, ?Workspace $workspace = null): array
{
$definition = $this->migrate($definition);
$definition = array_replace($this->defaults(), $definition);
- $definition = $this->normalizeAliases($definition);
$definition = $this->normalizer->normalize($definition, backfillPropertyIds: true);
$definition['properties'] = collect($definition['properties'])->map(function ($property) {
if (! is_array($property)) {
@@ -129,24 +130,11 @@ class AgentFormDefinition
]);
}
- $propertyIds = collect($definition['properties'] ?? [])
- ->pluck('id')
- ->filter(fn ($id) => is_string($id) && $id !== '');
-
- if ($propertyIds->duplicates()->isNotEmpty()) {
- throw ValidationException::withMessages([
- 'properties' => ['Every form block must have a unique id.'],
- ]);
- }
-
- Validator::make($definition, [
+ $validator = Validator::make($definition, [
'schema_version' => ['required', 'integer', Rule::in([self::SCHEMA_VERSION])],
'title' => ['required', 'string', 'max:255'],
'visibility' => ['required', Rule::in(Form::VISIBILITY)],
- 'properties' => ['required', 'array', 'min:1', 'max:500', new FormPropertiesRule($workspace)],
- 'properties.*.id' => ['required', 'string', 'max:255'],
- 'properties.*.name' => ['required', 'string', 'max:500'],
- 'properties.*.type' => ['required', Rule::in(FieldCatalog::types())],
+ 'properties' => ['required', 'array', 'min:1', 'max:'.FormStructureValidator::MAX_PROPERTY_COUNT, new FormPropertiesRule($workspace)],
'properties.*.help' => ['nullable', 'string'],
'properties.*.image.url' => ['nullable', new PublicMediaUrlRule()],
'computed_variables' => ['nullable', 'array', new ComputedVariablesRule()],
@@ -211,7 +199,16 @@ class AgentFormDefinition
'size.in' => 'size must be one of: sm, md, lg.',
'border_radius.in' => 'border_radius must be one of: none, small, full.',
'dark_mode.in' => 'dark_mode must be one of: auto, light, dark.',
- ])->validate();
+ ]);
+
+ if ($validator->passes()) {
+ return;
+ }
+
+ $errors = $validator->errors()->toArray();
+ $pathErrors = $this->issueMapper->pathErrors($errors);
+
+ throw ValidationException::withMessages($pathErrors !== [] ? $pathErrors : $errors);
}
public function defaults(): array
@@ -304,7 +301,13 @@ class AgentFormDefinition
'maxItems' => 500,
'items' => ['$ref' => '#/$defs/block'],
],
- 'computed_variables' => ['type' => 'array', 'default' => []],
+ 'computed_variables' => [
+ 'type' => 'array',
+ 'maxItems' => ComputedVariablesRule::MAX_VARIABLE_COUNT,
+ 'items' => ['$ref' => '#/$defs/computedVariable'],
+ 'default' => [],
+ 'description' => 'Calculated values available to other formulas and display logic. Formula references use braces, for example {budget} * 1.2.',
+ ],
'language' => ['type' => 'string', 'enum' => Form::LANGUAGES, 'default' => 'en'],
'font_family' => ['type' => ['string', 'null']],
'theme' => ['type' => 'string', 'enum' => Form::THEMES, 'default' => 'default'],
@@ -372,6 +375,109 @@ class AgentFormDefinition
'placeholder' => ['type' => ['string', 'null']],
'width' => ['type' => 'string', 'enum' => ['full', '1/2', '1/3', '2/3', '1/4', '3/4'], 'default' => 'full'],
'image' => ['$ref' => '#/$defs/blockImage'],
+ 'logic' => [
+ 'anyOf' => [
+ ['$ref' => '#/$defs/displayLogic'],
+ ['type' => 'null'],
+ ],
+ 'description' => 'Optional conditional behavior for this target block. Empty or safely invalid logic is removed during normalization.',
+ ],
+ ],
+ ],
+ 'computedVariable' => [
+ 'type' => 'object',
+ 'additionalProperties' => true,
+ 'required' => ['id', 'name', 'formula'],
+ 'properties' => [
+ 'id' => [
+ 'type' => 'string',
+ 'pattern' => '^cv_',
+ 'description' => 'Unique technical identifier beginning with cv_. It must not duplicate a block ID.',
+ ],
+ 'name' => ['type' => 'string', 'minLength' => 1, 'maxLength' => 100],
+ 'formula' => [
+ 'type' => 'string',
+ 'minLength' => 1,
+ 'maxLength' => 2000,
+ 'description' => 'Expression referencing block or computed-variable IDs with braces, for example {budget} * 1.2.',
+ ],
+ 'result_type' => ['type' => ['string', 'null'], 'enum' => ['number', 'text', 'auto', null]],
+ ],
+ ],
+ 'displayLogic' => [
+ 'type' => 'object',
+ 'additionalProperties' => true,
+ 'required' => ['conditions', 'actions'],
+ 'properties' => [
+ 'conditions' => ['$ref' => '#/$defs/logicCondition'],
+ 'actions' => [
+ 'type' => 'array',
+ 'minItems' => 1,
+ 'uniqueItems' => true,
+ 'items' => ['type' => 'string', 'enum' => \App\Rules\PropertyValidators\LogicPropertyValidator::ACTIONS_VALUES],
+ 'description' => 'Allowed actions depend on the target block state and type; validate_form_definition returns the exact path for an incompatible action.',
+ ],
+ ],
+ ],
+ 'logicCondition' => [
+ 'oneOf' => [
+ ['$ref' => '#/$defs/logicConditionGroup'],
+ ['$ref' => '#/$defs/logicLeafCondition'],
+ ],
+ ],
+ 'logicConditionGroup' => [
+ 'type' => 'object',
+ 'additionalProperties' => true,
+ 'required' => ['operatorIdentifier', 'children'],
+ 'properties' => [
+ 'operatorIdentifier' => ['type' => 'string', 'enum' => ['and', 'or']],
+ 'children' => [
+ 'type' => 'array',
+ 'minItems' => 1,
+ 'maxItems' => \App\Rules\PropertyValidators\LogicPropertyValidator::MAX_CONDITION_COUNT,
+ 'items' => ['$ref' => '#/$defs/logicCondition'],
+ ],
+ ],
+ ],
+ 'logicLeafCondition' => [
+ 'type' => 'object',
+ 'additionalProperties' => true,
+ 'required' => ['identifier', 'value'],
+ 'properties' => [
+ 'identifier' => [
+ 'type' => 'string',
+ 'minLength' => 1,
+ 'description' => 'ID of the referenced field or computed variable. It must match value.property_meta.id.',
+ ],
+ 'value' => ['$ref' => '#/$defs/logicConditionValue'],
+ ],
+ ],
+ 'logicConditionValue' => [
+ 'type' => 'object',
+ 'additionalProperties' => true,
+ 'required' => ['operator', 'property_meta'],
+ 'properties' => [
+ 'operator' => [
+ 'type' => 'string',
+ 'enum' => FieldCatalog::logicOperators(),
+ 'description' => 'Comparison operator compatible with property_meta.type. Consult operators_by_reference_type in the field catalog.',
+ ],
+ 'property_meta' => [
+ 'type' => 'object',
+ 'additionalProperties' => true,
+ 'required' => ['id', 'type'],
+ 'properties' => [
+ 'id' => ['type' => 'string', 'minLength' => 1],
+ 'type' => [
+ 'type' => 'string',
+ 'enum' => array_keys(FieldCatalog::logicOperatorsByReferenceType()),
+ 'description' => 'Use computed when referencing a computed variable; otherwise use the referenced field type.',
+ ],
+ ],
+ ],
+ 'value' => [
+ 'description' => 'Comparison value. Omit only for operators such as is_empty, is_not_empty, is_checked, or is_not_checked.',
+ ],
],
],
'blockImage' => [
@@ -415,16 +521,4 @@ class AgentFormDefinition
return $definition;
}
- private function normalizeAliases(array $definition): array
- {
- $definition['properties'] = collect($definition['properties'] ?? [])->map(function ($property) {
- if (! is_array($property) || ! isset(FieldCatalog::ALIASES[$property['type'] ?? ''])) {
- return $property;
- }
-
- return array_replace($property, FieldCatalog::ALIASES[$property['type']]);
- })->values()->all();
-
- return $definition;
- }
}
diff --git a/api/app/Service/Forms/AgentFormFieldCatalog.php b/api/app/Service/Forms/AgentFormFieldCatalog.php
index 0e10633a3..5368e5aa9 100644
--- a/api/app/Service/Forms/AgentFormFieldCatalog.php
+++ b/api/app/Service/Forms/AgentFormFieldCatalog.php
@@ -2,6 +2,8 @@
namespace App\Service\Forms;
+use App\Rules\PropertyValidators\LogicPropertyValidator;
+
class AgentFormFieldCatalog
{
public const INPUT_TYPES = [
@@ -42,11 +44,73 @@ class AgentFormFieldCatalog
'toggle_switch' => ['type' => 'checkbox', 'use_toggle_switch' => true],
];
+ public const LEGACY_ALIASES = [
+ 'textarea' => ['type' => 'text', 'multi_lines' => true],
+ 'long_text' => ['type' => 'text', 'multi_lines' => true],
+ 'multi_lines' => ['type' => 'text', 'multi_lines' => true],
+ 'short_text' => ['type' => 'text', 'multi_lines' => false],
+ 'multiselect' => ['type' => 'multi_select'],
+ 'phone' => ['type' => 'phone_number'],
+ 'file_upload' => ['type' => 'files'],
+ 'file' => ['type' => 'files'],
+ 'hidden' => ['type' => 'text', 'hidden' => true],
+ 'divider' => ['type' => 'nf-divider'],
+ 'nf_text' => ['type' => 'nf-text'],
+ 'header' => ['type' => 'nf-text'],
+ 'info' => ['type' => 'nf-text'],
+ 'paragraph' => ['type' => 'nf-text'],
+ 'section_break' => ['type' => 'nf-text'],
+ 'html' => ['type' => 'nf-text'],
+ 'page_break' => ['type' => 'nf-page-break'],
+ 'nf-page_break' => ['type' => 'nf-page-break'],
+ 'radio_button' => ['type' => 'select', 'without_dropdown' => true],
+ 'datetime-local' => ['type' => 'date', 'with_time' => true],
+ 'date_range' => ['type' => 'date', 'date_range' => true],
+ ];
+
+ public const OBSOLETE_NON_FIELD_TYPES = [
+ 'submit',
+ 'submit_button',
+ 'nf-submit',
+ 'captcha',
+ 'use_captcha',
+ ];
+
public static function types(): array
{
return [...self::INPUT_TYPES, ...self::LAYOUT_TYPES];
}
+ public static function normalizationAliases(): array
+ {
+ return array_merge(self::ALIASES, self::LEGACY_ALIASES);
+ }
+
+ /** @return array<string, array<int, string>> */
+ public static function logicOperatorsByReferenceType(): array
+ {
+ return collect(LogicPropertyValidator::getConditionMapping())
+ ->map(function (array $mapping): array {
+ return collect($mapping['comparators'] ?? [])
+ ->reject(fn (mixed $config): bool => is_array($config)
+ && ($config['custom_validation_only'] ?? false) === true)
+ ->keys()
+ ->values()
+ ->all();
+ })
+ ->all();
+ }
+
+ /** @return array<int, string> */
+ public static function logicOperators(): array
+ {
+ return collect(self::logicOperatorsByReferenceType())
+ ->flatten()
+ ->unique()
+ ->values()
+ ->all();
+ }
+
public static function reference(): array
{
return [
@@ -62,6 +126,7 @@ class AgentFormFieldCatalog
'required' => 'Boolean, defaults to false.',
'placeholder' => 'Optional placeholder.',
'width' => 'One of full, 1/2, 1/3, 2/3, 1/4, 3/4. Defaults to full.',
+ 'logic' => 'Optional display logic object described in display_logic. Empty or invalid logic that can be removed safely is discarded during normalization.',
],
'type_properties' => [
'text' => ['multi_lines', 'max_char_limit', 'show_char_limit', 'secret_input', 'input_mask'],
@@ -115,6 +180,44 @@ class AgentFormFieldCatalog
'uppercase_labels' => 'Boolean.',
'show_progress_bar' => 'Boolean.',
],
+ 'computed_variables' => [
+ 'description' => 'Optional calculated values that formulas and display logic may reference. Invalid variables and variables depending on them are removed during normalization.',
+ 'item' => [
+ 'id' => 'Required unique technical identifier beginning with cv_. It must not duplicate a block ID.',
+ 'name' => 'Required unique human-readable name, at most 100 characters.',
+ 'formula' => 'Required expression, at most 2000 characters. Reference a field or another variable with braces, for example {budget} * 1.2.',
+ 'result_type' => 'Optional hint: number, text, or auto.',
+ ],
+ 'example' => [
+ 'id' => 'cv_priority_score',
+ 'name' => 'Priority score',
+ 'formula' => '{budget} * 1.2',
+ 'result_type' => 'number',
+ ],
+ ],
+ 'display_logic' => [
+ 'description' => 'Attach logic to the target block. Conditions may reference another field or a computed variable, never the target field itself.',
+ 'shape' => [
+ 'conditions' => 'A leaf condition or a group with operatorIdentifier and/or plus a non-empty children array. Groups may be nested up to 10 levels and contain at most 100 total nodes.',
+ 'actions' => LogicPropertyValidator::ACTIONS_VALUES,
+ ],
+ 'operators_by_reference_type' => self::logicOperatorsByReferenceType(),
+ 'computed_variable_reference_type' => 'Use property_meta.type computed for every computed-variable condition.',
+ 'example' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [[
+ 'identifier' => 'cv_priority_score',
+ 'value' => [
+ 'operator' => 'greater_than',
+ 'property_meta' => ['id' => 'cv_priority_score', 'type' => 'computed'],
+ 'value' => 10000,
+ ],
+ ]],
+ ],
+ 'actions' => ['show-block'],
+ ],
+ ],
'authoring_guidelines' => AgentFormAuthoringGuide::reference(),
'block_media' => [
'property' => 'image',
diff --git a/api/app/Service/Forms/FormDataNormalizer.php b/api/app/Service/Forms/FormDataNormalizer.php
index 0119dd85d..f5356e412 100644
--- a/api/app/Service/Forms/FormDataNormalizer.php
+++ b/api/app/Service/Forms/FormDataNormalizer.php
@@ -2,55 +2,256 @@
namespace App\Service\Forms;
+use App\Rules\ComputedVariablesRule;
+use App\Rules\PropertyValidators\LogicPropertyValidator;
+use App\Rules\PropertyValidators\TypePropertyValidator;
+use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Stevebauman\Purify\Facades\Purify;
class FormDataNormalizer
{
+ private const PROPERTY_BOOLEAN_FIELDS = [
+ 'hidden',
+ 'required',
+ 'disabled',
+ 'multiple',
+ 'use_toggle_switch',
+ 'multi_lines',
+ 'show_char_limit',
+ 'secret_input',
+ 'with_time',
+ 'date_range',
+ 'prefill_today',
+ 'disable_past_dates',
+ 'disable_future_dates',
+ 'allow_creation',
+ 'without_dropdown',
+ 'generates_uuid',
+ 'generates_auto_increment_id',
+ 'hide_field_name',
+ 'shuffle_options',
+ 'use_focused_selector',
+ 'file_upload',
+ 'camera_upload',
+ ];
+
/**
* Normalize data shared by HTTP requests, MCP tools, and draft claims.
*/
- public function normalize(array $data, bool $backfillPropertyIds = false): array
+ public function normalize(array $data, bool $backfillPropertyIds = true): array
{
if (isset($data['title']) && is_string($data['title'])) {
$data['title'] = Str::substr(trim($data['title']), 0, 255);
}
if (isset($data['properties']) && is_array($data['properties'])) {
+ $data = $this->migrateObsoleteNonFields($data);
$data['properties'] = $this->normalizeProperties($data['properties'], $backfillPropertyIds);
+
+ if (array_key_exists('computed_variables', $data)) {
+ $computedVariables = is_array($data['computed_variables'])
+ ? array_values($data['computed_variables'])
+ : [];
+ $data['computed_variables'] = $this->normalizeComputedVariables(
+ $computedVariables,
+ $data['properties'],
+ );
+ }
+
+ $data['properties'] = $this->normalizeRecoverableLogic(
+ $data['properties'],
+ is_array($data['computed_variables'] ?? null) ? $data['computed_variables'] : [],
+ );
}
return $data;
}
- public function normalizeProperties(array $properties, bool $backfillIds = false): array
+ private function migrateObsoleteNonFields(array $data): array
{
- return collect($properties)->map(function ($property) use ($backfillIds) {
- if (! is_array($property)) {
- return $property;
+ foreach ($data['properties'] as $property) {
+ if (! is_array($property) || ! is_string($property['type'] ?? null)) {
+ continue;
}
- if ($backfillIds && empty($property['id'])) {
- $property['id'] = Str::uuid()->toString();
+ if (in_array($property['type'], ['captcha', 'use_captcha'], true)) {
+ $data['use_captcha'] = true;
}
- if (isset($property['name']) && is_string($property['name'])) {
- $property['name'] = trim(strip_tags($property['name']));
+ if (! in_array($property['type'], ['submit', 'submit_button', 'nf-submit'], true)
+ || (is_string($data['submit_button_text'] ?? null) && trim($data['submit_button_text']) !== '')) {
+ continue;
}
- if (isset($property['help']) && is_string($property['help'])) {
- $property['help'] = Purify::clean($property['help']);
+ foreach (['submit_button_text', 'button_text'] as $field) {
+ if (is_string($property[$field] ?? null) && trim($property[$field]) !== '') {
+ $data['submit_button_text'] = Str::substr(trim($property[$field]), 0, 50);
- if (strip_tags($property['help']) === '') {
- $property['help'] = null;
+ break;
}
}
+ }
- return $this->normalizeSelectOptionIds($property);
- })->values()->all();
+ return $data;
}
- private function normalizeSelectOptionIds(array $property): array
+ public function normalizeProperties(array $properties, bool $backfillIds = true): array
+ {
+ $aliases = AgentFormFieldCatalog::normalizationAliases();
+
+ return collect($properties)
+ ->filter(fn ($property) => is_array($property))
+ ->reject(fn (array $property) => is_string($property['type'] ?? null)
+ && in_array($property['type'], AgentFormFieldCatalog::OBSOLETE_NON_FIELD_TYPES, true))
+ ->map(function (array $property) use ($aliases, $backfillIds) {
+ $propertyType = $property['type'] ?? null;
+ if (is_string($propertyType) && isset($aliases[$propertyType])) {
+ if ($propertyType === 'html'
+ && ! isset($property['content'])
+ && is_string($property['html_content'] ?? null)) {
+ $property['content'] = $property['html_content'];
+ }
+
+ $property = array_replace($property, $aliases[$propertyType]);
+ }
+
+ if ($backfillIds
+ && (! array_key_exists('id', $property) || $property['id'] === null || $property['id'] === '')) {
+ $property['id'] = Str::uuid()->toString();
+ }
+
+ if (isset($property['name']) && is_string($property['name'])) {
+ $property['name'] = Str::substr(trim(strip_tags($property['name'])), 0, 500);
+ }
+
+ if (isset($property['help']) && is_string($property['help'])) {
+ $property['help'] = Purify::clean($property['help']);
+
+ if (strip_tags($property['help']) === '') {
+ $property['help'] = null;
+ }
+ }
+
+ foreach (self::PROPERTY_BOOLEAN_FIELDS as $field) {
+ if (! array_key_exists($field, $property)) {
+ continue;
+ }
+
+ if (in_array($property[$field], [0, 1, '0', '1'], true)) {
+ $property[$field] = (bool) (int) $property[$field];
+ } elseif (is_string($property[$field])
+ && in_array(Str::lower($property[$field]), ['true', 'false'], true)) {
+ $property[$field] = Str::lower($property[$field]) === 'true';
+ } elseif ($property[$field] !== null && ! is_bool($property[$field])) {
+ unset($property[$field]);
+ }
+ }
+
+ $property = $this->normalizeOptionalPropertySettings($property);
+ $property = $this->normalizeTypeSpecificSettings($property);
+
+ return $this->normalizeSelectOptions($property);
+ })
+ ->values()
+ ->all();
+ }
+
+ private function normalizeOptionalPropertySettings(array $property): array
+ {
+ if (isset($property['width'])
+ && ! in_array($property['width'], ['full', '1/2', '1/3', '2/3', '3/4', '1/4'], true)) {
+ $property['width'] = 'full';
+ }
+
+ if (isset($property['help_position'])
+ && ! in_array($property['help_position'], ['below_input', 'above_input'], true)) {
+ unset($property['help_position']);
+ }
+
+ if (isset($property['align'])
+ && ! in_array($property['align'], ['left', 'center', 'right', 'justify'], true)) {
+ unset($property['align']);
+ }
+
+ if (! array_key_exists('image', $property) || $property['image'] === null) {
+ return $property;
+ }
+
+ if (! is_array($property['image'])) {
+ unset($property['image']);
+
+ return $property;
+ }
+
+ $image = $property['image'];
+ if (isset($image['url'])
+ && (! is_string($image['url']) || filter_var($image['url'], FILTER_VALIDATE_URL) === false)) {
+ unset($property['image']);
+
+ return $property;
+ }
+
+ if (isset($image['alt'])) {
+ if (is_string($image['alt'])) {
+ $image['alt'] = Str::substr($image['alt'], 0, 125);
+ } else {
+ unset($image['alt']);
+ }
+ }
+
+ if (isset($image['layout'])
+ && ! in_array($image['layout'], ['between', 'left-small', 'right-small', 'left-split', 'right-split', 'background'], true)) {
+ unset($image['layout']);
+ }
+
+ if (isset($image['focal_point']) && ! is_array($image['focal_point'])) {
+ unset($image['focal_point']);
+ } elseif (isset($image['focal_point'])) {
+ foreach (['x', 'y'] as $axis) {
+ $value = $image['focal_point'][$axis] ?? null;
+ if ($value !== null && (! is_numeric($value) || $value < 0 || $value > 100)) {
+ unset($image['focal_point'][$axis]);
+ }
+ }
+
+ if ($image['focal_point'] === []) {
+ unset($image['focal_point']);
+ }
+ }
+
+ if (isset($image['brightness'])) {
+ $brightness = $image['brightness'];
+ if ((! is_int($brightness) && (! is_string($brightness) || preg_match('/^-?\d+$/', $brightness) !== 1))
+ || (int) $brightness < -100
+ || (int) $brightness > 100) {
+ unset($image['brightness']);
+ }
+ }
+
+ if (isset($image['fade']) && ! is_bool($image['fade'])) {
+ unset($image['fade']);
+ }
+
+ $property['image'] = $image;
+
+ return $property;
+ }
+
+ private function normalizeTypeSpecificSettings(array $property): array
+ {
+ $errors = (new TypePropertyValidator())->validate($property, 0, []);
+
+ foreach (array_keys($errors) as $field) {
+ if ($field !== 'type') {
+ unset($property[$field]);
+ }
+ }
+
+ return $property;
+ }
+
+ private function normalizeSelectOptions(array $property): array
{
$type = $property['type'] ?? null;
@@ -58,22 +259,240 @@ class FormDataNormalizer
return $property;
}
+ $validDisplayModes = ['text_only', 'text_and_image', 'image_only'];
+ if (! in_array($property['option_display_mode'] ?? 'text_only', $validDisplayModes, true)) {
+ $property['option_display_mode'] = 'text_only';
+ }
+
+ if (isset($property['option_image_size'])
+ && ! in_array($property['option_image_size'], ['sm', 'md', 'lg'], true)) {
+ unset($property['option_image_size']);
+ }
+
if (! isset($property[$type]['options']) || ! is_array($property[$type]['options'])) {
+ if (($property['allow_creation'] ?? false) === true) {
+ $property[$type] = is_array($property[$type] ?? null) ? $property[$type] : [];
+ $property[$type]['options'] = [];
+ $property['option_display_mode'] = 'text_only';
+ }
+
return $property;
}
- $property[$type]['options'] = array_map(function ($option) {
- if (! is_array($option) || ! empty($option['id'] ?? null)) {
+ $property[$type]['options'] = collect($property[$type]['options'])
+ ->map(function ($option) {
+ if (is_array($option) && is_string($option['name'] ?? null)) {
+ $option['name'] = trim($option['name']);
+ }
+
+ return $option;
+ })
+ ->filter(fn ($option) => is_array($option)
+ && is_string($option['name'] ?? null)
+ && $option['name'] !== '')
+ ->map(function (array $option) {
+ if (! is_string($option['id'] ?? null) || $option['id'] === '') {
+ $option['id'] = $option['name'];
+ }
+
+ if (array_key_exists('image', $option)
+ && (! is_string($option['image'])
+ || filter_var($option['image'], FILTER_VALIDATE_URL) === false)) {
+ unset($option['image']);
+ }
+
return $option;
+ })
+ ->values()
+ ->all();
+
+ if (in_array($property['option_display_mode'] ?? 'text_only', ['text_and_image', 'image_only'], true)) {
+ $hasUnusableImage = collect($property[$type]['options'])->contains(
+ fn (array $option) => ! is_string($option['image'] ?? null)
+ || filter_var($option['image'], FILTER_VALIDATE_URL) === false,
+ );
+
+ if ($hasUnusableImage) {
+ $property['option_display_mode'] = 'text_only';
}
+ }
- if (! empty($option['name'] ?? null) && is_string($option['name'])) {
- $option['id'] = $option['name'];
+ return $property;
+ }
+
+ private function normalizeRecoverableLogic(array $properties, array $computedVariables): array
+ {
+ $references = $this->buildReferenceMap($properties, $computedVariables);
+ $context = [
+ 'properties' => $properties,
+ 'computed_variables' => $computedVariables,
+ ];
+ $validator = new LogicPropertyValidator();
+
+ foreach ($properties as $index => &$property) {
+ if (! is_array($property) || ! array_key_exists('logic', $property)) {
+ continue;
}
- return $option;
- }, $property[$type]['options']);
+ if (! is_array($property['logic'])) {
+ unset($property['logic']);
- return $property;
+ continue;
+ }
+
+ $conditions = $property['logic']['conditions'] ?? null;
+ $actions = $property['logic']['actions'] ?? [];
+ if ($conditions === null && $actions === []) {
+ unset($property['logic']);
+
+ continue;
+ }
+
+ if (array_key_exists('conditions', $property['logic'])) {
+ $this->repairConditionReferences(
+ $property['logic']['conditions'],
+ $property['id'] ?? null,
+ $references,
+ );
+ }
+
+ if (is_array($property['logic']['actions'] ?? null)) {
+ $allowedActions = LogicPropertyValidator::allowedActionsFor($property);
+ $property['logic']['actions'] = collect($property['logic']['actions'])
+ ->filter(fn ($action) => is_string($action) && in_array($action, $allowedActions, true))
+ ->unique()
+ ->values()
+ ->all();
+ }
+
+ if ($validator->validate($property, $index, $context) !== []) {
+ unset($property['logic']);
+ }
+ }
+ unset($property);
+
+ return $properties;
+ }
+
+ /** @param array<string, array{type: string}> $references */
+ private function repairConditionReferences(
+ mixed &$condition,
+ mixed $targetId,
+ array $references,
+ int $depth = 1,
+ ): void {
+ if (! is_array($condition) || $depth > LogicPropertyValidator::MAX_CONDITION_DEPTH) {
+ return;
+ }
+
+ if (array_key_exists('operatorIdentifier', $condition)) {
+ if (! is_array($condition['children'] ?? null)) {
+ return;
+ }
+
+ foreach ($condition['children'] as &$child) {
+ $this->repairConditionReferences($child, $targetId, $references, $depth + 1);
+ }
+ unset($child);
+
+ return;
+ }
+
+ $referenceId = $condition['value']['property_meta']['id'] ?? null;
+ if (! is_string($referenceId) || $referenceId === '' || $referenceId === $targetId || ! isset($references[$referenceId])) {
+ return;
+ }
+
+ $condition['identifier'] = $referenceId;
+ $condition['value']['property_meta']['type'] = $references[$referenceId]['type'];
+
+ if ($references[$referenceId]['type'] !== 'checkbox') {
+ return;
+ }
+
+ $condition['value']['operator'] = match ($condition['value']['operator'] ?? null) {
+ 'equals' => 'is_checked',
+ 'does_not_equal' => 'is_not_checked',
+ default => $condition['value']['operator'] ?? null,
+ };
+ if (in_array($condition['value']['operator'], ['is_checked', 'is_not_checked'], true)) {
+ unset($condition['value']['value']);
+ }
+ }
+
+ /** @return array<string, array{type: string}> */
+ private function buildReferenceMap(array $properties, array $computedVariables): array
+ {
+ $references = [];
+
+ foreach ($properties as $property) {
+ if (is_array($property) && is_string($property['id'] ?? null) && is_string($property['type'] ?? null)) {
+ $references[$property['id']] = ['type' => $property['type']];
+ }
+ }
+
+ foreach ($computedVariables as $variable) {
+ if (is_array($variable) && is_string($variable['id'] ?? null)) {
+ $references[$variable['id']] = ['type' => 'computed'];
+ }
+ }
+
+ return $references;
+ }
+
+ private function normalizeComputedVariables(array $variables, array $properties): array
+ {
+ $variables = collect(array_slice($variables, 0, ComputedVariablesRule::MAX_VARIABLE_COUNT))
+ ->map(function ($variable) {
+ if (! is_array($variable)) {
+ return $variable;
+ }
+
+ foreach (['name', 'formula'] as $field) {
+ if (is_string($variable[$field] ?? null)) {
+ $variable[$field] = trim($variable[$field]);
+ }
+ }
+
+ return $variable;
+ })
+ ->values()
+ ->all();
+
+ do {
+ $invalidIndexes = $this->invalidComputedVariableIndexes($variables, $properties);
+ if ($invalidIndexes === []) {
+ return $variables;
+ }
+
+ foreach ($invalidIndexes as $index) {
+ unset($variables[$index]);
+ }
+
+ $variables = array_values($variables);
+ } while (true);
+ }
+
+ /** @return array<int, int> */
+ private function invalidComputedVariableIndexes(array $variables, array $properties): array
+ {
+ $validator = Validator::make([
+ 'properties' => $properties,
+ 'computed_variables' => $variables,
+ ], [
+ 'computed_variables' => ['nullable', 'array', new ComputedVariablesRule()],
+ ]);
+ $validator->passes();
+
+ return collect($validator->errors()->keys())
+ ->map(function (string $path): ?int {
+ return preg_match('/^computed_variables\.(\d+)(?:\.|$)/', $path, $matches) === 1
+ ? (int) $matches[1]
+ : null;
+ })
+ ->filter(fn (?int $index) => $index !== null)
+ ->unique()
+ ->values()
+ ->all();
}
}
diff --git a/api/app/Service/Forms/FormLogicConditionChecker.php b/api/app/Service/Forms/FormLogicConditionChecker.php
index 6f522a1b0..1895de0ee 100644
--- a/api/app/Service/Forms/FormLogicConditionChecker.php
+++ b/api/app/Service/Forms/FormLogicConditionChecker.php
@@ -718,23 +718,17 @@ class FormLogicConditionChecker
case 'content_length_less_than_or_equal_to':
return $this->checkLength($propertyCondition, $value, '<=');
case 'matches_regex':
- try {
- if (!is_string($propertyCondition['value']) || !is_string($value)) {
- return false;
- }
- return (bool) preg_match('/' . $propertyCondition['value'] . '/', $value);
- } catch (\Exception $e) {
+ if (! is_string($propertyCondition['value']) || ! is_string($value)) {
return false;
}
+ return FormRegex::matches($propertyCondition['value'], $value) ?? false;
case 'does_not_match_regex':
- try {
- if (!is_string($propertyCondition['value']) || !is_string($value)) {
- return true;
- }
- return !(bool) preg_match('/' . $propertyCondition['value'] . '/', $value);
- } catch (\Exception $e) {
+ if (! is_string($propertyCondition['value']) || ! is_string($value)) {
return true;
}
+ $matches = FormRegex::matches($propertyCondition['value'], $value);
+
+ return $matches === null ? true : ! $matches;
case 'exists_in_submissions':
return $this->checkExistsInSubmissions($propertyCondition, $value);
case 'does_not_exist_in_submissions':
diff --git a/api/app/Service/Forms/FormRegex.php b/api/app/Service/Forms/FormRegex.php
new file mode 100644
index 000000000..a8fae2e6d
--- /dev/null
+++ b/api/app/Service/Forms/FormRegex.php
@@ -0,0 +1,55 @@
+<?php
+
+namespace App\Service\Forms;
+
+use Illuminate\Support\Str;
+
+final class FormRegex
+{
+ public const MAX_PATTERN_LENGTH = 1000;
+
+ public static function isValid(string $pattern): bool
+ {
+ return self::compile($pattern) !== null;
+ }
+
+ public static function matches(string $pattern, string $value): ?bool
+ {
+ $compiledPattern = self::compile($pattern);
+ if ($compiledPattern === null) {
+ return null;
+ }
+
+ return preg_match($compiledPattern, $value) === 1;
+ }
+
+ private static function compile(string $pattern): ?string
+ {
+ if (Str::length($pattern) > self::MAX_PATTERN_LENGTH) {
+ return null;
+ }
+
+ $delimiter = null;
+ foreach (['~', '#', '%', '!', '@', ';', '`', '='] as $candidate) {
+ if (! str_contains($pattern, $candidate)) {
+ $delimiter = $candidate;
+
+ break;
+ }
+ }
+ if ($delimiter === null) {
+ return null;
+ }
+
+ $compiledPattern = $delimiter.$pattern.$delimiter.'u';
+
+ set_error_handler(static fn (): bool => true);
+ try {
+ $isValid = preg_match($compiledPattern, '') !== false;
+ } finally {
+ restore_error_handler();
+ }
+
+ return $isValid ? $compiledPattern : null;
+ }
+}
diff --git a/api/app/Service/Forms/FormStructureValidator.php b/api/app/Service/Forms/FormStructureValidator.php
new file mode 100644
index 000000000..40f3ec143
--- /dev/null
+++ b/api/app/Service/Forms/FormStructureValidator.php
@@ -0,0 +1,55 @@
+<?php
+
+namespace App\Service\Forms;
+
+use App\Models\Workspace;
+use App\Rules\ComputedVariablesRule;
+use App\Rules\FormPropertiesRule;
+use Illuminate\Contracts\Validation\Validator as ValidatorContract;
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\ValidationException;
+
+final class FormStructureValidator
+{
+ public const MAX_PROPERTY_COUNT = 500;
+
+ public function __construct(private readonly FormValidationIssueMapper $issueMapper)
+ {
+ }
+
+ public function validator(array $definition, ?Workspace $workspace = null): ValidatorContract
+ {
+ return Validator::make($definition, [
+ 'properties' => ['required', 'array', 'max:'.self::MAX_PROPERTY_COUNT, new FormPropertiesRule($workspace)],
+ 'computed_variables' => ['nullable', 'array', new ComputedVariablesRule()],
+ ]);
+ }
+
+ public function validate(array $definition, ?Workspace $workspace = null): void
+ {
+ $validator = $this->validator($definition, $workspace);
+ if ($validator->passes()) {
+ return;
+ }
+
+ $errors = $validator->errors()->toArray();
+ $issues = $this->issueMapper->fromErrors($errors);
+
+ throw new ValidationException($validator, response()->json([
+ 'message' => $this->issueMapper->summary($this->issueMapper->count($errors)),
+ 'errors' => $errors,
+ 'issues' => $issues,
+ ], 422));
+ }
+
+ /**
+ * @return array<int, array{code: string, path: string, message: string, meta: array<string, mixed>}>
+ */
+ public function issues(array $definition, ?Workspace $workspace = null): array
+ {
+ $validator = $this->validator($definition, $workspace);
+ $validator->passes();
+
+ return $this->issueMapper->fromErrors($validator->errors()->toArray());
+ }
+}
diff --git a/api/app/Service/Forms/FormUpdateService.php b/api/app/Service/Forms/FormUpdateService.php
index 57052880d..285b34fcc 100644
--- a/api/app/Service/Forms/FormUpdateService.php
+++ b/api/app/Service/Forms/FormUpdateService.php
@@ -22,7 +22,11 @@ final class FormUpdateService
$formData['removed_properties'] = array_merge(
$form->removed_properties ?? [],
collect($form->properties)
- ->filter(fn (array $field): bool => ! Str::of($field['type'])->startsWith('nf-') && ! isset($newPropertyIds[$field['id']]))
+ ->filter(fn ($field): bool => is_array($field)
+ && is_string($field['id'] ?? null)
+ && is_string($field['type'] ?? null)
+ && ! Str::of($field['type'])->startsWith('nf-')
+ && ! isset($newPropertyIds[$field['id']]))
->all(),
);
diff --git a/api/app/Service/Forms/FormValidationIssueMapper.php b/api/app/Service/Forms/FormValidationIssueMapper.php
new file mode 100644
index 000000000..95f125525
--- /dev/null
+++ b/api/app/Service/Forms/FormValidationIssueMapper.php
@@ -0,0 +1,133 @@
+<?php
+
+namespace App\Service\Forms;
+
+final class FormValidationIssueMapper
+{
+ public const MAX_ISSUES = 100;
+
+ private const AGGREGATE_MESSAGES = [
+ 'One or more properties have validation errors.',
+ 'One or more computed variables have validation errors.',
+ ];
+
+ /**
+ * @param array<string, array<int, string>> $errors
+ * @return array<int, array{code: string, path: string, message: string, meta: array<string, mixed>}>
+ */
+ public function fromErrors(array $errors): array
+ {
+ $issues = [];
+
+ foreach ($errors as $path => $messages) {
+ foreach ((array) $messages as $message) {
+ if (! is_string($message) || in_array($message, self::AGGREGATE_MESSAGES, true)) {
+ continue;
+ }
+
+ $code = $this->codeFor($path, $message);
+ $issues[] = [
+ 'code' => $code,
+ 'path' => $path,
+ 'message' => $message,
+ 'meta' => $this->metaFor($code, $message),
+ ];
+
+ if (count($issues) >= self::MAX_ISSUES) {
+ return $issues;
+ }
+ }
+ }
+
+ return $issues;
+ }
+
+ public function summary(int $issueCount): string
+ {
+ return $issueCount === 1
+ ? 'The form contains one issue that must be fixed before saving.'
+ : "The form contains {$issueCount} issues that must be fixed before saving.";
+ }
+
+ /** @param array<string, array<int, string>> $errors */
+ public function count(array $errors): int
+ {
+ $count = 0;
+
+ foreach ($errors as $messages) {
+ foreach ((array) $messages as $message) {
+ if (is_string($message) && ! in_array($message, self::AGGREGATE_MESSAGES, true)) {
+ $count++;
+ }
+ }
+ }
+
+ return $count;
+ }
+
+ /**
+ * Laravel MCP serializes validation messages without their attribute keys.
+ * Prefixing messages here preserves the exact repair target for agents.
+ *
+ * @param array<string, array<int, string>> $errors
+ * @return array<string, array<int, string>>
+ */
+ public function pathErrors(array $errors): array
+ {
+ $localizedErrors = [];
+
+ foreach ($errors as $path => $messages) {
+ foreach ((array) $messages as $message) {
+ if (! is_string($message) || in_array($message, self::AGGREGATE_MESSAGES, true)) {
+ continue;
+ }
+
+ $localizedErrors[$path][] = "{$path}: {$message}";
+ }
+ }
+
+ return $localizedErrors;
+ }
+
+ private function codeFor(string $path, string $message): string
+ {
+ $normalized = strtolower($message);
+
+ return match (true) {
+ str_contains($normalized, 'no longer exists'),
+ str_contains($normalized, 'unknown field') => 'unknown_reference',
+ str_contains($normalized, 'reference type must be') => 'reference_type_mismatch',
+ str_contains($normalized, 'cannot reference itself'),
+ str_contains($normalized, 'same field') => 'self_reference',
+ str_contains($normalized, 'circular dependency') => 'cyclic_dependency',
+ str_contains($normalized, 'dependency chain is too deep') => 'dependency_chain_depth_exceeded',
+ str_contains($normalized, 'cannot contain more than') => 'condition_count_exceeded',
+ str_contains($normalized, 'cannot be nested more than') => 'condition_depth_exceeded',
+ str_contains($normalized, 'only available for custom validation'),
+ str_contains($normalized, 'operator') && str_contains($normalized, 'not available') => 'unsupported_operator',
+ str_contains($normalized, 'already used'),
+ str_contains($normalized, 'duplicate') => str_ends_with($path, '.id') ? 'duplicate_id' : 'duplicate_value',
+ str_contains($normalized, 'formula') || str_contains($path, '.formula') => 'formula_error',
+ str_contains($path, '.logic') => 'invalid_logic',
+ default => 'invalid_definition',
+ };
+ }
+
+ /** @return array<string, mixed> */
+ private function metaFor(string $code, string $message): array
+ {
+ if ($code === 'reference_type_mismatch' && preg_match('/for \[([^\]]+)]/', $message, $matches) === 1) {
+ return ['reference_id' => $matches[1]];
+ }
+
+ if ($code === 'unknown_reference' && preg_match('/\[([^\]]+)]/', $message, $matches) === 1) {
+ return ['reference_id' => $matches[1]];
+ }
+
+ if ($code === 'unknown_reference' && preg_match('/"([^"]+)"/', $message, $matches) === 1) {
+ return ['reference_id' => $matches[1]];
+ }
+
+ return [];
+ }
+}
diff --git a/api/routes/api.php b/api/routes/api.php
index 48f6a30b0..4ed4c413e 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -246,6 +246,7 @@ Route::group(['middleware' => 'auth.multi'], function () {
Route::prefix('forms')->name('forms.')->group(function () {
Route::post('/', [FormController::class, 'store'])->name('store');
+ Route::post('/{form}/validate-definition', [FormController::class, 'validateDefinition'])->name('validate-definition');
Route::post('/{form}/workspace/{workspace}', [FormController::class, 'updateWorkspace'])->name('workspace.update');
Route::put('/{form}', [FormController::class, 'update'])->name('update');
Route::delete('/{form}', [FormController::class, 'destroy'])->name('destroy');
diff --git a/api/tests/Feature/Forms/AuditFormDefinitionsTest.php b/api/tests/Feature/Forms/AuditFormDefinitionsTest.php
new file mode 100644
index 000000000..c9ecba2d7
--- /dev/null
+++ b/api/tests/Feature/Forms/AuditFormDefinitionsTest.php
@@ -0,0 +1,65 @@
+<?php
+
+use Illuminate\Support\Facades\Artisan;
+
+it('audits form definitions without modifying them', function () {
+ $user = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($user);
+ $validForm = $this->createForm($user, $workspace);
+ $validForm->forceFill([
+ 'properties' => [['id' => 'valid', 'name' => 'Valid', 'type' => 'text']],
+ 'computed_variables' => [],
+ ])->save();
+ $repairableForm = $this->createForm($user, $workspace);
+ $repairableProperties = [
+ ['id' => 'source', 'name' => 'Source', 'type' => 'text'],
+ ['id' => 'target', 'name' => 'Target', 'type' => 'text'],
+ ];
+ $repairableProperties[1]['logic'] = [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [[
+ 'identifier' => 'removed',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => ['id' => 'removed', 'type' => 'text'],
+ 'value' => 'yes',
+ ],
+ ]],
+ ],
+ 'actions' => ['hide-block'],
+ ];
+ $repairableForm->forceFill([
+ 'properties' => $repairableProperties,
+ 'computed_variables' => [],
+ ])->save();
+ $invalidForm = $this->createForm($user, $workspace);
+ $invalidForm->forceFill([
+ 'properties' => [[
+ 'id' => 'choice',
+ 'name' => 'Choice',
+ 'type' => 'select',
+ 'select' => ['options' => []],
+ ]],
+ 'computed_variables' => [],
+ ])->save();
+ $repairableUpdatedAt = $repairableForm->updated_at->toISOString();
+ $invalidUpdatedAt = $invalidForm->updated_at->toISOString();
+
+ expect(Artisan::call('forms:audit-definitions', ['--json' => true]))->toBe(0);
+ $report = json_decode(Artisan::output(), true, flags: JSON_THROW_ON_ERROR);
+
+ expect($report)
+ ->toMatchArray([
+ 'forms_checked' => 3,
+ 'valid_forms' => 2,
+ 'auto_repaired_forms' => 1,
+ 'invalid_forms_count' => 1,
+ 'issues_by_code' => ['invalid_definition' => 1],
+ ])
+ ->and($report['invalid_forms'][0]['form_id'])->toBe($invalidForm->id);
+
+ expect($validForm->fresh())->not->toBeNull()
+ ->and($repairableForm->fresh()->updated_at->toISOString())->toBe($repairableUpdatedAt)
+ ->and($invalidForm->fresh()->updated_at->toISOString())->toBe($invalidUpdatedAt);
+});
diff --git a/api/tests/Feature/Forms/FormTest.php b/api/tests/Feature/Forms/FormTest.php
index 8c937d663..fa5c44e0e 100644
--- a/api/tests/Feature/Forms/FormTest.php
+++ b/api/tests/Feature/Forms/FormTest.php
@@ -182,6 +182,137 @@ it('can update a form', function () {
]);
});
+it('prevalidates recoverable logic after normalizing it without saving', function () {
+ $user = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+ $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());
+ $formData['properties'][1]['logic'] = [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [[
+ 'identifier' => 'deleted_field',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => ['id' => 'deleted_field', 'type' => 'text'],
+ 'value' => 'yes',
+ ],
+ ]],
+ ],
+ 'actions' => ['hide-block'],
+ ];
+
+ $this->postJson(route('open.forms.validate-definition', $form), $formData)
+ ->assertSuccessful()
+ ->assertJsonPath('valid', true);
+
+ expect($form->fresh()->properties[1]['logic'] ?? null)->toBeNull();
+});
+
+it('authorizes definition prevalidation before running its validation rules', function () {
+ $owner = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($owner);
+ $form = $this->createForm($owner, $workspace);
+ $otherUser = $this->createUser();
+ $this->actingAs($otherUser);
+
+ $this->postJson(route('open.forms.validate-definition', $form), [
+ 'properties' => 'invalid',
+ ])->assertForbidden();
+});
+
+it('removes recoverably invalid logic while saving the rest of the form', function () {
+ $user = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+ $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());
+ $formData['title'] = 'Persisted after cleanup';
+ $formData['properties'][1]['logic'] = [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [[
+ 'identifier' => 'missing',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => ['id' => 'missing', 'type' => 'text'],
+ 'value' => 'yes',
+ ],
+ ]],
+ ],
+ 'actions' => ['hide-block'],
+ ];
+
+ $this->putJson(route('open.forms.update', $form), $formData)
+ ->assertSuccessful()
+ ->assertJsonPath('form.title', 'Persisted after cleanup');
+
+ expect($form->fresh()->title)->toBe('Persisted after cleanup')
+ ->and($form->fresh()->properties[1])->not->toHaveKey('logic');
+});
+
+it('saves after discarding malformed legacy property entries', function () {
+ $user = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+ $form->forceFill([
+ 'properties' => [
+ 'malformed',
+ ['id' => 'kept', 'name' => 'Kept', 'type' => 'text'],
+ ],
+ ])->save();
+ $formData = (new \App\Http\Resources\FormResource($form->fresh()))->toArray(request());
+ $formData['title'] = 'Saved after cleanup';
+
+ $this->putJson(route('open.forms.update', $form), $formData)
+ ->assertSuccessful()
+ ->assertJsonPath('form.title', 'Saved after cleanup');
+
+ expect($form->fresh()->properties)->toBe([
+ ['id' => 'kept', 'name' => 'Kept', 'type' => 'text'],
+ ]);
+});
+
+it('still blocks when cleanup would require inventing a select option', function () {
+ $user = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+ $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());
+ $formData['properties'][] = [
+ 'id' => 'empty-choice',
+ 'name' => 'Choose one',
+ 'type' => 'select',
+ 'select' => [
+ 'options' => [
+ ['id' => null, 'name' => null],
+ ],
+ ],
+ ];
+
+ $this->putJson(route('open.forms.update', $form), $formData)
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors(['properties.14.select.options'])
+ ->assertJsonPath('issues.0.code', 'invalid_definition');
+});
+
+it('applies the shared field count limit to human form saves', function () {
+ $user = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+ $formData = (new \App\Http\Resources\FormResource($form))->toArray(request());
+ $formData['properties'] = collect(range(1, \App\Service\Forms\FormStructureValidator::MAX_PROPERTY_COUNT + 1))
+ ->map(fn (int $index) => [
+ 'id' => "field-{$index}",
+ 'name' => "Field {$index}",
+ 'type' => 'text',
+ ])
+ ->all();
+
+ $this->putJson(route('open.forms.update', $form), $formData)
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors(['properties'])
+ ->assertJsonPath('issues.0.path', 'properties');
+});
+
it('preserves strikethrough formatting when updating field help text', function () {
$user = $this->actingAsUser();
$workspace = $this->createUserWorkspace($user);
@@ -347,6 +478,36 @@ it('can duplicate a form', function () {
]);
});
+it('normalizes recoverable logic while duplicating without changing the source form', function () {
+ $user = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+ $properties = $form->properties;
+ $properties[1]['logic'] = [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [[
+ 'identifier' => 'deleted_field',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => ['id' => 'deleted_field', 'type' => 'text'],
+ 'value' => 'yes',
+ ],
+ ]],
+ ],
+ 'actions' => ['hide-block'],
+ ];
+ $form->forceFill(['properties' => $properties])->save();
+
+ $response = $this->postJson(route('open.forms.duplicate', $form))
+ ->assertSuccessful();
+
+ $copy = \App\Models\Forms\Form::query()->findOrFail($response->json('new_form.id'));
+ expect($workspace->forms()->count())->toBe(2)
+ ->and($copy->properties[1])->not->toHaveKey('logic')
+ ->and($form->fresh()->properties[1])->toHaveKey('logic');
+});
+
it('can delete a form', function () {
$user = $this->actingAsUser();
$workspace = $this->createUserWorkspace($user);
@@ -605,7 +766,7 @@ it('can update form with multi select min/max selection constraints', function (
expect($multiSelectField['max_selection'])->toBe(3);
});
-it('validates min/max selection constraints format in form creation', function () {
+it('clears invalid optional selection constraints during form creation', function () {
$user = $this->actingAsUser();
$workspace = $this->createUserWorkspace($user);
$form = $this->makeForm($user, $workspace);
@@ -628,10 +789,11 @@ it('validates min/max selection constraints format in form creation', function (
$formData = (new \App\Http\Resources\FormResource($form))->toArray(request());
- $this->postJson(route('open.forms.store', $formData))
- ->assertUnprocessable()
- ->assertJsonValidationErrors([
- 'properties.14.min_selection',
- 'properties.14.max_selection'
- ]);
+ $response = $this->postJson(route('open.forms.store', $formData))
+ ->assertSuccessful();
+
+ $savedForm = \App\Models\Forms\Form::query()->findOrFail($response->json('form.id'));
+ $savedField = collect($savedForm->properties)->firstWhere('id', 'invalid_field');
+
+ expect($savedField)->not->toHaveKeys(['min_selection', 'max_selection']);
});
diff --git a/api/tests/Feature/Mcp/AgentPluginPackageTest.php b/api/tests/Feature/Mcp/AgentPluginPackageTest.php
index 7bd673884..ccefd3e41 100644
--- a/api/tests/Feature/Mcp/AgentPluginPackageTest.php
+++ b/api/tests/Feature/Mcp/AgentPluginPackageTest.php
@@ -238,6 +238,18 @@ it('teaches agents how to change presentation and media without repository inspe
->toContain('Never persist localhost, private addresses, temporary tunnels');
});
+it('teaches agents how to author and patch computed variables and display logic', function () {
+ $bundle = readOpnformSkillBundle();
+
+ expect($bundle)
+ ->toContain('A computed variable needs a unique `id` beginning with `cv_`')
+ ->toContain('`{budget} * 1.2`')
+ ->toContain('Use the referenced block type in `property_meta.type`, or `computed`')
+ ->toContain('`operators_by_reference_type`')
+ ->toContain('replace the complete `computed_variables` list through `set_form_values`')
+ ->toContain("clear a block's `logic`");
+});
+
it('renders a guest preview automatically after creation and every draft change', function () {
$skill = file_get_contents(opnformPluginPath('skills/opnform/SKILL.md'));
$server = file_get_contents(app_path('Mcp/Servers/OpnFormServer.php'));
diff --git a/api/tests/Feature/Mcp/GuestDraftToolsTest.php b/api/tests/Feature/Mcp/GuestDraftToolsTest.php
index f5918da24..f11c07220 100644
--- a/api/tests/Feature/Mcp/GuestDraftToolsTest.php
+++ b/api/tests/Feature/Mcp/GuestDraftToolsTest.php
@@ -160,6 +160,78 @@ it('describes strict style values in the patch schema and field catalog', functi
->toBe(['none', 'small', 'full']);
});
+it('publishes and applies computed variable and display logic draft patches', function () {
+ $schema = app(PatchFormDraftTool::class)->schema(new \Illuminate\JsonSchema\JsonSchemaTypeFactory());
+ $operationProperties = $schema['operations']->toArray()['items']['properties'];
+
+ expect($operationProperties['values']['properties']['computed_variables']['items']['properties'])
+ ->toHaveKeys(['id', 'name', 'formula', 'result_type'])
+ ->and($operationProperties['block']['properties'])
+ ->toHaveKeys(['hidden', 'logic'])
+ ->and($operationProperties['patch']['properties'])
+ ->toHaveKeys(['hidden', 'logic'])
+ ->and($operationProperties['patch']['properties']['logic']['type'])
+ ->toBe(['object', 'null'])
+ ->and($operationProperties['patch']['properties']['logic']['properties']['conditions']['properties']['value']['properties']['value']['type'])
+ ->toBe(['string', 'number', 'boolean', 'object', 'array', 'null'])
+ ->and($operationProperties['patch']['properties']['logic']['properties']['actions']['items']['enum'])
+ ->toContain('show-block', 'hide-block', 'require-answer');
+
+ $drafts = app(AgentFormDraftService::class);
+ $created = $drafts->create(guestDraftDefinition([
+ 'properties' => [
+ ['id' => 'budget', 'name' => 'Budget', 'type' => 'number'],
+ ['id' => 'details', 'name' => 'Details', 'type' => 'text'],
+ ],
+ ]));
+
+ OpnFormServer::tool(PatchFormDraftTool::class, [
+ 'draft_handle' => $created['token'],
+ 'expected_version' => 1,
+ 'operations' => [
+ [
+ 'op' => 'set_form_values',
+ 'values' => [
+ 'computed_variables' => [[
+ 'id' => 'cv_priority_score',
+ 'name' => 'Priority score',
+ 'formula' => '{budget} * 1.5',
+ 'result_type' => 'number',
+ ]],
+ ],
+ ],
+ [
+ 'op' => 'update_block',
+ 'block_id' => 'details',
+ 'patch' => [
+ 'hidden' => true,
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [[
+ 'identifier' => 'cv_priority_score',
+ 'value' => [
+ 'operator' => 'greater_than',
+ 'property_meta' => ['id' => 'cv_priority_score', 'type' => 'computed'],
+ 'value' => 15000,
+ ],
+ ]],
+ ],
+ 'actions' => ['show-block'],
+ ],
+ ],
+ ],
+ ],
+ ])->assertOk();
+
+ $definition = $created['draft']->refresh()->definition;
+ expect($created['draft']->version)->toBe(2)
+ ->and($definition['computed_variables'][0]['formula'])->toBe('{budget} * 1.5')
+ ->and($definition['properties'][1]['hidden'])->toBeTrue()
+ ->and($definition['properties'][1]['logic']['conditions']['children'][0]['value']['value'])
+ ->toBe(15000);
+});
+
it('returns actionable validation errors for invalid style values', function () {
$drafts = app(AgentFormDraftService::class);
$created = $drafts->create(guestDraftDefinition());
@@ -217,6 +289,50 @@ it('rolls back invalid patch operations and preserves the previous version', fun
->and($created['draft']->definition['properties'])->toHaveCount(1);
});
+it('cleans dependent variables and logic after removing an MCP draft block', function () {
+ $drafts = app(AgentFormDraftService::class);
+ $created = $drafts->create(guestDraftDefinition([
+ 'properties' => [
+ ['id' => 'amount', 'name' => 'Amount', 'type' => 'number'],
+ [
+ 'id' => 'details',
+ 'name' => 'Details',
+ 'type' => 'text',
+ 'hidden' => true,
+ 'logic' => [
+ 'conditions' => [
+ 'identifier' => 'cv_double',
+ 'value' => [
+ 'operator' => 'greater_than',
+ 'property_meta' => ['id' => 'cv_double', 'type' => 'computed'],
+ 'value' => 10,
+ ],
+ ],
+ 'actions' => ['show-block'],
+ ],
+ ],
+ ],
+ 'computed_variables' => [
+ ['id' => 'cv_base', 'name' => 'Base', 'formula' => '{amount}', 'result_type' => 'number'],
+ ['id' => 'cv_double', 'name' => 'Double', 'formula' => '{cv_base} * 2', 'result_type' => 'number'],
+ ],
+ ]));
+
+ OpnFormServer::tool(PatchFormDraftTool::class, [
+ 'draft_handle' => $created['token'],
+ 'expected_version' => 1,
+ 'operations' => [[
+ 'op' => 'remove_block',
+ 'block_id' => 'amount',
+ ]],
+ ])->assertOk();
+
+ $definition = $created['draft']->refresh()->definition;
+ expect($definition['computed_variables'])->toBeEmpty()
+ ->and($definition['properties'][0]['id'])->toBe('details')
+ ->and($definition['properties'][0])->not->toHaveKey('logic');
+});
+
it('rejects malformed, expired, and claimed draft capabilities with one generic error', function () {
$drafts = app(AgentFormDraftService::class);
$created = $drafts->create(guestDraftDefinition());
@@ -247,7 +363,81 @@ it('rejects duplicate block ids', function () {
['id' => 'duplicate', 'name' => 'Two', 'type' => 'email'],
],
]),
- ])->assertHasErrors(['unique id']);
+ ])->assertHasErrors([
+ 'properties.1.id',
+ 'The field ID [duplicate] is already used by field 1.',
+ ]);
+});
+
+it('accepts computed variables as display logic sources', function () {
+ OpnFormServer::tool(CreateFormDraftTool::class, [
+ 'definition' => guestDraftDefinition([
+ 'properties' => [
+ ['id' => 'amount', 'name' => 'Amount', 'type' => 'number'],
+ [
+ 'id' => 'details',
+ 'name' => 'Details',
+ 'type' => 'text',
+ 'hidden' => true,
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [[
+ 'identifier' => 'cv_total',
+ 'value' => [
+ 'operator' => 'greater_than',
+ 'property_meta' => ['id' => 'cv_total', 'type' => 'computed'],
+ 'value' => 100,
+ ],
+ ]],
+ ],
+ 'actions' => ['show-block'],
+ ],
+ ],
+ ],
+ 'computed_variables' => [[
+ 'id' => 'cv_total',
+ 'name' => 'Total',
+ 'formula' => '{amount} * 2',
+ 'result_type' => 'number',
+ ]],
+ ]),
+ ])->assertOk();
+
+ $this->assertDatabaseCount('agent_form_drafts', 1);
+ $condition = AgentFormDraft::query()->firstOrFail()
+ ->definition['properties'][1]['logic']['conditions']['children'][0];
+ expect($condition['identifier'])->toBe('cv_total')
+ ->and($condition['value']['property_meta'])->toBe(['id' => 'cv_total', 'type' => 'computed']);
+});
+
+it('removes display logic with missing MCP references before persisting', function () {
+ OpnFormServer::tool(CreateFormDraftTool::class, [
+ 'definition' => guestDraftDefinition([
+ 'properties' => [[
+ 'id' => 'details',
+ 'name' => 'Details',
+ 'type' => 'text',
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [[
+ 'identifier' => 'removed',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => ['id' => 'removed', 'type' => 'text'],
+ 'value' => 'yes',
+ ],
+ ]],
+ ],
+ 'actions' => ['show-block'],
+ ],
+ ]],
+ ]),
+ ])->assertOk();
+
+ $this->assertDatabaseCount('agent_form_drafts', 1);
+ expect(AgentFormDraft::query()->firstOrFail()->definition['properties'][0])->not->toHaveKey('logic');
});
it('rejects machine-like labels before persisting a guest draft', function () {
diff --git a/api/tests/Feature/Mcp/McpFoundationTest.php b/api/tests/Feature/Mcp/McpFoundationTest.php
index 5899d4f62..0d6c39d24 100644
--- a/api/tests/Feature/Mcp/McpFoundationTest.php
+++ b/api/tests/Feature/Mcp/McpFoundationTest.php
@@ -172,6 +172,9 @@ it('publishes the versioned form definition schema', function () {
->assertSee('agent-form-definition/v1.json')
->assertSee('schema_version')
->assertSee('properties')
+ ->assertSee('computedVariable')
+ ->assertSee('displayLogic')
+ ->assertSee('property_meta')
->assertSee('Respondent-facing label')
->assertSee('sanitized HTML fragment')
->assertSee('never Markdown');
@@ -271,6 +274,32 @@ it('documents block media in the published form definition schema', function ()
->toContain('right-split', 'background');
});
+it('documents computed variables and recursive display logic in the published resources', function () {
+ $schema = app(AgentFormDefinition::class)->jsonSchema();
+ $catalog = \App\Service\Forms\AgentFormFieldCatalog::reference();
+
+ expect($schema['properties']['computed_variables']['items']['$ref'])
+ ->toBe('#/$defs/computedVariable')
+ ->and($schema['$defs']['computedVariable']['required'])
+ ->toBe(['id', 'name', 'formula'])
+ ->and($schema['$defs']['computedVariable']['properties']['id']['pattern'])
+ ->toBe('^cv_')
+ ->and($schema['$defs']['block']['properties']['logic']['anyOf'][0]['$ref'])
+ ->toBe('#/$defs/displayLogic')
+ ->and($schema['$defs']['logicConditionGroup']['properties']['children']['items']['$ref'])
+ ->toBe('#/$defs/logicCondition')
+ ->and($schema['$defs']['logicConditionValue']['properties']['property_meta']['properties']['type']['enum'])
+ ->toContain('number', 'computed')
+ ->and($schema['$defs']['logicConditionValue']['properties']['operator']['enum'])
+ ->toContain('greater_than', 'contains', 'is_empty')
+ ->and($catalog['computed_variables']['example']['formula'])
+ ->toBe('{budget} * 1.2')
+ ->and($catalog['display_logic']['operators_by_reference_type']['computed'])
+ ->toContain('greater_than', 'equals')
+ ->and($catalog['display_logic']['example']['conditions']['children'][0]['value']['property_meta'])
+ ->toBe(['id' => 'cv_priority_score', 'type' => 'computed']);
+});
+
it('applies the public media URL policy to block images', function () {
$definition = app(AgentFormDefinition::class);
diff --git a/api/tests/Unit/Rules/ComputedVariablesRuleTest.php b/api/tests/Unit/Rules/ComputedVariablesRuleTest.php
new file mode 100644
index 000000000..79bd47b17
--- /dev/null
+++ b/api/tests/Unit/Rules/ComputedVariablesRuleTest.php
@@ -0,0 +1,181 @@
+<?php
+
+use App\Rules\ComputedVariablesRule;
+use Tests\TestCase;
+
+uses(TestCase::class);
+
+it('returns every actionable formula error on its variable path', function () {
+ $validator = validator([
+ 'properties' => [
+ ['id' => 'amount', 'name' => 'Amount', 'type' => 'number'],
+ ],
+ 'computed_variables' => [
+ [
+ 'id' => 'cv_total',
+ 'name' => 'Total',
+ 'formula' => '{missing_one} + {missing_two}',
+ 'result_type' => 'number',
+ ],
+ ],
+ ], [
+ 'computed_variables' => ['array', new ComputedVariablesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->get('computed_variables.0.formula'))->toHaveCount(2)
+ ->and($validator->errors()->first('computed_variables.0.formula'))->toContain('missing_one');
+});
+
+it('rejects an ID shared by a field and computed variable', function () {
+ $validator = validator([
+ 'properties' => [
+ ['id' => 'cv_total', 'name' => 'Amount', 'type' => 'number'],
+ ],
+ 'computed_variables' => [
+ [
+ 'id' => 'cv_total',
+ 'name' => 'Total',
+ 'formula' => '10',
+ 'result_type' => 'number',
+ ],
+ ],
+ ], [
+ 'computed_variables' => ['array', new ComputedVariablesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->first('computed_variables.0.id'))->toContain('already used by a form field');
+});
+
+it('returns circular dependency and unknown reference errors together', function () {
+ $validator = validator([
+ 'properties' => [],
+ 'computed_variables' => [
+ ['id' => 'cv_a', 'name' => 'A', 'formula' => '{cv_b}', 'result_type' => 'number'],
+ ['id' => 'cv_b', 'name' => 'B', 'formula' => '{cv_a}', 'result_type' => 'number'],
+ ['id' => 'cv_c', 'name' => 'C', 'formula' => '{missing}', 'result_type' => 'number'],
+ ],
+ ], [
+ 'computed_variables' => ['array', new ComputedVariablesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->first('computed_variables.0.formula'))->toContain('Circular dependency')
+ ->and($validator->errors()->first('computed_variables.1.formula'))->toContain('Circular dependency')
+ ->and($validator->errors()->first('computed_variables.2.formula'))->toContain('missing');
+});
+
+it('reports malformed variables without throwing while calculating dependency depth', function () {
+ $validator = validator([
+ 'properties' => [],
+ 'computed_variables' => ['not-an-object'],
+ ], [
+ 'computed_variables' => ['array', new ComputedVariablesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->first('computed_variables.0._'))->toContain('must be an array');
+});
+
+it('localizes a malformed variable id even when its formula must also be checked', function () {
+ $validator = validator([
+ 'properties' => [],
+ 'computed_variables' => [[
+ 'id' => ['cv_invalid'],
+ 'name' => 'Invalid',
+ 'formula' => '{missing}',
+ ]],
+ ], [
+ 'computed_variables' => ['array', new ComputedVariablesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->first('computed_variables.0.id'))->toContain('required')
+ ->and($validator->errors()->first('computed_variables.0.formula'))->toContain('missing');
+});
+
+it('does not throw when the sibling properties collection is malformed', function () {
+ $validator = validator([
+ 'properties' => 'not-an-array',
+ 'computed_variables' => [[
+ 'id' => 'cv_total',
+ 'name' => 'Total',
+ 'formula' => '{missing}',
+ ]],
+ ], [
+ 'properties' => ['array'],
+ 'computed_variables' => ['array', new ComputedVariablesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->first('properties'))->not->toBeEmpty()
+ ->and($validator->errors()->first('computed_variables.0.formula'))->toContain('missing');
+});
+
+it('attaches excessive dependency depth to each affected variable formula', function () {
+ $variables = [];
+ foreach (range(1, 21) as $index) {
+ $variables[] = [
+ 'id' => "cv_{$index}",
+ 'name' => "Variable {$index}",
+ 'formula' => $index === 21 ? '1' : '{cv_'.($index + 1).'}',
+ 'result_type' => 'number',
+ ];
+ }
+
+ $validator = validator([
+ 'properties' => [],
+ 'computed_variables' => $variables,
+ ], [
+ 'computed_variables' => ['array', new ComputedVariablesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->first('computed_variables.0.formula'))->toContain('21 levels')
+ ->and($validator->errors()->has('computed_variables.1.formula'))->toBeFalse();
+});
+
+it('counts multibyte variable names as characters and rejects whitespace-only names', function () {
+ $valid = validator([
+ 'properties' => [],
+ 'computed_variables' => [[
+ 'id' => 'cv_multibyte',
+ 'name' => str_repeat('é', 100),
+ 'formula' => '1',
+ ]],
+ ], [
+ 'computed_variables' => ['array', new ComputedVariablesRule()],
+ ]);
+ $invalid = validator([
+ 'properties' => [],
+ 'computed_variables' => [[
+ 'id' => 'cv_blank',
+ 'name' => ' ',
+ 'formula' => '1',
+ ]],
+ ], [
+ 'computed_variables' => ['array', new ComputedVariablesRule()],
+ ]);
+
+ expect($valid->passes())->toBeTrue()
+ ->and($invalid->passes())->toBeFalse()
+ ->and($invalid->errors()->first('computed_variables.0.name'))->toContain('cannot be empty');
+});
+
+it('rejects an unbounded computed variable collection before graph traversal', function () {
+ $variables = array_fill(0, ComputedVariablesRule::MAX_VARIABLE_COUNT + 1, [
+ 'id' => 'cv_duplicate',
+ 'name' => 'Duplicate',
+ 'formula' => '1',
+ ]);
+ $validator = validator([
+ 'properties' => [],
+ 'computed_variables' => $variables,
+ ], [
+ 'computed_variables' => ['array', new ComputedVariablesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->first('computed_variables'))->toContain('cannot contain more than 500');
+});
diff --git a/api/tests/Unit/Rules/FormPropertiesRuleTest.php b/api/tests/Unit/Rules/FormPropertiesRuleTest.php
index 2403366cf..7eeb54748 100644
--- a/api/tests/Unit/Rules/FormPropertiesRuleTest.php
+++ b/api/tests/Unit/Rules/FormPropertiesRuleTest.php
@@ -6,6 +6,77 @@ use Tests\TestCase;
uses(TestCase::class);
describe('FormPropertiesRule', function () {
+ it('returns field-local errors for malformed core values without throwing', function () {
+ $validator = validator([
+ 'properties' => [[
+ 'id' => 123,
+ 'name' => ['Not', 'text'],
+ 'type' => ['text'],
+ ]],
+ ], [
+ 'properties' => ['array', new FormPropertiesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->first('properties.0.id'))->toContain('must be a string')
+ ->and($validator->errors()->first('properties.0.name'))->toContain('must be a string')
+ ->and($validator->errors()->first('properties.0.type'))->toContain('must be a string');
+ });
+
+ it('rejects unsupported field types on the exact field path', function () {
+ $validator = validator([
+ 'properties' => [[
+ 'id' => 'unknown',
+ 'name' => 'Unknown',
+ 'type' => 'invented_field_type',
+ ]],
+ ], [
+ 'properties' => ['array', new FormPropertiesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->first('properties.0.type'))->toContain('not supported');
+ });
+
+ it('returns localized errors instead of throwing for malformed payment neighbours and values', function () {
+ $validator = validator([
+ 'properties' => [
+ 'not-a-property',
+ [
+ 'id' => 'payment',
+ 'name' => 'Payment',
+ 'type' => 'payment',
+ 'amount' => 10,
+ 'currency' => ['EUR'],
+ 'stripe_account_id' => ['invalid'],
+ ],
+ ],
+ ], [
+ 'properties' => ['array', new FormPropertiesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->first('properties.0'))->toContain('must be an array')
+ ->and($validator->errors()->first('properties.1.currency'))->toContain('valid currency');
+ });
+
+ it('rejects malformed nested image values without PHP warnings', function () {
+ $validator = validator([
+ 'properties' => [[
+ 'id' => 'photo',
+ 'name' => 'Photo',
+ 'type' => 'text',
+ 'image' => ['focal_point' => 'center', 'brightness' => ['bright']],
+ ]],
+ ], [
+ 'properties' => ['array', new FormPropertiesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->first('properties.0.image.focal_point'))->toContain('must be an object')
+ ->and($validator->errors()->first('properties.0.image.brightness'))->toContain('must be an integer');
+ });
+
describe('basic validation', function () {
it('passes with valid properties', function () {
$rules = [
@@ -83,6 +154,19 @@ describe('FormPropertiesRule', function () {
});
describe('core property validation', function () {
+ it('counts multibyte field names as characters rather than bytes', function () {
+ $validator = $this->app['validator']->make(
+ ['properties' => [[
+ 'id' => 'multibyte-name',
+ 'name' => str_repeat('é', 500),
+ 'type' => 'text',
+ ]]],
+ ['properties' => [new FormPropertiesRule()]],
+ );
+
+ expect($validator->passes())->toBeTrue();
+ });
+
it('fails when id is missing', function () {
$rules = [
'properties' => ['required', 'array', new FormPropertiesRule()],
@@ -566,6 +650,11 @@ describe('FormPropertiesRule', function () {
'name' => 'Priority',
'type' => 'select',
'allow_creation' => false,
+ 'select' => [
+ 'options' => [
+ ['name' => 'High'],
+ ],
+ ],
],
[
'id' => 'divider',
@@ -588,6 +677,11 @@ describe('FormPropertiesRule', function () {
$data = [
'properties' => [
+ [
+ 'id' => 'source',
+ 'name' => 'Source',
+ 'type' => 'text',
+ ],
[
'id' => 'title',
'name' => 'Title',
@@ -599,11 +693,11 @@ describe('FormPropertiesRule', function () {
'operatorIdentifier' => 'and',
'children' => [
[
- 'identifier' => 'title',
+ 'identifier' => 'source',
'value' => [
'operator' => 'equals',
'property_meta' => [
- 'id' => 'title',
+ 'id' => 'source',
'type' => 'text',
],
'value' => 'TEST',
@@ -628,6 +722,11 @@ describe('FormPropertiesRule', function () {
$data = [
'properties' => [
+ [
+ 'id' => 'source',
+ 'name' => 'Source',
+ 'type' => 'text',
+ ],
[
'id' => 'text',
'name' => 'Custom Text',
@@ -641,7 +740,7 @@ describe('FormPropertiesRule', function () {
'value' => [
'operator' => 'equals',
'property_meta' => [
- 'id' => 'title',
+ 'id' => 'source',
'type' => 'text',
],
'value' => 'TEST',
@@ -657,7 +756,7 @@ describe('FormPropertiesRule', function () {
$validator = $this->app['validator']->make($data, $rules);
expect($validator->passes())->toBeFalse();
- expect($validator->errors()->has('properties.0.logic'))->toBeTrue();
+ expect($validator->errors()->has('properties.1.logic.actions.0'))->toBeTrue();
});
});
});
diff --git a/api/tests/Unit/Rules/LogicPropertyValidatorTest.php b/api/tests/Unit/Rules/LogicPropertyValidatorTest.php
index a60c586ca..2454c848b 100644
--- a/api/tests/Unit/Rules/LogicPropertyValidatorTest.php
+++ b/api/tests/Unit/Rules/LogicPropertyValidatorTest.php
@@ -1,6 +1,7 @@
<?php
use App\Rules\PropertyValidators\LogicPropertyValidator;
+use App\Service\Forms\FormRegex;
use Tests\TestCase;
uses(TestCase::class);
@@ -54,8 +55,36 @@ describe('LogicPropertyValidator action validation', function () {
],
];
$errors = $validator->validate($property, 0, $context);
- expect($errors)->toHaveKey('logic');
- expect($errors['logic'])->toContain('The logic actions for Name are not valid.');
+ expect($errors)->toHaveKey('logic.actions.0');
+ expect($errors['logic.actions.0'])->toContain('not valid for this field');
+ });
+
+ it('rejects no-op actions that the editor does not offer for the current field state', function () {
+ $validator = new LogicPropertyValidator();
+ $source = ['id' => 'source', 'name' => 'Source', 'type' => 'text'];
+ $property = [
+ 'id' => 'target',
+ 'name' => 'Target',
+ 'type' => 'text',
+ 'hidden' => false,
+ 'required' => false,
+ 'disabled' => false,
+ 'logic' => [
+ 'conditions' => [
+ 'identifier' => 'source',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => ['id' => 'source', 'type' => 'text'],
+ 'value' => 'yes',
+ ],
+ ],
+ 'actions' => ['show-block'],
+ ],
+ ];
+
+ $errors = $validator->validate($property, 0, ['properties' => [$source, $property]]);
+
+ expect($errors['logic.actions.0'])->toContain('not valid for this field');
});
it('fails when nf-text block has require-answer action', function () {
@@ -86,8 +115,8 @@ describe('LogicPropertyValidator action validation', function () {
],
];
$errors = $validator->validate($property, 0, $context);
- expect($errors)->toHaveKey('logic');
- expect($errors['logic'])->toContain('The logic actions for Custom Test are not valid.');
+ expect($errors)->toHaveKey('logic.actions.0');
+ expect($errors['logic.actions.0'])->toContain('not valid for this field');
});
});
@@ -125,9 +154,40 @@ describe('LogicPropertyValidator condition validation', function () {
expect($errors)->toBeEmpty();
});
+ it('accepts browser-compatible regex patterns containing slashes and rejects oversized patterns', function () {
+ $property = [
+ 'id' => 'target',
+ 'name' => 'Target',
+ 'type' => 'text',
+ 'logic' => [
+ 'conditions' => [
+ 'identifier' => 'source',
+ 'value' => [
+ 'operator' => 'matches_regex',
+ 'property_meta' => ['id' => 'source', 'type' => 'text'],
+ 'value' => '^docs/example$',
+ ],
+ ],
+ 'actions' => ['hide-block'],
+ ],
+ ];
+ $validator = new LogicPropertyValidator();
+
+ expect($validator->validate($property, 0, ['properties' => []]))->toBeEmpty();
+
+ $property['logic']['conditions']['value']['value'] = str_repeat('a', FormRegex::MAX_PATTERN_LENGTH + 1);
+ expect($validator->validate($property, 0, ['properties' => []]))
+ ->toHaveKey('logic.conditions.value.value');
+ });
+
it('passes with computed variable conditions', function () {
$validator = new LogicPropertyValidator();
- $context = ['properties' => []];
+ $context = [
+ 'properties' => [],
+ 'computed_variables' => [
+ ['id' => 'cv_total', 'name' => 'Total', 'formula' => '100', 'result_type' => 'number'],
+ ],
+ ];
$property = [
'id' => 'target',
'name' => 'Target',
@@ -159,6 +219,34 @@ describe('LogicPropertyValidator condition validation', function () {
expect($errors)->toBeEmpty();
});
+ it('accepts numeric strings that the runtime evaluates as numbers', function () {
+ $property = [
+ 'id' => 'target',
+ 'name' => 'Target',
+ 'type' => 'text',
+ 'logic' => [
+ 'conditions' => [
+ 'identifier' => 'amount',
+ 'value' => [
+ 'operator' => 'greater_than',
+ 'property_meta' => ['id' => 'amount', 'type' => 'number'],
+ 'value' => '10',
+ ],
+ ],
+ 'actions' => ['hide-block'],
+ ],
+ ];
+
+ $errors = (new LogicPropertyValidator())->validate($property, 0, [
+ 'properties' => [
+ ['id' => 'amount', 'name' => 'Amount', 'type' => 'number'],
+ $property,
+ ],
+ ]);
+
+ expect($errors)->toBeEmpty();
+ });
+
it('fails when condition value is missing', function () {
$validator = new LogicPropertyValidator();
$context = ['properties' => []];
@@ -188,8 +276,8 @@ describe('LogicPropertyValidator condition validation', function () {
],
];
$errors = $validator->validate($property, 0, $context);
- expect($errors)->toHaveKey('logic');
- expect($errors['logic'])->toBe('The logic conditions for Name are not complete. Error detail(s): missing condition value');
+ expect($errors)->toHaveKey('logic.conditions.children.0.value.value');
+ expect($errors['logic.conditions.children.0.value.value'])->toContain('requires a comparison value');
});
it('fails when operator is missing', function () {
@@ -221,8 +309,168 @@ describe('LogicPropertyValidator condition validation', function () {
],
];
$errors = $validator->validate($property, 0, $context);
- expect($errors)->toHaveKey('logic');
- expect($errors['logic'])->toBe('The logic conditions for Name are not complete. Error detail(s): missing operator');
+ expect($errors)->toHaveKey('logic.conditions.operatorIdentifier');
+ expect($errors['logic.conditions.operatorIdentifier'])->toContain('must be "and" or "or"');
+ });
+});
+
+describe('LogicPropertyValidator reference integrity', function () {
+ function propertyWithReference(string $referenceId, string $referenceType = 'text'): array
+ {
+ return [
+ 'id' => 'target',
+ 'name' => 'Target',
+ 'type' => 'text',
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [[
+ 'identifier' => $referenceId,
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => [
+ 'id' => $referenceId,
+ 'type' => $referenceType,
+ ],
+ 'value' => 'yes',
+ ],
+ ]],
+ ],
+ 'actions' => ['hide-block'],
+ ],
+ ];
+ }
+
+ it('reports an unknown field reference at its exact path', function () {
+ $property = propertyWithReference('deleted_field');
+ $errors = (new LogicPropertyValidator())->validate($property, 0, [
+ 'properties' => [$property],
+ 'computed_variables' => [],
+ ]);
+
+ expect($errors)
+ ->toHaveKey('logic.conditions.children.0.value.property_meta.id')
+ ->and($errors['logic.conditions.children.0.value.property_meta.id'])
+ ->toContain('no longer exists');
+ });
+
+ it('reports a stale reference type', function () {
+ $property = propertyWithReference('source', 'number');
+ $errors = (new LogicPropertyValidator())->validate($property, 0, [
+ 'properties' => [
+ $property,
+ ['id' => 'source', 'name' => 'Source', 'type' => 'text'],
+ ],
+ 'computed_variables' => [],
+ ]);
+
+ expect($errors['logic.conditions.children.0.value.property_meta.type'])
+ ->toContain('must be [text]');
+ });
+
+ it('rejects a condition identifier that does not match its reference', function () {
+ $property = propertyWithReference('source');
+ $property['logic']['conditions']['children'][0]['identifier'] = 'stale_source';
+ $errors = (new LogicPropertyValidator())->validate($property, 0, [
+ 'properties' => [
+ $property,
+ ['id' => 'source', 'name' => 'Source', 'type' => 'text'],
+ ],
+ 'computed_variables' => [],
+ ]);
+
+ expect($errors['logic.conditions.children.0.identifier'])
+ ->toContain('must match the referenced item [source]');
+ });
+
+ it('rejects a field referencing itself', function () {
+ $property = propertyWithReference('target');
+ $errors = (new LogicPropertyValidator())->validate($property, 0, [
+ 'properties' => [$property],
+ 'computed_variables' => [],
+ ]);
+
+ expect($errors['logic.conditions.children.0.value.property_meta.id'])
+ ->toContain('cannot reference the same field');
+ });
+
+ it('rejects custom-validation-only operators in display logic', function () {
+ $property = propertyWithReference('source', 'email');
+ $property['logic']['conditions']['children'][0]['value']['operator'] = 'exists_in_submissions';
+ $property['logic']['conditions']['children'][0]['value']['value'] = true;
+ $errors = (new LogicPropertyValidator())->validate($property, 0, [
+ 'properties' => [
+ $property,
+ ['id' => 'source', 'name' => 'Source', 'type' => 'email'],
+ ],
+ 'computed_variables' => [],
+ ]);
+
+ expect($errors['logic.conditions.children.0.value.operator'])
+ ->toContain('only available for custom validation');
+ });
+
+ it('limits nested condition groups', function () {
+ $condition = [
+ 'identifier' => 'source',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => ['id' => 'source', 'type' => 'text'],
+ 'value' => 'yes',
+ ],
+ ];
+
+ foreach (range(1, LogicPropertyValidator::MAX_CONDITION_DEPTH) as $unused) {
+ $condition = ['operatorIdentifier' => 'and', 'children' => [$condition]];
+ }
+
+ $property = [
+ 'id' => 'target',
+ 'name' => 'Target',
+ 'type' => 'text',
+ 'logic' => ['conditions' => $condition, 'actions' => ['hide-block']],
+ ];
+ $errors = (new LogicPropertyValidator())->validate($property, 0, [
+ 'properties' => [
+ $property,
+ ['id' => 'source', 'name' => 'Source', 'type' => 'text'],
+ ],
+ 'computed_variables' => [],
+ ]);
+
+ expect(collect($errors)->contains(fn (string $message) => str_contains($message, 'cannot be nested')))->toBeTrue();
+ });
+
+ it('limits the total number of conditions', function () {
+ $leaf = [
+ 'identifier' => 'source',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => ['id' => 'source', 'type' => 'text'],
+ 'value' => 'yes',
+ ],
+ ];
+ $property = [
+ 'id' => 'target',
+ 'name' => 'Target',
+ 'type' => 'text',
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => array_fill(0, LogicPropertyValidator::MAX_CONDITION_COUNT, $leaf),
+ ],
+ 'actions' => ['hide-block'],
+ ],
+ ];
+ $errors = (new LogicPropertyValidator())->validate($property, 0, [
+ 'properties' => [
+ $property,
+ ['id' => 'source', 'name' => 'Source', 'type' => 'text'],
+ ],
+ 'computed_variables' => [],
+ ]);
+
+ expect(collect($errors)->contains(fn (string $message) => str_contains($message, 'cannot contain more than')))->toBeTrue();
});
});
@@ -340,6 +588,7 @@ describe('LogicPropertyValidator operators without values', function () {
'id' => 'checkbox1',
'name' => 'Checkbox Field',
'type' => 'checkbox',
+ 'hidden' => true,
'logic' => [
'conditions' => [
'operatorIdentifier' => 'and',
@@ -370,6 +619,7 @@ describe('LogicPropertyValidator operators without values', function () {
'id' => 'checkbox1',
'name' => 'Checkbox Field',
'type' => 'checkbox',
+ 'hidden' => true,
'logic' => [
'conditions' => [
'operatorIdentifier' => 'and',
@@ -401,6 +651,7 @@ describe('LogicPropertyValidator operators without values', function () {
'id' => 'checkbox1',
'name' => 'Checkbox Field',
'type' => 'checkbox',
+ 'hidden' => true,
'logic' => [
'conditions' => [
'operatorIdentifier' => 'and',
@@ -451,7 +702,7 @@ describe('LogicPropertyValidator operators without values', function () {
]
];
$errors = $validator->validate($property, 0, $context);
- expect($errors)->toHaveKey('logic');
- expect($errors['logic'])->toBe('The logic conditions for Checkbox Field are not complete. Error detail(s): configuration not found for condition operator');
+ expect($errors)->toHaveKey('logic.conditions.children.0.value.operator');
+ expect($errors['logic.conditions.children.0.value.operator'])->toContain('is not available');
});
});
diff --git a/api/tests/Unit/Rules/SelectOptionsPropertyValidatorTest.php b/api/tests/Unit/Rules/SelectOptionsPropertyValidatorTest.php
index e68f438c5..0a73ef9e2 100644
--- a/api/tests/Unit/Rules/SelectOptionsPropertyValidatorTest.php
+++ b/api/tests/Unit/Rules/SelectOptionsPropertyValidatorTest.php
@@ -194,13 +194,14 @@ describe('SelectOptionsPropertyValidator image size validation', function () {
});
describe('SelectOptionsPropertyValidator options array validation', function () {
- it('skips validation when options not set (legacy format)', function () {
+ it('requires options when they are not set', function () {
$validator = new SelectOptionsPropertyValidator();
$property = [
'type' => 'select',
];
$errors = $validator->validate($property, 0, []);
- expect($errors)->toBeEmpty();
+ expect($errors)->toHaveKey('select.options');
+ expect($errors['select.options'])->toBe('At least one option is required.');
});
it('fails when options is not an array', function () {
@@ -216,6 +217,21 @@ describe('SelectOptionsPropertyValidator options array validation', function ()
expect($errors['select.options'])->toBe('The options must be an array.');
});
+ it('allows an empty option list when respondents can create values', function () {
+ $validator = new SelectOptionsPropertyValidator();
+
+ expect($validator->validate([
+ 'type' => 'select',
+ 'allow_creation' => true,
+ 'select' => ['options' => []],
+ ], 0, []))->toBeEmpty();
+
+ expect($validator->validate([
+ 'type' => 'multi_select',
+ 'allow_creation' => true,
+ ], 0, []))->toBeEmpty();
+ });
+
it('fails when options array is empty', function () {
$validator = new SelectOptionsPropertyValidator();
$property = [
@@ -259,13 +275,13 @@ describe('SelectOptionsPropertyValidator option field validation', function () {
expect($errors['select.options.0.name'])->toBe('The option name is required.');
});
- it('fails when option name is empty string', function () {
+ it('fails when option name contains only whitespace', function () {
$validator = new SelectOptionsPropertyValidator();
$property = [
'type' => 'select',
'select' => [
'options' => [
- ['id' => 'opt1', 'name' => ''],
+ ['id' => 'opt1', 'name' => ' '],
],
],
];
@@ -273,7 +289,7 @@ describe('SelectOptionsPropertyValidator option field validation', function () {
expect($errors)->toHaveKey('select.options.0.name');
});
- it('fails when option id is missing', function () {
+ it('allows an option id to be omitted because response values use option names', function () {
$validator = new SelectOptionsPropertyValidator();
$property = [
'type' => 'select',
@@ -284,11 +300,10 @@ describe('SelectOptionsPropertyValidator option field validation', function () {
],
];
$errors = $validator->validate($property, 0, []);
- expect($errors)->toHaveKey('select.options.0.id');
- expect($errors['select.options.0.id'])->toBe('The option id is required.');
+ expect($errors)->toBeEmpty();
});
- it('fails when option id is empty string', function () {
+ it('allows an empty option id because it is not a response value', function () {
$validator = new SelectOptionsPropertyValidator();
$property = [
'type' => 'select',
@@ -299,10 +314,10 @@ describe('SelectOptionsPropertyValidator option field validation', function () {
],
];
$errors = $validator->validate($property, 0, []);
- expect($errors)->toHaveKey('select.options.0.id');
+ expect($errors)->toBeEmpty();
});
- it('collects multiple errors for same option', function () {
+ it('only reports the missing response name for an otherwise empty option', function () {
$validator = new SelectOptionsPropertyValidator();
$property = [
'type' => 'select',
@@ -313,8 +328,38 @@ describe('SelectOptionsPropertyValidator option field validation', function () {
],
];
$errors = $validator->validate($property, 0, []);
- expect($errors)->toHaveKey('select.options.0.id');
expect($errors)->toHaveKey('select.options.0.name');
+ expect($errors)->toHaveCount(1);
+ });
+
+ it('accepts zero as a string option name', function () {
+ $validator = new SelectOptionsPropertyValidator();
+ $property = [
+ 'type' => 'select',
+ 'select' => [
+ 'options' => [
+ ['id' => '0', 'name' => '0'],
+ ],
+ ],
+ ];
+
+ expect($validator->validate($property, 0, []))->toBeEmpty();
+ });
+
+ it('rejects a non-string option name', function () {
+ $validator = new SelectOptionsPropertyValidator();
+ $property = [
+ 'type' => 'select',
+ 'select' => [
+ 'options' => [
+ ['id' => 'opt1', 'name' => 123],
+ ],
+ ],
+ ];
+
+ $errors = $validator->validate($property, 0, []);
+ expect($errors)->toHaveKey('select.options.0.name');
+ expect($errors['select.options.0.name'])->toBe('The option name must be a string.');
});
});
@@ -462,7 +507,7 @@ describe('SelectOptionsPropertyValidator multi_select type', function () {
expect($errors)->toBeEmpty();
});
- it('reports errors with multi_select prefix', function () {
+ it('allows multi_select options without internal ids', function () {
$validator = new SelectOptionsPropertyValidator();
$property = [
'type' => 'multi_select',
@@ -473,7 +518,7 @@ describe('SelectOptionsPropertyValidator multi_select type', function () {
],
];
$errors = $validator->validate($property, 0, []);
- expect($errors)->toHaveKey('multi_select.options.0.id');
+ expect($errors)->toBeEmpty();
});
it('fails when multi_select options is empty', function () {
@@ -500,7 +545,7 @@ describe('SelectOptionsPropertyValidator multiple options validation', function
'options' => [
['id' => 'opt1', 'name' => 'Option 1'], // Missing image
['id' => 'opt2'], // Missing name and image
- ['name' => 'Option 3', 'image' => 'https://example.com/3.png'], // Missing id
+ ['name' => 'Option 3', 'image' => 'https://example.com/3.png'], // Optional id omitted
],
],
];
@@ -508,7 +553,7 @@ describe('SelectOptionsPropertyValidator multiple options validation', function
expect($errors)->toHaveKey('select.options.0.image');
expect($errors)->toHaveKey('select.options.1.name');
expect($errors)->toHaveKey('select.options.1.image');
- expect($errors)->toHaveKey('select.options.2.id');
+ expect($errors)->not->toHaveKey('select.options.2.id');
});
it('passes with multiple valid options', function () {
diff --git a/api/tests/Unit/Service/Forms/FormDataNormalizerTest.php b/api/tests/Unit/Service/Forms/FormDataNormalizerTest.php
index 8c91d858c..ce34b754a 100644
--- a/api/tests/Unit/Service/Forms/FormDataNormalizerTest.php
+++ b/api/tests/Unit/Service/Forms/FormDataNormalizerTest.php
@@ -28,6 +28,135 @@ it('uses one normalization path for form titles, properties, and select options'
->and($normalized['properties'][0]['id'])->toBeString()->not->toBeEmpty();
});
+it('canonicalizes legacy boolean representations before validating behavior', function () {
+ $normalized = app(FormDataNormalizer::class)->normalizeProperties([
+ [
+ 'id' => 'choice',
+ 'name' => 'Choice',
+ 'type' => 'select',
+ 'hidden' => '0',
+ 'allow_creation' => '1',
+ 'select' => ['options' => []],
+ ],
+ ]);
+
+ expect($normalized[0]['hidden'])->toBeFalse()
+ ->and($normalized[0]['allow_creation'])->toBeTrue();
+});
+
+it('clears invalid optional field settings without discarding the field', function () {
+ $normalized = app(FormDataNormalizer::class)->normalizeProperties([
+ [
+ 'id' => 'message',
+ 'name' => 'Message',
+ 'type' => 'text',
+ 'required' => 'false',
+ 'hidden' => 'not-a-boolean',
+ 'width' => 'oversized',
+ 'align' => 'diagonal',
+ 'max_char_limit' => 0,
+ 'image' => [
+ 'url' => 'not-a-url',
+ 'alt' => 'Unused',
+ ],
+ ],
+ ]);
+
+ expect($normalized[0]['required'])->toBeFalse()
+ ->and($normalized[0]['width'])->toBe('full')
+ ->and($normalized[0])->not->toHaveKeys(['hidden', 'align', 'max_char_limit', 'image'])
+ ->and($normalized[0]['name'])->toBe('Message');
+});
+
+it('backfills a missing block id on every canonical normalization path', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [[
+ 'name' => 'Email address',
+ 'type' => 'email',
+ ]],
+ ]);
+
+ expect($normalized['properties'][0]['id'])->toBeString()->not->toBeEmpty();
+});
+
+it('drops property entries that cannot represent a form block', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [
+ 'not-a-block',
+ ['id' => 'email', 'name' => 'Email', 'type' => 'email'],
+ ],
+ ]);
+
+ expect($normalized['properties'])->toBe([
+ ['id' => 'email', 'name' => 'Email', 'type' => 'email'],
+ ]);
+});
+
+it('normalizes supported field aliases on every authoring path', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [
+ ['id' => 'choice', 'name' => 'Choice', 'type' => 'radio'],
+ ['id' => 'secret', 'name' => 'Secret', 'type' => 'password'],
+ ],
+ ]);
+
+ expect($normalized['properties'][0])->toMatchArray([
+ 'type' => 'select',
+ 'without_dropdown' => true,
+ ])->and($normalized['properties'][1])->toMatchArray([
+ 'type' => 'text',
+ 'secret_input' => true,
+ 'multi_lines' => false,
+ ]);
+});
+
+it('migrates deterministic legacy field aliases and removes obsolete non-fields', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [
+ ['id' => 'long', 'name' => 'Details', 'type' => 'textarea'],
+ ['id' => 'phone', 'name' => 'Phone', 'type' => 'phone'],
+ ['id' => 'copy', 'name' => 'Copy', 'type' => 'html', 'html_content' => '<p>Hello</p>'],
+ ['id' => 'submit', 'name' => 'Submit', 'type' => 'submit', 'button_text' => 'Send it'],
+ ['id' => 'captcha', 'name' => 'Captcha', 'type' => 'captcha'],
+ ],
+ ]);
+
+ expect($normalized['properties'])->toHaveCount(3)
+ ->and($normalized['properties'][0])->toMatchArray(['type' => 'text', 'multi_lines' => true])
+ ->and($normalized['properties'][1]['type'])->toBe('phone_number')
+ ->and($normalized['properties'][2])->toMatchArray(['type' => 'nf-text', 'content' => '<p>Hello</p>'])
+ ->and($normalized['use_captcha'])->toBeTrue()
+ ->and($normalized['submit_button_text'])->toBe('Send it');
+});
+
+it('leaves a malformed field type for localized validation without throwing during alias normalization', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [[
+ 'id' => 'invalid',
+ 'name' => 'Invalid',
+ 'type' => ['text'],
+ ]],
+ ]);
+ $validator = validator($normalized, [
+ 'properties' => ['array', new \App\Rules\FormPropertiesRule()],
+ ]);
+
+ expect($validator->passes())->toBeFalse()
+ ->and($validator->errors()->first('properties.0.type'))->toContain('must be a string');
+});
+
+it('preserves a valid string zero block id', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [[
+ 'id' => '0',
+ 'name' => 'Zero',
+ 'type' => 'text',
+ ]],
+ ]);
+
+ expect($normalized['properties'][0]['id'])->toBe('0');
+});
+
it('preserves strikethrough help text while removing unsafe markup', function () {
$normalized = app(FormDataNormalizer::class)->normalizeProperties([
[
@@ -41,3 +170,275 @@ it('preserves strikethrough help text while removing unsafe markup', function ()
->not->toContain('onclick')
->not->toContain('<script>');
});
+
+it('removes recoverably invalid logic instead of returning a validation burden', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [
+ ['id' => 'source', 'name' => 'Source', 'type' => 'text'],
+ [
+ 'id' => 'target',
+ 'name' => 'Target',
+ 'type' => 'text',
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [],
+ ],
+ 'actions' => ['hide-block'],
+ ],
+ ],
+ ],
+ 'computed_variables' => [],
+ ]);
+
+ expect($normalized['properties'][1])->not->toHaveKey('logic');
+});
+
+it('removes over-nested logic without traversing beyond the validation limit', function () {
+ $condition = [
+ 'identifier' => 'source',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => ['id' => 'source', 'type' => 'text'],
+ 'value' => 'yes',
+ ],
+ ];
+
+ foreach (range(1, 20) as $unused) {
+ $condition = ['operatorIdentifier' => 'and', 'children' => [$condition]];
+ }
+
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [
+ ['id' => 'source', 'name' => 'Source', 'type' => 'text'],
+ [
+ 'id' => 'target',
+ 'name' => 'Target',
+ 'type' => 'text',
+ 'logic' => [
+ 'conditions' => $condition,
+ 'actions' => ['show-block'],
+ ],
+ ],
+ ],
+ 'computed_variables' => [],
+ ]);
+
+ expect($normalized['properties'][1])->not->toHaveKey('logic');
+});
+
+it('repairs certain logic migrations before deciding whether to remove the rule', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [
+ ['id' => 'accepted', 'name' => 'Accepted', 'type' => 'checkbox'],
+ [
+ 'id' => 'details',
+ 'name' => 'Details',
+ 'type' => 'text',
+ 'hidden' => true,
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [[
+ 'identifier' => 'stale-identifier',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => ['id' => 'accepted', 'type' => 'text'],
+ 'value' => true,
+ ],
+ ]],
+ ],
+ 'actions' => ['show-block'],
+ ],
+ ],
+ ],
+ 'computed_variables' => [],
+ ]);
+
+ $condition = $normalized['properties'][1]['logic']['conditions']['children'][0];
+ expect($condition['identifier'])->toBe('accepted')
+ ->and($condition['value']['property_meta']['type'])->toBe('checkbox')
+ ->and($condition['value']['operator'])->toBe('is_checked')
+ ->and($condition['value'])->not->toHaveKey('value');
+});
+
+it('removes only unusable logic actions when valid actions remain', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [
+ ['id' => 'source', 'name' => 'Source', 'type' => 'text'],
+ [
+ 'id' => 'target',
+ 'name' => 'Target',
+ 'type' => 'text',
+ 'logic' => [
+ 'conditions' => [
+ 'identifier' => 'source',
+ 'value' => [
+ 'operator' => 'equals',
+ 'property_meta' => ['id' => 'source', 'type' => 'text'],
+ 'value' => 'yes',
+ ],
+ ],
+ 'actions' => ['hide-block', 'show-block', 'hide-block'],
+ ],
+ ],
+ ],
+ 'computed_variables' => [],
+ ]);
+
+ expect($normalized['properties'][1]['logic']['actions'])->toBe(['hide-block']);
+});
+
+it('drops unusable select options while preserving valid response values', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [[
+ 'id' => 'choice',
+ 'name' => 'Choice',
+ 'type' => 'select',
+ 'select' => [
+ 'options' => [
+ ['id' => null, 'name' => null],
+ ['name' => ' Keep me '],
+ ['name' => ' '],
+ 'invalid-option',
+ ],
+ ],
+ ]],
+ ]);
+
+ expect($normalized['properties'][0]['select']['options'])->toBe([
+ ['name' => 'Keep me', 'id' => 'Keep me'],
+ ]);
+});
+
+it('canonicalizes missing options for a select that allows respondent-created values', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [[
+ 'id' => 'tags',
+ 'name' => 'Tags',
+ 'type' => 'multi_select',
+ 'allow_creation' => true,
+ 'multi_select' => 'invalid',
+ ]],
+ ]);
+
+ expect($normalized['properties'][0]['multi_select'])->toBe(['options' => []]);
+});
+
+it('falls back to safe text option presentation when optional image settings are unusable', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [[
+ 'id' => 'choice',
+ 'name' => 'Choice',
+ 'type' => 'select',
+ 'option_display_mode' => 'image_only',
+ 'option_image_size' => 'huge',
+ 'select' => [
+ 'options' => [
+ ['id' => 'first', 'name' => 'First', 'image' => 'not-a-url'],
+ ],
+ ],
+ ]],
+ ]);
+
+ expect($normalized['properties'][0]['option_display_mode'])->toBe('text_only')
+ ->and($normalized['properties'][0])->not->toHaveKey('option_image_size')
+ ->and($normalized['properties'][0]['select']['options'][0]['name'])->toBe('First')
+ ->and($normalized['properties'][0]['select']['options'][0])->not->toHaveKey('image');
+
+ $validator = validator($normalized, [
+ 'properties' => ['array', new \App\Rules\FormPropertiesRule()],
+ ]);
+ expect($validator->passes())->toBeTrue();
+});
+
+it('removes invalid computed variables and their invalid dependents in cascade', function () {
+ $normalizer = app(FormDataNormalizer::class);
+ $base = [
+ 'properties' => [
+ ['id' => 'amount', 'name' => 'Amount', 'type' => 'number'],
+ [
+ 'id' => 'result',
+ 'name' => 'Result',
+ 'type' => 'text',
+ 'logic' => [
+ 'conditions' => [
+ 'operatorIdentifier' => 'and',
+ 'children' => [[
+ 'identifier' => 'cv_broken',
+ 'value' => [
+ 'operator' => 'greater_than',
+ 'property_meta' => ['id' => 'cv_broken', 'type' => 'computed'],
+ 'value' => 10,
+ ],
+ ]],
+ ],
+ 'actions' => ['show-block'],
+ ],
+ ],
+ ],
+ 'computed_variables' => [
+ [
+ 'id' => 'cv_broken',
+ 'name' => 'Broken',
+ 'formula' => '{missing}',
+ 'result_type' => 'number',
+ ],
+ [
+ 'id' => 'cv_dependent',
+ 'name' => 'Dependent',
+ 'formula' => '{cv_broken} + 1',
+ 'result_type' => 'number',
+ ],
+ [
+ 'id' => 'cv_valid',
+ 'name' => ' Valid ',
+ 'formula' => ' {amount} + 1 ',
+ 'result_type' => 'number',
+ ],
+ ],
+ ];
+
+ $normalized = $normalizer->normalize($base);
+
+ expect($normalized['computed_variables'])->toBe([
+ [
+ 'id' => 'cv_valid',
+ 'name' => 'Valid',
+ 'formula' => '{amount} + 1',
+ 'result_type' => 'number',
+ ],
+ ])->and($normalized['properties'][1])->not->toHaveKey('logic');
+});
+
+it('clears a malformed computed variables collection', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'properties' => [
+ ['id' => 'amount', 'name' => 'Amount', 'type' => 'number'],
+ ],
+ 'computed_variables' => 'invalid',
+ ]);
+
+ expect($normalized['computed_variables'])->toBe([]);
+});
+
+it('is idempotent after applying deterministic repairs', function () {
+ $normalizer = app(FormDataNormalizer::class);
+ $once = $normalizer->normalize([
+ 'properties' => [[
+ 'name' => 'Choice',
+ 'type' => 'select',
+ 'required' => 'true',
+ 'option_display_mode' => 'image_only',
+ 'select' => [
+ 'options' => [
+ ['name' => 'First', 'image' => 'invalid'],
+ ],
+ ],
+ 'logic' => ['conditions' => null, 'actions' => []],
+ ]],
+ 'computed_variables' => 'invalid',
+ ]);
+
+ expect($normalizer->normalize($once))->toBe($once);
+});
diff --git a/api/tests/Unit/Service/Forms/FormLogicConditionCheckerTest.php b/api/tests/Unit/Service/Forms/FormLogicConditionCheckerTest.php
index 8b71b0bde..30b324d4e 100644
--- a/api/tests/Unit/Service/Forms/FormLogicConditionCheckerTest.php
+++ b/api/tests/Unit/Service/Forms/FormLogicConditionCheckerTest.php
@@ -329,6 +329,10 @@ describe('FormLogicConditionChecker', function () {
$formData = ['text_field' => 'invalid'];
expect(FormLogicConditionChecker::conditionsMet($condition, $formData))->toBeFalse();
+ $condition['value']['value'] = '^docs/example$';
+ $formData = ['text_field' => 'docs/example'];
+ expect(FormLogicConditionChecker::conditionsMet($condition, $formData))->toBeTrue();
+
// Test invalid regex pattern
$condition['value']['value'] = '['; // Invalid regex
expect(FormLogicConditionChecker::conditionsMet($condition, $formData))->toBeFalse();
diff --git a/api/tests/Unit/Service/Forms/FormValidationIssueMapperTest.php b/api/tests/Unit/Service/Forms/FormValidationIssueMapperTest.php
new file mode 100644
index 000000000..05fdb4c3c
--- /dev/null
+++ b/api/tests/Unit/Service/Forms/FormValidationIssueMapperTest.php
@@ -0,0 +1,58 @@
+<?php
+
+use App\Service\Forms\FormValidationIssueMapper;
+
+it('maps validation messages to stable issue codes and metadata', function () {
+ $issues = (new FormValidationIssueMapper())->fromErrors([
+ 'properties.2.logic.conditions.children.0.value.property_meta.id' => [
+ 'The referenced field or computed variable [deleted_field] no longer exists.',
+ ],
+ 'computed_variables.1.formula' => [
+ 'Circular dependency detected: Total → Tax → Total',
+ ],
+ ]);
+
+ expect($issues)->toHaveCount(2)
+ ->and($issues[0])->toMatchArray([
+ 'code' => 'unknown_reference',
+ 'path' => 'properties.2.logic.conditions.children.0.value.property_meta.id',
+ 'meta' => ['reference_id' => 'deleted_field'],
+ ])
+ ->and($issues[1]['code'])->toBe('cyclic_dependency');
+});
+
+it('omits aggregate messages and caps the response', function () {
+ $errors = [
+ 'properties' => ['One or more properties have validation errors.'],
+ ];
+
+ foreach (range(1, FormValidationIssueMapper::MAX_ISSUES + 20) as $index) {
+ $errors["properties.{$index}.name"] = ['The field name is required.'];
+ }
+
+ $issues = (new FormValidationIssueMapper())->fromErrors($errors);
+
+ $mapper = new FormValidationIssueMapper();
+
+ expect($issues)->toHaveCount(FormValidationIssueMapper::MAX_ISSUES)
+ ->and($mapper->count($errors))->toBe(FormValidationIssueMapper::MAX_ISSUES + 20)
+ ->and($mapper->summary($mapper->count($errors)))
+ ->toBe('The form contains 120 issues that must be fixed before saving.')
+ ->and(collect($issues)->pluck('message'))->not->toContain('One or more properties have validation errors.');
+});
+
+it('preserves paths in MCP-safe validation messages', function () {
+ $mapper = new FormValidationIssueMapper();
+ $errors = [
+ 'properties.2.logic.conditions.children.0.value.property_meta.id' => [
+ 'The referenced field or computed variable [deleted_field] no longer exists.',
+ ],
+ 'properties' => ['One or more properties have validation errors.'],
+ ];
+
+ expect($mapper->pathErrors($errors))->toBe([
+ 'properties.2.logic.conditions.children.0.value.property_meta.id' => [
+ 'properties.2.logic.conditions.children.0.value.property_meta.id: The referenced field or computed variable [deleted_field] no longer exists.',
+ ],
+ ]);
+});
diff --git a/client/api/forms.js b/client/api/forms.js
index a9a85a4dd..ba8a740ff 100644
--- a/client/api/forms.js
+++ b/client/api/forms.js
@@ -15,6 +15,7 @@ export const formsApi = {
create: (data) => apiService.post('/open/forms', data),
update: (id, data) => apiService.put(`/open/forms/${id}`, data),
+ validateDefinition: (id, data) => apiService.post(`/open/forms/${id}/validate-definition`, data),
delete: (id) => apiService.delete(`/open/forms/${id}`),
duplicate: (id) => apiService.post(`/open/forms/${id}/duplicate`),
diff --git a/client/components/open/forms/components/FormEditor.vue b/client/components/open/forms/components/FormEditor.vue
index 798928095..334589747 100644
--- a/client/components/open/forms/components/FormEditor.vue
+++ b/client/components/open/forms/components/FormEditor.vue
@@ -49,6 +49,30 @@
</template>
</FormEditorNavbar>
+ <div
+ v-if="backgroundValidationIssueCount > 0"
+ class="flex items-center justify-between gap-4 border-b border-amber-200 bg-amber-50 px-4 py-3 text-amber-900"
+ data-testid="form-background-validation-banner"
+ >
+ <div class="flex min-w-0 items-center gap-2">
+ <Icon
+ name="i-heroicons-exclamation-triangle"
+ class="size-5 shrink-0 text-amber-600"
+ />
+ <p class="text-sm">
+ This form has {{ backgroundValidationIssueCount }} {{ backgroundValidationIssueCount === 1 ? 'issue' : 'issues' }} to fix before it can be saved again.
+ </p>
+ </div>
+ <UButton
+ color="warning"
+ variant="soft"
+ size="sm"
+ @click="showValidationErrors"
+ >
+ Review issues
+ </UButton>
+ </div>
+
<FormEditorErrorHandler>
<div class="w-full flex grow min-h-0 overflow-hidden relative bg-white">
<div
@@ -98,13 +122,6 @@
@edit-computed-variable="editInvalidComputedVariable"
/>
- <!-- Logic Confirmation Modal -->
- <LogicConfirmationModal
- :is-visible="showLogicConfirmationModal"
- :errors="logicErrors"
- @cancel="handleLogicConfirmationCancel"
- @confirm="handleLogicConfirmationConfirm"
- />
</div>
<FormEditorSkeleton
v-else
@@ -123,12 +140,10 @@ import FormErrorModal from "./form-components/FormErrorModal.vue"
import FormFieldsEditor from './FormFieldsEditor.vue'
import FormCustomization from "./form-components/FormCustomization.vue"
import FormEditorPreview from "./form-components/FormEditorPreview.vue"
-import { useFormLogic } from "~/composables/forms/useFormLogic.js"
import { captureException } from "@sentry/core"
import FormEditorErrorHandler from '~/components/open/forms/components/FormEditorErrorHandler.vue'
import { setFormDefaults, ensureSettingsObject } from '~/composables/forms/initForm.js'
import { breakpointsTailwind, useBreakpoints } from '@vueuse/core'
-import LogicConfirmationModal from '~/components/forms/heavy/LogicConfirmationModal.vue'
import { formsApi } from "~/api"
import { useResizable } from '~/composables/components/useResizable'
import ResizeHandle from '~/components/global/ResizeHandle.vue'
@@ -173,10 +188,10 @@ const emit = defineEmits(['mounted', 'on-save', 'openRegister', 'go-back', 'save
// Reactive data
const showFormErrorModal = ref(false)
-const showLogicConfirmationModal = ref(false)
const validationErrorResponse = ref(null)
+const hasBackgroundValidationErrors = ref(false)
+const backgroundValidatedFormId = ref(null)
const createdFormSlug = ref(null)
-const logicErrors = ref([])
const formEditorNavbar = ref(null)
const route = useRoute()
const { emitFormSaved, emitNavigateBack } = useEditorEmbedBridge()
@@ -217,6 +232,9 @@ const saveErrorSummary = computed(() => {
form.value?.computed_variables || [],
)
})
+const backgroundValidationIssueCount = computed(() => {
+ return hasBackgroundValidationErrors.value ? saveErrorSummary.value.issueCount : 0
+})
watch(
() => form.value,
@@ -289,6 +307,52 @@ const showValidationErrors = () => {
showFormErrorModal.value = true
}
+const validateLoadedForm = () => {
+ if (!props.isEdit || !form.value?.id || typeof form.value.data !== 'function') {
+ return
+ }
+
+ const validatedFormId = form.value.id
+ const definition = setFormDefaults(form.value.data())
+ validationErrorResponse.value = null
+ hasBackgroundValidationErrors.value = false
+ backgroundValidatedFormId.value = validatedFormId
+ formsApi.validateDefinition(validatedFormId, definition)
+ .then(() => {
+ if (form.value?.id !== validatedFormId) {
+ return
+ }
+
+ hasBackgroundValidationErrors.value = false
+ })
+ .catch((error) => {
+ if (form.value?.id !== validatedFormId) {
+ return
+ }
+
+ const errorStatus = error?.response?.status || error?.status
+ if (errorStatus === 422) {
+ validationErrorResponse.value = error.data
+ hasBackgroundValidationErrors.value = true
+ return
+ }
+
+ captureException(error)
+ })
+}
+
+watch(
+ () => form.value?.id,
+ (id) => {
+ if (!props.isEdit || !id || backgroundValidatedFormId.value === id) {
+ return
+ }
+
+ nextTick(validateLoadedForm)
+ },
+ { immediate: true },
+)
+
const handleFormErrorModalClose = () => {
showFormErrorModal.value = false
@@ -348,26 +412,10 @@ const saveForm = () => {
// Apply defaults to the form
const defaultedData = setFormDefaults(form.value.data())
form.value.fill(defaultedData)
-
- // Check for logic errors
- const { getLogicErrors } = useFormLogic()
- logicErrors.value = getLogicErrors(form.value.properties)
-
- if (logicErrors.value.length > 0) {
- showLogicConfirmationModal.value = true
- return
- }
-
proceedWithSave()
}
const proceedWithSave = () => {
- if (logicErrors.value.length > 0) {
- // Clean invalid logic before saving using the comprehensive validator
- const { validatePropertiesLogic } = useFormLogic()
- form.value.properties = validatePropertiesLogic(form.value.properties)
- }
-
if (props.saveHandler) {
props.saveHandler(form.value.data())
return
@@ -382,19 +430,11 @@ const proceedWithSave = () => {
}
}
-const handleLogicConfirmationCancel = () => {
- showLogicConfirmationModal.value = false
-}
-
-const handleLogicConfirmationConfirm = () => {
- showLogicConfirmationModal.value = false
- proceedWithSave()
-}
-
const saveFormEdit = () => {
if (form.value.busy || !form.value.id) return
validationErrorResponse.value = null
+ hasBackgroundValidationErrors.value = false
form.value.mutate(updateMutation).then((response) => {
const updatedForm = response.form
@@ -430,6 +470,7 @@ const saveFormEdit = () => {
if (errorStatus === 422) {
validationErrorResponse.value = error.data
+ hasBackgroundValidationErrors.value = true
showValidationErrors()
} else {
console.error(error)
@@ -452,6 +493,7 @@ const saveFormCreate = () => {
// Attach workspace ID before sending
form.value.workspace_id = workspace.value.id
validationErrorResponse.value = null
+ hasBackgroundValidationErrors.value = false
form.value.mutate(createMutation).then((response) => {
const newForm = response.form
@@ -494,6 +536,7 @@ const saveFormCreate = () => {
if (errorStatus === 422) {
validationErrorResponse.value = error.data
+ hasBackgroundValidationErrors.value = true
showValidationErrors()
} else {
useAlert().error(
@@ -518,13 +561,14 @@ onMounted(() => {
emit("mounted")
workingFormStore.activeTab = 'build'
amplitude.logEvent('form_editor_viewed')
-
+
if (!props.isEdit) {
nextTick(() => {
workingFormStore.openAddFieldSidebar()
})
}
})
+
</script>
<style lang="scss">
diff --git a/client/composables/forms/initForm.js b/client/composables/forms/initForm.js
index f2c7fdda4..60a9000be 100644
--- a/client/composables/forms/initForm.js
+++ b/client/composables/forms/initForm.js
@@ -1,6 +1,6 @@
import clonedeep from 'clone-deep'
import { isReadonly } from 'vue'
-import { generateUUID } from "~/lib/utils.js"
+import { generateUUID } from "../../lib/utils.js"
export const DEFAULT_COLOR = '#3B82F6'
export const initForm = (defaultValue = {}, withDefaultProperties = false) => {
@@ -132,14 +132,14 @@ export function setFormDefaults(formData) {
}
}
- // Handle required nested properties
- if (filledFormData.properties && Array.isArray(filledFormData.properties)) {
- filledFormData.properties = filledFormData.properties.map(property => ({
- ...property,
- name: property.name === '' || property.name === null || property.name === undefined ? 'Untitled' : property.name,
- }))
- }
-
+ // Entries that are not objects cannot represent form blocks. Discarding
+ // them prevents legacy malformed data from breaking the editor while real
+ // blocks remain available for localized validation.
+ const properties = Array.isArray(filledFormData.properties) ? filledFormData.properties : []
+ filledFormData.properties = properties.filter(property => {
+ return property !== null && typeof property === 'object' && !Array.isArray(property)
+ })
+
// Ensure settings object exists and is a plain object (not a readonly proxy)
ensureSettingsObject(filledFormData)
diff --git a/client/pages/agent-drafts/edit.vue b/client/pages/agent-drafts/edit.vue
index 546b3d89d..6231b5644 100644
--- a/client/pages/agent-drafts/edit.vue
+++ b/client/pages/agent-drafts/edit.vue
@@ -143,8 +143,22 @@ const performSync = (rawData, keepalive = false) => {
body: { expected_version: version.value, definition },
keepalive,
}).then((response) => {
+ const serverDefinition = cleanDefinition(response.draft.definition)
+ const serverFingerprint = JSON.stringify(serverDefinition)
+ const currentData = workingFormStore.content?.data?.()
+ const currentFingerprint = currentData
+ ? JSON.stringify(cleanDefinition(currentData))
+ : null
+
version.value = response.draft.version
- lastSavedFingerprint.value = JSON.stringify(cleanDefinition(response.draft.definition))
+ lastSavedFingerprint.value = serverFingerprint
+
+ // Reflect deterministic server cleanups without overwriting edits made
+ // while this request was in flight.
+ if (currentFingerprint === fingerprint && serverFingerprint !== fingerprint) {
+ workingFormStore.set(useForm(serverDefinition))
+ }
+
syncState.value = 'saved'
}).catch((exception) => {
syncState.value = 'error'
diff --git a/client/pages/forms/[slug]/edit.vue b/client/pages/forms/[slug]/edit.vue
index 6958daabc..21ddb14e0 100644
--- a/client/pages/forms/[slug]/edit.vue
+++ b/client/pages/forms/[slug]/edit.vue
@@ -35,6 +35,7 @@
<script setup>
import FormEditor from "~/components/open/forms/components/FormEditor.vue"
+import { setFormDefaults } from "~/composables/forms/initForm.js"
import { hash } from "~/lib/utils.js"
// Composables
@@ -83,7 +84,7 @@ function initUpdatedForm() {
return
}
- updatedForm.value = useForm(form.value)
+ updatedForm.value = useForm(setFormDefaults(form.value))
if (!updatedForm.value) {
return
}
diff --git a/client/test/unit/init-form-defaults.test.ts b/client/test/unit/init-form-defaults.test.ts
new file mode 100644
index 000000000..dd550cfc9
--- /dev/null
+++ b/client/test/unit/init-form-defaults.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest'
+import { setFormDefaults } from '../../composables/forms/initForm.js'
+
+describe('setFormDefaults', () => {
+ it('does not invent respondent-facing field labels', () => {
+ const result = setFormDefaults({
+ properties: [
+ { id: 'missing', type: 'text' },
+ { id: 'blank', name: '', type: 'email' },
+ ],
+ })
+
+ expect(result.properties[0]).not.toHaveProperty('name')
+ expect(result.properties[1].name).toBe('')
+ })
+
+ it('discards entries that cannot represent form blocks', () => {
+ const result = setFormDefaults({
+ properties: [
+ 'malformed',
+ null,
+ ['also-malformed'],
+ { id: 'kept', name: 'Kept', type: 'text' },
+ ],
+ })
+
+ expect(result.properties).toEqual([
+ { id: 'kept', name: 'Kept', type: 'text' },
+ ])
+ expect(setFormDefaults({ properties: 'malformed' }).properties).toEqual([])
+ })
+})
diff --git a/docs/integrations/mcp.mdx b/docs/integrations/mcp.mdx
index 81777eb8f..a369d8372 100644
--- a/docs/integrations/mcp.mdx
+++ b/docs/integrations/mcp.mdx
@@ -208,6 +208,54 @@ Workspace administration and submission mutations are unavailable. MCP does not
Normal workspace permissions and plan limits continue to apply. If saving a form disables unavailable premium features, the tool response lists those changes.
+Before validating or saving a definition, OpnForm silently normalizes issues it can repair without guessing intent. For example, it removes empty or invalid display-logic blocks, repairs stale logic reference metadata, discards unusable entries from select options, and removes invalid computed variables together with formulas or logic that become invalid as a result. Ambiguous changes still return a precise error path, such as an empty select field, a duplicate field ID, or a malformed form block.
+
+### Computed variables and display logic
+
+The versioned form-definition schema and field catalog document computed variables, display-logic actions, condition groups, and the operators available for each reference type. Formula references use technical IDs in braces:
+
+```json
+{
+ "computed_variables": [
+ {
+ "id": "cv_priority_score",
+ "name": "Priority score",
+ "formula": "{budget} * 1.2",
+ "result_type": "number"
+ }
+ ]
+}
+```
+
+A logic condition may use that calculated value by setting `property_meta.type` to `computed`:
+
+```json
+{
+ "hidden": true,
+ "logic": {
+ "conditions": {
+ "operatorIdentifier": "and",
+ "children": [
+ {
+ "identifier": "cv_priority_score",
+ "value": {
+ "operator": "greater_than",
+ "property_meta": {
+ "id": "cv_priority_score",
+ "type": "computed"
+ },
+ "value": 10000
+ }
+ }
+ ]
+ },
+ "actions": ["show-block"]
+ }
+}
+```
+
+With `patch_form_draft`, replace the complete `computed_variables` list through `set_form_values`, and add or modify a block's `logic` through `add_block` or `update_block`. The draft is normalized and validated atomically before its version changes.
+
## Self-hosted OAuth configuration
The following settings apply only to self-hosted instances.
diff --git a/plugins/opnform/skills/opnform/references/form-authoring.md b/plugins/opnform/skills/opnform/references/form-authoring.md
index 48b2b3ee3..202e8d6d0 100644
--- a/plugins/opnform/skills/opnform/references/form-authoring.md
+++ b/plugins/opnform/skills/opnform/references/form-authoring.md
@@ -29,6 +29,48 @@ Incorrect:
}
```
+## Computed variables and display logic
+
+- A computed variable needs a unique `id` beginning with `cv_`, a unique human-readable `name`, and a non-empty `formula`. Reference block and variable IDs with braces, for example `{budget} * 1.2`.
+- Attach `logic` to the block whose behavior should change. A condition must reference another block or variable; it cannot reference its own target block.
+- Keep `identifier` equal to `value.property_meta.id`. Use the referenced block type in `property_meta.type`, or `computed` for a computed variable.
+- Read `operators_by_reference_type` from `opnform://reference/form-fields/v1` instead of guessing an operator. Use only actions listed by the schema and let `validate_form_definition` check whether each action is compatible with the target block.
+- To revise a draft, replace the complete `computed_variables` list through `set_form_values`, and add, replace, or clear a block's `logic` through `add_block` or `update_block`.
+
+Example:
+
+```json
+{
+ "computed_variables": [
+ {
+ "id": "cv_priority_score",
+ "name": "Priority score",
+ "formula": "{budget} * 1.2",
+ "result_type": "number"
+ }
+ ],
+ "logic": {
+ "conditions": {
+ "operatorIdentifier": "and",
+ "children": [
+ {
+ "identifier": "cv_priority_score",
+ "value": {
+ "operator": "greater_than",
+ "property_meta": {
+ "id": "cv_priority_score",
+ "type": "computed"
+ },
+ "value": 10000
+ }
+ }
+ ]
+ },
+ "actions": ["show-block"]
+ }
+}
+```
+
## `nf-text` uses HTML
The `content` property of an `nf-text` block is a sanitized HTML fragment. Never use Markdown syntax such as `# Heading`, `**bold**`, Markdown links, or fenced code blocks.