@ng-forge/dynamic-forms 0.8.0-next.3 → 0.8.0-next.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/fesm2022/ng-forge-dynamic-forms-array-field.component-CJ_OclbR.mjs +1005 -0
- package/fesm2022/ng-forge-dynamic-forms-array-field.component-CJ_OclbR.mjs.map +1 -0
- package/fesm2022/ng-forge-dynamic-forms-container-field.component-DQ_OQLtx.mjs +92 -0
- package/fesm2022/ng-forge-dynamic-forms-container-field.component-DQ_OQLtx.mjs.map +1 -0
- package/fesm2022/ng-forge-dynamic-forms-container-utils-zQSTe7Jk.mjs +49 -0
- package/fesm2022/ng-forge-dynamic-forms-container-utils-zQSTe7Jk.mjs.map +1 -0
- package/fesm2022/{ng-forge-dynamic-forms-css-wrapper.component-CGNGJoqv.mjs → ng-forge-dynamic-forms-css-wrapper.component-2fdmbtL7.mjs} +2 -2
- package/fesm2022/{ng-forge-dynamic-forms-css-wrapper.component-CGNGJoqv.mjs.map → ng-forge-dynamic-forms-css-wrapper.component-2fdmbtL7.mjs.map} +1 -1
- package/fesm2022/ng-forge-dynamic-forms-emit-initialization-pCNwBRRm.mjs +29 -0
- package/fesm2022/ng-forge-dynamic-forms-emit-initialization-pCNwBRRm.mjs.map +1 -0
- package/fesm2022/ng-forge-dynamic-forms-group-field.component-BdLdSEHj.mjs +186 -0
- package/fesm2022/ng-forge-dynamic-forms-group-field.component-BdLdSEHj.mjs.map +1 -0
- package/fesm2022/{ng-forge-dynamic-forms-ng-forge-dynamic-forms-BwoONrnj.mjs → ng-forge-dynamic-forms-ng-forge-dynamic-forms-BdMxsqmk.mjs} +12330 -13667
- package/fesm2022/ng-forge-dynamic-forms-ng-forge-dynamic-forms-BdMxsqmk.mjs.map +1 -0
- package/fesm2022/{ng-forge-dynamic-forms-page-field.component-DV-EX9U0.mjs → ng-forge-dynamic-forms-page-field.component-C5rUo80O.mjs} +3 -2
- package/fesm2022/{ng-forge-dynamic-forms-page-field.component-DV-EX9U0.mjs.map → ng-forge-dynamic-forms-page-field.component-C5rUo80O.mjs.map} +1 -1
- package/fesm2022/{ng-forge-dynamic-forms-text-field.component-CHC8v87r.mjs → ng-forge-dynamic-forms-text-field.component-lvuyTM1r.mjs} +2 -2
- package/fesm2022/{ng-forge-dynamic-forms-text-field.component-CHC8v87r.mjs.map → ng-forge-dynamic-forms-text-field.component-lvuyTM1r.mjs.map} +1 -1
- package/fesm2022/ng-forge-dynamic-forms.mjs +1 -1
- package/package.json +1 -1
- package/types/ng-forge-dynamic-forms.d.ts +7 -8
- package/fesm2022/ng-forge-dynamic-forms-ng-forge-dynamic-forms-BwoONrnj.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ng-forge-dynamic-forms-ng-forge-dynamic-forms-BwoONrnj.mjs","sources":["../../../../packages/dynamic-forms/src/lib/models/wrapper-type.ts","../../../../packages/dynamic-forms/src/lib/errors/dynamic-form-error.ts","../../../../packages/dynamic-forms/src/lib/models/field-signal-context.token.ts","../../../../packages/dynamic-forms/src/lib/utils/wrapper-chain/wrapper-chain.ts","../../../../packages/dynamic-forms/src/lib/providers/features/logger/logger.token.ts","../../../../packages/dynamic-forms/src/lib/utils/resolve-wrappers/resolve-wrappers.ts","../../../../packages/dynamic-forms/src/lib/utils/wrapper-chain/wrapper-chain-controller.ts","../../../../packages/dynamic-forms/src/lib/core/field-tree-utils.ts","../../../../packages/dynamic-forms/src/lib/directives/df-field-outlet.directive.ts","../../../../packages/dynamic-forms/src/lib/utils/submission-handler/submission-handler.ts","../../../../packages/dynamic-forms/src/lib/providers/features/event-form-value/emit-form-value.token.ts","../../../../packages/dynamic-forms/src/lib/core/registry/root-form-registry.service.ts","../../../../packages/dynamic-forms/src/lib/providers/features/logger/noop-logger.ts","../../../../packages/dynamic-forms/src/lib/events/event.bus.ts","../../../../packages/dynamic-forms/src/lib/events/constants/submit.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/component-initialized.event.ts","../../../../packages/dynamic-forms/src/lib/utils/initialization-tracker/initialization-tracker.ts","../../../../packages/dynamic-forms/src/lib/definitions/default/hidden-field.ts","../../../../packages/dynamic-forms/src/lib/definitions/default/group-field.ts","../../../../packages/dynamic-forms/src/lib/definitions/default/row-field.ts","../../../../packages/dynamic-forms/src/lib/definitions/default/page-field.ts","../../../../packages/dynamic-forms/src/lib/definitions/default/array-field.ts","../../../../packages/dynamic-forms/src/lib/definitions/default/container-field.ts","../../../../packages/dynamic-forms/src/lib/models/types/type-guards.ts","../../../../packages/dynamic-forms/src/lib/utils/debounce/debounce.ts","../../../../packages/dynamic-forms/src/lib/utils/object-utils.ts","../../../../packages/dynamic-forms/src/lib/core/registry/function-registry.service.ts","../../../../packages/dynamic-forms/src/lib/core/registry/schema-registry.service.ts","../../../../packages/dynamic-forms/src/lib/utils/deprecation-warning-tracker.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/value-utils.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/field-state-extractor.ts","../../../../packages/dynamic-forms/src/lib/utils/safe-read-path-keys.ts","../../../../packages/dynamic-forms/src/lib/core/registry/field-context-registry.service.ts","../../../../packages/dynamic-forms/src/lib/utils/path-utils/path-utils.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/parser/types.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/parser/tokenizer.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/parser/parser.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/parser/evaluator.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/parser/expression-parser.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/condition-evaluator.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-types.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-constants.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/field-value-utils.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-applicator.ts","../../../../packages/dynamic-forms/src/lib/models/logic/logic-config.ts","../../../../packages/dynamic-forms/src/lib/core/cross-field/cross-field-detector.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-sorter.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-collector.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/cycle-detector.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-warning-tracker.ts","../../../../packages/dynamic-forms/src/lib/core/http/http-request-resolver.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/http-derivation-stream.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/async-derivation-stream.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-orchestrator.ts","../../../../packages/dynamic-forms/src/lib/core/property-derivation/property-derivation-applicator.ts","../../../../packages/dynamic-forms/src/lib/core/property-derivation/property-override-key.ts","../../../../packages/dynamic-forms/src/lib/core/property-derivation/property-derivation-collector.ts","../../../../packages/dynamic-forms/src/lib/core/property-derivation/property-derivation-orchestrator.ts","../../../../packages/dynamic-forms/src/lib/events/constants/next-page.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/page-change.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/previous-page.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/form-reset.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/form-clear.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/append-array-item.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/prepend-array-item.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/insert-array-item.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/pop-array-item.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/shift-array-item.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/move-array-item.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/remove-at-index.event.ts","../../../../packages/dynamic-forms/src/lib/events/constants/page-navigation-state-change.event.ts","../../../../packages/dynamic-forms/src/lib/core/page-orchestrator/page-orchestrator.component.ts","../../../../packages/dynamic-forms/src/lib/utils/array-field/normalized-array-metadata.ts","../../../../packages/dynamic-forms/src/lib/utils/array-field/normalize-simplified-arrays.ts","../../../../packages/dynamic-forms/src/lib/models/types/form-mode.ts","../../../../packages/dynamic-forms/src/lib/models/validation/validator-config.ts","../../../../packages/dynamic-forms/src/lib/core/http/http-response-evaluator.ts","../../../../packages/dynamic-forms/src/lib/utils/stable-stringify.ts","../../../../packages/dynamic-forms/src/lib/core/http/http-condition-cache.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/http-condition-function-cache.service.ts","../../../../packages/dynamic-forms/src/lib/utils/resource-composition/with-previous-value.ts","../../../../packages/dynamic-forms/src/lib/utils/derived-from-deferred/derived-from-deferred.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/http-condition-logic-function.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/async-condition-function-cache.service.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/async-condition-logic-function.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/logic-function-cache.service.ts","../../../../packages/dynamic-forms/src/lib/core/expressions/logic-function-factory.ts","../../../../packages/dynamic-forms/src/lib/core/values/dynamic-value-function-cache.service.ts","../../../../packages/dynamic-forms/src/lib/core/values/dynamic-value-factory.ts","../../../../packages/dynamic-forms/src/lib/core/validation/validator-factory.ts","../../../../packages/dynamic-forms/src/lib/core/logic/logic-applicator.ts","../../../../packages/dynamic-forms/src/lib/core/values/type-predicate-factory.ts","../../../../packages/dynamic-forms/src/lib/core/schema-application.ts","../../../../packages/dynamic-forms/src/lib/core/form-mapping.ts","../../../../packages/dynamic-forms/src/lib/models/field-type.ts","../../../../packages/dynamic-forms/src/lib/utils/default-value/default-value.ts","../../../../packages/dynamic-forms/src/lib/core/form-schema-merger.ts","../../../../packages/dynamic-forms/src/lib/core/schema-builder.ts","../../../../packages/dynamic-forms/src/lib/core/cross-field/cross-field-collector.ts","../../../../packages/dynamic-forms/src/lib/utils/flattener/field-flattener.ts","../../../../packages/dynamic-forms/src/lib/utils/container-utils/container-field-processors.ts","../../../../packages/dynamic-forms/src/lib/utils/grid-classes/grid-classes.ts","../../../../packages/dynamic-forms/src/lib/mappers/base/base-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/core/property-derivation/property-override-store.ts","../../../../packages/dynamic-forms/src/lib/core/property-derivation/apply-property-overrides.ts","../../../../packages/dynamic-forms/src/lib/utils/field-mapper/field-mapper.ts","../../../../packages/dynamic-forms/src/lib/utils/resolve-field/resolve-field.ts","../../../../packages/dynamic-forms/src/lib/utils/form-validation/form-mode-validator.ts","../../../../packages/dynamic-forms/src/lib/utils/inject-field-registry/inject-field-registry.ts","../../../../packages/dynamic-forms/src/lib/utils/config-validation/config-validator.ts","../../../../packages/dynamic-forms/src/lib/providers/features/value-exclusion/value-exclusion.token.ts","../../../../packages/dynamic-forms/src/lib/utils/value-filter/value-filter.ts","../../../../packages/dynamic-forms/src/lib/state/state-types.ts","../../../../packages/dynamic-forms/src/lib/state/side-effect-scheduler.ts","../../../../packages/dynamic-forms/src/lib/state/form-state-machine.ts","../../../../packages/dynamic-forms/src/lib/state/form-state-manager.ts","../../../../packages/dynamic-forms/src/lib/core/derivation/derivation-logger.service.ts","../../../../packages/dynamic-forms/src/lib/providers/features/dynamic-form-feature.ts","../../../../packages/dynamic-forms/src/lib/providers/features/logger/console-logger.ts","../../../../packages/dynamic-forms/src/lib/providers/features/logger/with-logger-config.ts","../../../../packages/dynamic-forms/src/lib/providers/dynamic-form-di.ts","../../../../packages/dynamic-forms/src/lib/events/event-dispatcher.ts","../../../../packages/dynamic-forms/src/lib/dynamic-form.component.ts","../../../../packages/dynamic-forms/src/lib/core/logic/non-field-logic-resolver.ts","../../../../packages/dynamic-forms/src/lib/mappers/apply-hidden-logic.ts","../../../../packages/dynamic-forms/src/lib/mappers/array/array-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/mappers/group/group-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/mappers/row/row-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/mappers/page/page-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/mappers/text/text-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/mappers/container/container-field-mapper.ts","../../../../packages/dynamic-forms/src/lib/providers/built-in-fields.ts","../../../../packages/dynamic-forms/src/lib/wrappers/create-wrappers.ts","../../../../packages/dynamic-forms/src/lib/providers/dynamic-form-providers.ts","../../../../packages/dynamic-forms/src/lib/providers/features/event-form-value/with-event-form-value.ts","../../../../packages/dynamic-forms/src/lib/events/interfaces/form-event.ts","../../../../packages/dynamic-forms/src/lib/providers/features/value-exclusion/with-value-exclusion-defaults.ts","../../../../packages/dynamic-forms/src/lib/wrappers/wrapper-props.ts","../../../../packages/dynamic-forms/src/lib/definitions/base/base-value-field.ts","../../../../packages/dynamic-forms/src/lib/definitions/base/base-checked-field.ts","../../../../packages/dynamic-forms/src/lib/events/array-event.ts","../../../../packages/dynamic-forms/src/lib/events/utils/token-resolver.ts","../../../../packages/dynamic-forms/src/lib/events/index.ts","../../../../packages/dynamic-forms/src/lib/helpers/form-config.ts","../../../../packages/dynamic-forms/src/lib/helpers/create-field.ts","../../../../packages/dynamic-forms/src/lib/utils/dynamic-text-to-observable.ts","../../../../packages/dynamic-forms/src/lib/utils/apply-meta.ts","../../../../packages/dynamic-forms/src/lib/pipes/dynamic-text/dynamic-text.pipe.ts","../../../../packages/dynamic-forms/src/lib/utils/emit-initialization/emit-initialization.ts","../../../../packages/dynamic-forms/src/lib/utils/container-utils/container-utils.ts","../../../../packages/dynamic-forms/src/lib/fields/group/group-field.component.ts","../../../../packages/dynamic-forms/src/lib/utils/array-field/array-field.types.ts","../../../../packages/dynamic-forms/src/lib/utils/array-field/create-array-item-injector.ts","../../../../packages/dynamic-forms/src/lib/utils/array-field/resolve-array-item.ts","../../../../packages/dynamic-forms/src/lib/utils/array-field/array-event-handler.ts","../../../../packages/dynamic-forms/src/lib/fields/array/array-field.component.ts","../../../../packages/dynamic-forms/src/lib/fields/container/container-field.component.ts","../../../../packages/dynamic-forms/src/lib/utils/interpolate-params.ts","../../../../packages/dynamic-forms/src/lib/index.ts","../../../../packages/dynamic-forms/src/ng-forge-dynamic-forms.ts"],"sourcesContent":["import { InjectionToken, Signal, Type, ViewContainerRef } from '@angular/core';\nimport { FieldRegistryWrappers, RegisteredWrapperTypes } from './registry/field-registry';\n\n/**\n * Resolves a wrapper type name to its registered config interface.\n *\n * When `TWrappers` is a specific registered key (e.g., `'css'`), resolves to\n * the full config type from `FieldRegistryWrappers` (e.g., `CssWrapper`),\n * providing type-safe access to wrapper-specific properties like `cssClasses`.\n *\n * When `TWrappers` is the full `RegisteredWrapperTypes` union, distributes\n * to produce a discriminated union of all registered wrapper configs.\n *\n * @example\n * ```typescript\n * // Resolves to CssWrapper — cssClasses is typed\n * type CssConfig = WrapperConfig<'css'>;\n *\n * // Union of all registered wrapper configs\n * type AnyConfig = WrapperConfig;\n * ```\n */\n\nexport type WrapperConfig<TWrappers extends RegisteredWrapperTypes = RegisteredWrapperTypes> = TWrappers extends keyof FieldRegistryWrappers\n ? FieldRegistryWrappers[TWrappers]\n : { readonly type: TWrappers };\n\n/**\n * Signature of a lazy component loader — either a direct component class or\n * an ES module whose `default` export is the component. Shared by field and\n * wrapper registrations so the `loadComponent: () => import('./x.component')`\n * idiom types cleanly in both places.\n */\nexport type LazyComponentLoader<T = unknown> = () => Promise<Type<T> | { default: Type<T> }>;\n\n/**\n * Pre-computed reverse index used by `resolveWrappers`: field type → the\n * wrappers that auto-apply to it. Built once in the `provideDynamicForm(...)`\n * factory from every registered `WrapperTypeDefinition.types` entry.\n */\nexport type WrapperAutoAssociations = ReadonlyMap<string, readonly WrapperConfig[]>;\n\n/**\n * Configuration interface for registering wrapper types.\n *\n * Defines how a wrapper component is loaded and identified. Wrapper components\n * provide visual decoration around field content (sections, headers, styling)\n * without affecting the form data structure.\n *\n * @example\n * ```typescript\n * const SectionWrapper: WrapperTypeDefinition = {\n * name: 'section',\n * loadComponent: () => import('./section-wrapper.component').then(m => m.SectionWrapperComponent),\n * };\n * ```\n */\nexport interface WrapperTypeDefinition<T extends WrapperConfig = WrapperConfig> {\n /** Unique identifier for the wrapper type (also serves as discriminant from FieldTypeDefinition) */\n wrapperName: string;\n /** Wrapper definition type marker (internal use) */\n _wrapper?: T;\n /**\n * Function to load the wrapper component (supports lazy loading).\n * Returns a Promise that resolves to the component class or module with default export.\n */\n loadComponent: LazyComponentLoader;\n /**\n * Field types this wrapper should auto-apply to.\n *\n * When a field's `type` matches any entry, the wrapper is injected into that\n * field's effective wrapper chain at the lowest priority (can be overridden\n * by `FormConfig.defaultWrappers` or the field-level `wrappers` array, and\n * fully cleared with `wrappers: null`).\n */\n types?: readonly string[];\n}\n\n/**\n * Type guard for WrapperTypeDefinition.\n *\n * Discriminates via `wrapperName` — field types use `name`, wrapper types use `wrapperName`.\n */\nexport function isWrapperTypeDefinition(value: unknown): value is WrapperTypeDefinition {\n return typeof value === 'object' && value !== null && 'wrapperName' in value;\n}\n\n/**\n * Contract that wrapper components must satisfy.\n *\n * Each wrapper exposes a `#fieldComponent` ViewContainerRef where the inner\n * content (next wrapper, or the field) is rendered imperatively. Config\n * properties (minus `type`) are set on the component via `setInput`; a\n * wrapper opts into a key by declaring a matching `input()`, and unknown\n * keys are silently dropped. Wrappers may additionally declare a\n * `fieldInputs` input for the wrapped field's mapper outputs (see\n * `WrapperFieldInputs` for when that's undefined).\n *\n * @example\n * ```typescript\n * @Component({\n * template: `\n * <dbx-section [header]=\"header() ?? ''\">\n * <ng-container #fieldComponent></ng-container>\n * </dbx-section>\n * `,\n * })\n * export class SectionWrapperComponent implements FieldWrapperContract {\n * readonly fieldComponent = viewChild.required('fieldComponent', { read: ViewContainerRef });\n * readonly header = input<string>();\n * readonly fieldInputs = input<WrapperFieldInputs>();\n * }\n * ```\n */\nexport interface FieldWrapperContract {\n /** ViewContainerRef slot where inner content is rendered */\n readonly fieldComponent: Signal<ViewContainerRef>;\n}\n\n/**\n * Injection token for the wrapper type registry.\n *\n * Provides access to the map of registered wrapper types. The registry is\n * populated via `provideDynamicForm()` and used by `ContainerFieldComponent` to\n * resolve wrapper types to their component implementations.\n */\nexport const WRAPPER_REGISTRY = new InjectionToken<Map<string, WrapperTypeDefinition>>('WRAPPER_REGISTRY', {\n providedIn: 'root',\n factory: () => new Map(),\n});\n\n/**\n * Component cache for loaded wrapper components.\n *\n * Caches resolved wrapper component classes for instant re-resolution.\n * SSR-safe because it's DI-scoped, not module-scoped.\n *\n * NOTE: The cache grows across the application lifetime. It's bounded by the\n * number of wrapper types registered (typically small), so this is not a leak;\n * the COMPONENT_CACHE for field types has the same shape.\n */\nexport const WRAPPER_COMPONENT_CACHE = new InjectionToken<Map<string, Type<unknown>>>('WRAPPER_COMPONENT_CACHE', {\n providedIn: 'root',\n factory: () => new Map(),\n});\n\n/**\n * Pre-computed reverse index: `fieldType → WrapperConfig[]` for every\n * registered `WrapperTypeDefinition.types` entry. Built once in the\n * `provideDynamicForm(...)` factory so `resolveWrappers` can look up\n * auto-associations in O(1) per field instead of scanning the full\n * wrapper registry on every render.\n */\nexport const WRAPPER_AUTO_ASSOCIATIONS = new InjectionToken<WrapperAutoAssociations>('WRAPPER_AUTO_ASSOCIATIONS', {\n providedIn: 'root',\n factory: () => new Map(),\n});\n","/**\n * Base error class for all Dynamic Forms errors.\n *\n * This class centralizes the `[Dynamic Forms]` prefix, ensuring consistent\n * error messaging across the library without requiring each error site to\n * manually include the prefix.\n */\nexport class DynamicFormError extends Error {\n private static readonly PREFIX = '[Dynamic Forms]';\n\n constructor(message: string) {\n super(`${DynamicFormError.PREFIX} ${message}`);\n this.name = 'DynamicFormError';\n }\n}\n","import { InjectionToken, Signal } from '@angular/core';\nimport type { FieldSignalContext, ArrayContext } from '../mappers/types';\nimport type { WrapperConfig } from './wrapper-type';\nimport type { ValidationMessages } from './validation-types';\nimport type { FormOptions } from './form-config';\nimport { DynamicFormError } from '../errors/dynamic-form-error';\n\n/**\n * Injection token for form-level default wrappers.\n *\n * Provides a Signal of the `defaultWrappers` array from FormConfig. Consumed by\n * `DfFieldOutlet` / `ContainerFieldComponent` to merge into each field's\n * effective wrapper chain (lowest priority after auto-associations, higher\n * than field-level `wrappers`).\n *\n * Provided once at the DynamicForm level and inherited via Angular's\n * hierarchical injector.\n */\nexport const DEFAULT_WRAPPERS = new InjectionToken<Signal<readonly WrapperConfig[] | undefined>>('DEFAULT_WRAPPERS');\n\n/**\n * Injection token for providing field signal context to mappers and components.\n *\n * The field signal context is the \"nervous system\" of the dynamic form library,\n * providing access to:\n * - The form instance and structure\n * - Current form values (as signals)\n * - Default values\n * - Validation messages\n * - The injector for creating components\n *\n * This token is provided by the DynamicForm component and can be scoped\n * for nested forms (Groups, Arrays) via child injectors.\n *\n * @example\n * ```typescript\n * // In a mapper function\n * export function mapValueField(fieldDef: BaseValueField<any, any>): Binding[] {\n * const context = inject(FIELD_SIGNAL_CONTEXT);\n * const form = context.form();\n * // ... use context\n * }\n *\n * // In a component\n * export class MyFieldComponent {\n * private context = inject(FIELD_SIGNAL_CONTEXT);\n * }\n * ```\n */\nexport const FIELD_SIGNAL_CONTEXT = new InjectionToken<FieldSignalContext>('FIELD_SIGNAL_CONTEXT', {\n providedIn: null, // Not provided at root - must be provided by DynamicForm\n factory: () => {\n throw new DynamicFormError(\n 'FIELD_SIGNAL_CONTEXT was not provided. ' +\n 'This token must be provided by DynamicFormComponent or a container field component. ' +\n 'If you are calling a mapper function directly, ensure it runs within runInInjectionContext() ' +\n 'with an injector that provides FIELD_SIGNAL_CONTEXT.',\n );\n },\n});\n\n/**\n * Injection token for providing array context metadata to mappers and components.\n *\n * This token is optionally provided by ArrayFieldComponent when creating injectors\n * for array items. It contains metadata about the array item's position and parent.\n *\n * Mappers can inject this token with {optional: true} to access array context:\n *\n * @example\n * ```typescript\n * // In a mapper function\n * export function buttonMapper(fieldDef: FieldDef<any>): Binding[] {\n * const arrayContext = inject(ARRAY_CONTEXT, { optional: true });\n * if (arrayContext) {\n * // Use arrayContext.index, arrayContext.arrayKey, etc.\n * }\n * }\n * ```\n */\nexport const ARRAY_CONTEXT = new InjectionToken<ArrayContext>('ARRAY_CONTEXT');\n\n/**\n * Injection token for form-level default props.\n *\n * Default props are form-wide property defaults that are merged with field-level props.\n * Field props take precedence over default props.\n *\n * Unlike FIELD_SIGNAL_CONTEXT which is re-provided by container components (Group, Array),\n * DEFAULT_PROPS is provided ONCE at the DynamicForm level and inherited by all children\n * via Angular's hierarchical injector.\n *\n * The token provides a Signal to enable reactivity - when config changes, mappers\n * that read the signal inside their computed() will automatically update.\n *\n * @example\n * ```typescript\n * // In a mapper function\n * const defaultPropsSignal = inject(DEFAULT_PROPS);\n *\n * return computed(() => {\n * const defaultProps = defaultPropsSignal?.(); // Read inside computed for reactivity\n * const baseInputs = buildBaseInputs(fieldDef, defaultProps);\n * // ...\n * });\n * ```\n */\nexport const DEFAULT_PROPS = new InjectionToken<Signal<Record<string, unknown> | undefined>>('DEFAULT_PROPS');\n\n/**\n * Injection token for form-level default validation messages.\n *\n * Default validation messages act as fallbacks when fields have validation\n * errors but no field-level `validationMessages` defined.\n *\n * Like DEFAULT_PROPS, this token is provided ONCE at the DynamicForm level\n * and inherited by all children via Angular's hierarchical injector.\n *\n * The token provides a Signal to enable reactivity - when config changes, mappers\n * that read the signal inside their computed() will automatically update.\n *\n * @example\n * ```typescript\n * // In a mapper or component\n * const defaultMessagesSignal = inject(DEFAULT_VALIDATION_MESSAGES);\n *\n * return computed(() => {\n * const defaultMessages = defaultMessagesSignal?.(); // Read inside computed for reactivity\n * const message = defaultMessages?.required ?? 'Field is required';\n * // ...\n * });\n * ```\n */\nexport const DEFAULT_VALIDATION_MESSAGES = new InjectionToken<Signal<ValidationMessages | undefined>>('DEFAULT_VALIDATION_MESSAGES');\n\n/**\n * Injection token for form-level options.\n *\n * Form options control form-wide behavior including button disabled states.\n * Used by button mappers to determine default disabled behavior.\n *\n * Like DEFAULT_PROPS, this token is provided ONCE at the DynamicForm level\n * and inherited by all children via Angular's hierarchical injector.\n *\n * The token provides a Signal to enable reactivity - when config changes, mappers\n * that read the signal inside their computed() will automatically update.\n *\n * @example\n * ```typescript\n * // In a button mapper\n * const formOptionsSignal = inject(FORM_OPTIONS);\n *\n * return computed(() => {\n * const formOptions = formOptionsSignal?.(); // Read inside computed for reactivity\n * const disableWhenInvalid = formOptions?.submitButton?.disableWhenInvalid ?? true;\n * // ...\n * });\n * ```\n */\nexport const FORM_OPTIONS = new InjectionToken<Signal<FormOptions | undefined>>('FORM_OPTIONS');\n\n/**\n * Injection token for form-level external data.\n *\n * Provides a Signal of the external data record from the form config.\n * Used by `FieldContextRegistryService` to resolve external data for expression evaluation\n * without coupling to `FormStateManager` directly.\n *\n * Like DEFAULT_PROPS, this token is provided ONCE at the DynamicForm level\n * and inherited by all children via Angular's hierarchical injector.\n */\nexport const EXTERNAL_DATA = new InjectionToken<Signal<Record<string, Signal<unknown>> | undefined>>('EXTERNAL_DATA');\n\n/**\n * Injection token for array-level template registry.\n *\n * This registry tracks which template was used to create each array item,\n * keyed by the item's unique ID. This is essential for \"recreate\" operations\n * (e.g., after removing items from the middle) where we need to re-resolve\n * items using their original templates, not a fallback.\n *\n * The token is provided by ArrayFieldComponent at its level and shared\n * across all items in that array. Each nested array gets its own registry.\n *\n * @example\n * ```typescript\n * // In ArrayFieldComponent\n * providers: [\n * { provide: ARRAY_TEMPLATE_REGISTRY, useValue: new Map() }\n * ]\n *\n * // When adding items\n * const registry = inject(ARRAY_TEMPLATE_REGISTRY);\n * registry.set(itemId, templates);\n *\n * // During recreate, look up original template\n * const originalTemplate = registry.get(existingItemId);\n * ```\n */\nexport const ARRAY_TEMPLATE_REGISTRY = new InjectionToken<ArrayTemplateRegistry>('ARRAY_TEMPLATE_REGISTRY');\n\n/**\n * Registry type for storing templates used to create array items.\n * Key is the item's unique ID, value is the template (array of field definitions).\n */\nexport type ArrayTemplateRegistry = Map<string, import('../definitions/base/field-def').FieldDef<unknown>[]>;\n\n/**\n * Injection token for array-level item ID generator.\n *\n * Provides a function that generates unique IDs for array items. Each array\n * component instance gets its own generator (via useFactory), ensuring:\n * - SSR hydration compatibility (server and client generate same IDs for same array)\n * - No global state pollution between form instances\n * - Deterministic IDs within each array's lifecycle\n *\n * The token is provided by ArrayFieldComponent at its level with a factory\n * that creates a fresh counter for each array instance.\n *\n * @example\n * ```typescript\n * // In ArrayFieldComponent\n * providers: [\n * { provide: ARRAY_ITEM_ID_GENERATOR, useFactory: createArrayItemIdGenerator }\n * ]\n *\n * // Usage\n * const generateId = inject(ARRAY_ITEM_ID_GENERATOR);\n * const itemId = generateId(); // 'item-0', 'item-1', etc.\n * ```\n */\nexport const ARRAY_ITEM_ID_GENERATOR = new InjectionToken<() => string>('ARRAY_ITEM_ID_GENERATOR');\n\n/**\n * Factory function that creates a new array item ID generator.\n * Each invocation creates an independent counter starting at 0.\n */\nexport function createArrayItemIdGenerator(): () => string {\n let counter = 0;\n return () => `item-${counter++}`;\n}\n","import {\n ComponentRef,\n EnvironmentInjector,\n InjectOptions,\n Injector,\n ProviderToken,\n reflectComponentType,\n Type,\n ViewContainerRef,\n} from '@angular/core';\nimport { catchError, forkJoin, from, map, Observable, of } from 'rxjs';\nimport { FieldWrapperContract, WrapperConfig, WrapperTypeDefinition } from '../../models/wrapper-type';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport { WrapperFieldInputs } from '../../wrappers/wrapper-field-inputs';\n\n/**\n * Module-level cache keyed by component class. `reflectComponentType` returns\n * immutable metadata per class, so we probe it once and reuse the resulting\n * `Set<templateName>` for every `setInputIfDeclared` call afterwards.\n *\n * We cache `templateName` (the public input name, aka alias) rather than\n * `propName` (the class field name) because `ComponentRef.setInput()` keys by\n * the public name — that's also the name wrapper configs use. An aliased\n * input declared as `input(..., { alias: 'header' })` with class field\n * `headerText` must be addressed as `'header'`; caching `propName` would\n * leave the alias out of the declared set and silently drop config values.\n *\n * SSR-safe: the WeakMap is keyed by the component class object — classes are\n * created per Angular application bootstrap and GC'd with it, so this does not\n * leak state between server renders.\n */\nconst inputNamesCache = new WeakMap<Type<unknown>, Set<string>>();\n\nfunction getDeclaredInputs(componentType: Type<unknown>): Set<string> {\n let inputs = inputNamesCache.get(componentType);\n if (!inputs) {\n const meta = reflectComponentType(componentType);\n inputs = new Set(meta?.inputs.map((i) => i.templateName) ?? []);\n inputNamesCache.set(componentType, inputs);\n }\n return inputs;\n}\n\n/**\n * Set an input on a ComponentRef only when the target component actually declares it.\n *\n * Angular's `ComponentRef.setInput()` throws NG0303 when the input is missing.\n * For config keys driven by user data (e.g. a wrapper config containing a prop\n * the wrapper doesn't care about) that would surface as a noisy runtime error.\n * We probe the component's metadata via `reflectComponentType` (public API),\n * cached per component class — called once per input key per emission, so\n * avoiding the reflection scan on each call is meaningful under heavy typing.\n */\nexport function setInputIfDeclared(ref: ComponentRef<unknown>, inputName: string, value: unknown): void {\n const declared = getDeclaredInputs(ref.componentType);\n if (declared.has(inputName)) {\n ref.setInput(inputName, value);\n }\n}\n\n/**\n * A wrapper whose component has been resolved and loaded.\n */\nexport interface LoadedWrapper {\n readonly config: WrapperConfig;\n readonly component: Type<unknown>;\n}\n\n/**\n * Narrows an ES-module-with-default-export from a bare component class.\n * Lazy component loaders may return either shape depending on how the user\n * wrote the import expression (`import('./x')` vs `import('./x').then(m => m.Foo)`).\n */\nexport function hasDefaultExport<T>(value: unknown): value is { default: T } {\n return typeof value === 'object' && value !== null && 'default' in value && !!(value as { default: unknown }).default;\n}\n\n/**\n * Pick the component class out of whatever a lazy loader returned.\n */\nexport function resolveDefaultExport<T>(result: Type<T> | { default: Type<T> }): Type<T> {\n return hasDefaultExport<Type<T>>(result) ? result.default : result;\n}\n\n/**\n * Resolve a wrapper type name to its component class, with DI-scoped caching.\n */\nexport async function loadWrapperComponent(\n type: string,\n registry: ReadonlyMap<string, WrapperTypeDefinition>,\n cache: Map<string, Type<unknown>>,\n): Promise<Type<unknown> | undefined> {\n const cached = cache.get(type);\n if (cached) return cached;\n\n const definition = registry.get(type);\n if (!definition) return undefined;\n\n const component = resolveDefaultExport(await definition.loadComponent());\n if (component) cache.set(type, component);\n return component;\n}\n\n/**\n * Load every wrapper for a chain, all-or-nothing. A single failed load\n * aborts the whole chain (emits `[]`) so the field renders bare rather\n * than in a partially-wrapped, visually-misleading state. Each failure\n * is logged; field-type resolution still throws — this isn't silent.\n */\nexport function loadWrapperComponents(\n configs: readonly WrapperConfig[],\n registry: ReadonlyMap<string, WrapperTypeDefinition>,\n cache: Map<string, Type<unknown>>,\n logger: Logger,\n): Observable<LoadedWrapper[]> {\n if (configs.length === 0) return of([]);\n\n return forkJoin(\n configs.map((config) =>\n from(loadWrapperComponent(config.type, registry, cache)).pipe(\n catchError(() => of(undefined)),\n map((component) => {\n if (!component) {\n logger.error(`Wrapper type '${config.type}' could not be loaded. Ensure it is registered via provideDynamicForm().`);\n return null;\n }\n return { config, component } satisfies LoadedWrapper;\n }),\n ),\n ),\n ).pipe(map((results) => (results.some((r) => r === null) ? [] : (results as LoadedWrapper[]))));\n}\n\n/**\n * Options for building a wrapper chain.\n */\nexport interface RenderWrapperChainOptions {\n readonly outerContainer: ViewContainerRef;\n readonly loadedWrappers: readonly LoadedWrapper[];\n readonly environmentInjector: EnvironmentInjector;\n readonly logger: Logger;\n /**\n * Optional mapper outputs to set as `fieldInputs` on each wrapper in the chain.\n * Container usages omit this (the children template is the innermost content,\n * not a single field).\n */\n readonly fieldInputs?: WrapperFieldInputs;\n /**\n * Optional field-level injector (e.g. `ResolvedField.injector`). When provided,\n * each wrapper is created with a merged injector that checks the field's\n * tokens first (`FIELD_SIGNAL_CONTEXT`, `ARRAY_CONTEXT`, …) and falls back to\n * the element injector — so wrappers can inject both field context AND outer\n * wrappers up the element hierarchy.\n */\n readonly fieldInjector?: Injector;\n /** Renders whatever belongs at the innermost slot (a field component, a children template, …). */\n readonly renderInnermost: (slot: ViewContainerRef) => void;\n}\n\n/**\n * Recursively create each wrapper component, threading the next one (or the\n * innermost content) into its `#fieldComponent` slot.\n *\n * Each wrapper receives:\n * - Each of its config properties (minus `type`) as an individual Angular input\n * - `fieldInputs` as a single input, if provided\n *\n * Returns the list of wrapper `ComponentRef`s — callers retain them for later\n * cleanup and for re-setting `fieldInputs` when the mapper signal emits.\n */\nexport function renderWrapperChain(options: RenderWrapperChainOptions): ComponentRef<unknown>[] {\n const refs: ComponentRef<unknown>[] = [];\n renderStep(options.outerContainer, options.loadedWrappers, options, refs);\n return refs;\n}\n\nfunction renderStep(\n slot: ViewContainerRef,\n remaining: readonly LoadedWrapper[],\n options: RenderWrapperChainOptions,\n refs: ComponentRef<unknown>[],\n): void {\n if (remaining.length === 0) {\n options.renderInnermost(slot);\n return;\n }\n\n const [wrapper, ...rest] = remaining;\n\n // `slot.injector` is the element injector seen from inside the current slot —\n // for nested slots that includes the outer wrapper's component, enabling\n // `inject(OuterWrapper)`. When a field injector is provided we merge it in\n // front so tokens like `ARRAY_CONTEXT` also resolve.\n const wrapperInjector = options.fieldInjector ? createWrapperAwareInjector(options.fieldInjector, slot.injector) : slot.injector;\n\n const ref = slot.createComponent(wrapper.component, {\n environmentInjector: options.environmentInjector,\n injector: wrapperInjector,\n });\n refs.push(ref);\n\n for (const [key, value] of Object.entries(wrapper.config)) {\n // `type` is the registry discriminant; `fieldInputs` is set explicitly\n // below. Don't let a stray config key override either.\n if (key === 'type' || key === 'fieldInputs') continue;\n setInputIfDeclared(ref, key, value);\n }\n\n if (options.fieldInputs !== undefined) {\n setInputIfDeclared(ref, 'fieldInputs', options.fieldInputs);\n }\n\n // Required to resolve `viewChild.required('fieldComponent')` before we\n // recurse into the slot. O(chain length) CD passes per rebuild — acceptable\n // for typical chains (≤3); refactor to a template-based render if it bites.\n ref.changeDetectorRef.detectChanges();\n\n const inner = resolveInnerSlot(ref);\n if (!inner) {\n options.logger.error(\n `Wrapper component for type '${wrapper.config.type}' does not provide a 'fieldComponent' ViewContainerRef. ` +\n `Ensure the wrapper component has a viewChild('fieldComponent', { read: ViewContainerRef }) query ` +\n `and that #fieldComponent is not inside a conditional (@if, @defer).`,\n );\n // Unwind: destroy every wrapper built so far, including this one, so the\n // caller doesn't end up with a partial chain left in the DOM.\n while (refs.length) refs.pop()!.destroy();\n return;\n }\n\n renderStep(inner, rest, options, refs);\n}\n\n/**\n * Read a wrapper's `#fieldComponent` ViewContainerRef. `viewChild.required`\n * throws when the query can't resolve (missing template ref, or ref sitting\n * inside `@if` / `@defer` / `@for`); any throw from this pure signal read\n * means the slot is unusable, so we return undefined and let the caller log\n * the actionable \"wrapper missing fieldComponent\" message.\n */\nfunction resolveInnerSlot(ref: ComponentRef<unknown>): ViewContainerRef | undefined {\n const contract = ref.instance as FieldWrapperContract;\n try {\n return contract.fieldComponent?.();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Merged injector: check the field-level injector first (for tokens like\n * `ARRAY_CONTEXT` / `FIELD_SIGNAL_CONTEXT`), fall back to the element-chain\n * injector (so nested wrappers can still `inject(OuterWrapper)`).\n *\n * Precedence: a field-level token shadows a same-named token provided by an\n * outer wrapper. That matches \"more specific context wins\" but is worth\n * keeping in mind if a wrapper exports service tokens.\n */\nexport function createWrapperAwareInjector(fieldInjector: Injector, elementInjector: Injector): Injector {\n if (fieldInjector === elementInjector) return fieldInjector;\n return new WrapperAwareInjector(fieldInjector, elementInjector);\n}\n\n/** Sentinel — distinguishes \"token not found\" from a legitimate `undefined` provider value. */\nconst WRAPPER_NOT_FOUND = {};\n\nclass WrapperAwareInjector extends Injector {\n constructor(\n private readonly fieldInjector: Injector,\n private readonly elementInjector: Injector,\n ) {\n super();\n }\n\n override get<T>(token: ProviderToken<T>, notFoundValue?: T, options?: InjectOptions): T;\n override get(token: unknown, notFoundValue?: unknown, options?: InjectOptions): unknown {\n const field = this.fieldInjector.get(token as ProviderToken<unknown>, WRAPPER_NOT_FOUND, options);\n if (field !== WRAPPER_NOT_FOUND) return field;\n return this.elementInjector.get(token as ProviderToken<unknown>, notFoundValue, options);\n }\n}\n","import { InjectionToken } from '@angular/core';\nimport type { Logger } from './logger.interface';\n\n/**\n * Injection token for the dynamic forms logger.\n *\n * Provided by provideDynamicForm() with ConsoleLogger as default.\n * Override with withLoggerConfig(false) to disable logging.\n */\nexport const DynamicFormLogger = new InjectionToken<Logger>('DynamicFormLogger');\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { WrapperAutoAssociations, WrapperConfig } from '../../models/wrapper-type';\n\n/**\n * Shared empty chain — returned when no wrappers apply so callers get a\n * stable reference. Freezing makes accidental mutation observable.\n */\nconst EMPTY_WRAPPERS: readonly WrapperConfig[] = Object.freeze([]);\n\n/**\n * Element-wise identity (`===`) comparator for wrapper chains. Used as the\n * `equal` option on signal memoisation so reconciled `FieldDef`s with the\n * same chain don't churn downstream — relies on `WrapperConfig` objects\n * being stable across ticks, which holds for configs declared in\n * `FormConfig` / `createWrappers(...)`.\n */\nexport function isSameWrapperChain(a: readonly WrapperConfig[], b: readonly WrapperConfig[]): boolean {\n if (a === b) return true;\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Resolves the wrapper chain for a field.\n *\n * Merge order (outermost → innermost): auto-associations, form defaults,\n * field-level wrappers. `wrappers: null` skips all three; `skipAutoWrappers` /\n * `skipDefaultWrappers` on the field opt out of individual layers. Fresh\n * array per call — downstream memoisation is on the consuming computed.\n */\nexport function resolveWrappers(\n field: Pick<FieldDef<unknown>, 'type' | 'wrappers' | 'skipAutoWrappers' | 'skipDefaultWrappers'>,\n defaultWrappers: readonly WrapperConfig[] | undefined,\n autoAssociations: WrapperAutoAssociations,\n): readonly WrapperConfig[] {\n if (field.wrappers === null) {\n return EMPTY_WRAPPERS;\n }\n\n const autoWrappers = field.skipAutoWrappers ? EMPTY_WRAPPERS : (autoAssociations.get(field.type) ?? EMPTY_WRAPPERS);\n const defaults = field.skipDefaultWrappers ? EMPTY_WRAPPERS : (defaultWrappers ?? EMPTY_WRAPPERS);\n const fieldLevel = field.wrappers ?? EMPTY_WRAPPERS;\n\n if (autoWrappers.length === 0 && defaults.length === 0 && fieldLevel.length === 0) {\n return EMPTY_WRAPPERS;\n }\n\n return [...autoWrappers, ...defaults, ...fieldLevel];\n}\n","import { ComponentRef, computed, DestroyRef, EnvironmentInjector, inject, Injector, Signal, ViewContainerRef } from '@angular/core';\nimport { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { map, Observable, of, switchMap } from 'rxjs';\nimport { WRAPPER_COMPONENT_CACHE, WRAPPER_REGISTRY, WrapperConfig, WrapperTypeDefinition } from '../../models/wrapper-type';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { WrapperFieldInputs } from '../../wrappers/wrapper-field-inputs';\nimport { isSameWrapperChain } from '../resolve-wrappers/resolve-wrappers';\nimport { LoadedWrapper, loadWrapperComponents, renderWrapperChain, setInputIfDeclared } from './wrapper-chain';\n\nexport interface WrapperChainControllerOptions {\n /**\n * The outer slot where the wrapper chain is mounted. Sampled only at render\n * time — safe to pass a `viewChild.required` signal that resolves post-init.\n */\n readonly vcr: Signal<ViewContainerRef>;\n /**\n * Signal of the wrapper chain. Ref-stable memoisation (e.g.\n * `isSameWrapperChain`) is recommended — `WrapperConfig` entries should be\n * singletons so the controller can tell a real chain change from ref churn.\n */\n readonly wrappers: Signal<readonly WrapperConfig[]>;\n /**\n * Optional gating signal. When `false`, the chain is not mounted (initial)\n * or left untouched (post-mount flicker). `DfFieldOutlet` passes\n * `renderReady`; containers omit the gate.\n */\n readonly gate?: Signal<boolean>;\n /**\n * Optional mapper-outputs signal. When present, the controller pushes it to\n * each wrapper's `fieldInputs` input at render time AND on every subsequent\n * change. Must always produce a value once subscribed — don't emit undefined.\n * Containers render a children template (no field), so they omit this.\n */\n readonly fieldInputs?: Signal<WrapperFieldInputs>;\n /**\n * Optional extra rebuild trigger. `DfFieldOutlet` passes the innermost\n * component class so that a reconciled field with the same wrapper chain\n * but a different `component` forces a rebuild. Compared by identity.\n */\n readonly rebuildKey?: Signal<unknown>;\n /**\n * Optional field-level injector signal (e.g. `ResolvedField.injector`). When\n * provided, wrapper components see a merged injector — field tokens first\n * (`ARRAY_CONTEXT`, `FIELD_SIGNAL_CONTEXT`), element chain behind\n * (parent wrappers). Containers omit this.\n */\n readonly fieldInjector?: Signal<Injector>;\n /**\n * Renders whatever belongs at the innermost slot (a field component, a children\n * template, …). Called each time the chain mounts or structurally rebuilds.\n */\n readonly renderInnermost: (slot: ViewContainerRef) => void;\n /**\n * Called right before the mounted chain is cleared on a structural change.\n * Lets the caller detach views it wants to preserve — e.g. `DfFieldOutlet`\n * detaches the innermost field's hostView so focus / caret / scroll survive\n * when only the wrapper chain changes. Not invoked on the pre-first-render path.\n */\n readonly beforeRebuild?: () => void;\n}\n\n/**\n * Owns the wrapper-chain lifecycle for a field or container: async component\n * loading, switchMap-based cancellation of stale loads, flicker-tolerant\n * rebuilds (only structural changes tear down), and `fieldInputs` push-through.\n * Must be called from a DI injection context.\n */\nexport function createWrapperChainController(opts: WrapperChainControllerOptions): void {\n const deps = injectChainDeps();\n const state = createStateSignal(opts);\n\n const mounted = { value: null as MountedChain | null };\n let refs: ComponentRef<unknown>[] = [];\n\n buildEmissionStream(state, deps)\n .pipe(takeUntilDestroyed(deps.destroyRef))\n .subscribe((emission) => {\n // Wrap the whole render path — a throw here (bad wrapper template,\n // caller's renderInnermost blew up, etc.) would otherwise terminate\n // the subscription and silently freeze subsequent chain updates.\n try {\n refs = applyEmission(emission, { opts, deps, mounted, refs });\n } catch (err) {\n deps.logger.error('Wrapper chain render failed; tearing down partial state.', err);\n opts.vcr().clear();\n refs = [];\n mounted.value = null;\n }\n });\n\n pushFieldInputsOnChange(opts, () => refs);\n deps.destroyRef.onDestroy(() => opts.vcr().clear());\n}\n\ninterface ChainDeps {\n readonly registry: ReadonlyMap<string, WrapperTypeDefinition>;\n readonly cache: Map<string, import('@angular/core').Type<unknown>>;\n readonly logger: Logger;\n readonly destroyRef: DestroyRef;\n readonly environmentInjector: EnvironmentInjector;\n}\n\ninterface ChainState {\n readonly open: boolean;\n readonly wrappers: readonly WrapperConfig[];\n readonly rebuildKey: unknown;\n}\n\ninterface MountedChain {\n readonly wrappers: readonly WrapperConfig[];\n readonly rebuildKey: unknown;\n}\n\ninterface ChainEmission {\n readonly state: ChainState;\n readonly loaded: readonly LoadedWrapper[] | null;\n}\n\ninterface EmissionApplyContext {\n readonly opts: WrapperChainControllerOptions;\n readonly deps: ChainDeps;\n readonly mounted: { value: MountedChain | null };\n readonly refs: ComponentRef<unknown>[];\n}\n\nfunction injectChainDeps(): ChainDeps {\n return {\n registry: inject(WRAPPER_REGISTRY),\n cache: inject(WRAPPER_COMPONENT_CACHE),\n logger: inject(DynamicFormLogger),\n destroyRef: inject(DestroyRef),\n environmentInjector: inject(EnvironmentInjector),\n };\n}\n\nfunction createStateSignal(opts: WrapperChainControllerOptions): Signal<ChainState> {\n return computed(\n () => ({\n open: opts.gate?.() ?? true,\n wrappers: opts.wrappers(),\n rebuildKey: opts.rebuildKey?.(),\n }),\n { equal: (a, b) => a.open === b.open && a.rebuildKey === b.rebuildKey && isSameWrapperChain(a.wrappers, b.wrappers) },\n );\n}\n\n/**\n * Resolve a `ChainState` into a `ChainEmission`. `switchMap` cancellation\n * guarantees in-flight async loads are discarded when a newer state arrives.\n */\nfunction buildEmissionStream(state: Signal<ChainState>, deps: ChainDeps): Observable<ChainEmission> {\n return toObservable(state).pipe(switchMap((s) => resolveLoadedWrappers(s, deps)));\n}\n\nfunction resolveLoadedWrappers(state: ChainState, deps: ChainDeps): Observable<ChainEmission> {\n if (!state.open) {\n return of({ state, loaded: null });\n }\n\n if (state.wrappers.every((w) => deps.cache.has(w.type))) {\n // Sync fast-path — the cache only holds SUCCESSFUL loads, so \"every cached\"\n // means every wrapper was previously resolved cleanly. No need to re-log.\n const loaded = state.wrappers.map((config) => ({ config, component: deps.cache.get(config.type)! }) satisfies LoadedWrapper);\n return of({ state, loaded });\n }\n\n return loadWrapperComponents(state.wrappers, deps.registry, deps.cache, deps.logger).pipe(map((loaded) => ({ state, loaded })));\n}\n\n/**\n * Diff what's mounted against the next state and act:\n * - Gate-only flicker → no-op (preserve the mounted chain)\n * - Structural change → beforeRebuild → vcr.clear → render fresh\n * - Idempotent re-emission → no-op\n *\n * Returns the (possibly new) wrapper refs so the caller can track them for\n * `fieldInputs` push-through.\n */\nfunction applyEmission({ state, loaded }: ChainEmission, ctx: EmissionApplyContext): ComponentRef<unknown>[] {\n const { opts, deps, mounted, refs } = ctx;\n const vcr = opts.vcr();\n const structurallyChanged = isStructurallyDifferent(mounted.value, state);\n\n // Gate-only flicker after first mount — keep the chain alive so the user's\n // focus / caret / scroll survive. The caller's rawInputs effect continues\n // to push live mapper outputs through the still-mounted innermost.\n if (!structurallyChanged && !state.open) return refs;\n\n // Real structural change — tear down. Angular cascades destroy through\n // every nested ComponentRef, so walking `refs` manually is redundant.\n // `beforeRebuild` gives the caller a chance to detach views it wants to\n // preserve (e.g. the innermost field when only wrappers changed).\n if (structurallyChanged && mounted.value !== null) {\n opts.beforeRebuild?.();\n vcr.clear();\n mounted.value = null;\n }\n\n if (!state.open || loaded === null) return [];\n // Same structure + already mounted — idempotent re-emission, nothing to do.\n if (mounted.value !== null) return refs;\n\n const newRefs = renderWrapperChain({\n outerContainer: vcr,\n loadedWrappers: loaded,\n environmentInjector: deps.environmentInjector,\n logger: deps.logger,\n fieldInputs: opts.fieldInputs?.(),\n fieldInjector: opts.fieldInjector?.(),\n renderInnermost: opts.renderInnermost,\n });\n mounted.value = { wrappers: state.wrappers, rebuildKey: state.rebuildKey };\n return newRefs;\n}\n\nfunction isStructurallyDifferent(mounted: MountedChain | null, next: ChainState): boolean {\n if (mounted === null) return true;\n if (mounted.rebuildKey !== next.rebuildKey) return true;\n return !isSameWrapperChain(mounted.wrappers, next.wrappers);\n}\n\n/**\n * Push the latest `fieldInputs` bag to every mounted wrapper whenever it\n * changes — without rebuilding the chain. No-op when the chain is empty\n * (gated off, or nothing rendered yet).\n */\nfunction pushFieldInputsOnChange(opts: WrapperChainControllerOptions, getRefs: () => readonly ComponentRef<unknown>[]): void {\n if (!opts.fieldInputs) return;\n explicitEffect([opts.fieldInputs], ([fi]) => {\n for (const ref of getRefs()) setInputIfDeclared(ref, 'fieldInputs', fi);\n });\n}\n","import { InjectionToken, Signal } from '@angular/core';\nimport { FieldTree } from '@angular/forms/signals';\n\n/**\n * Represents a FieldTree node for dynamic bracket-access navigation.\n *\n * TypeScript's `Subfields<T>` type on `FieldTree` only allows statically-known keys,\n * but at runtime the form tree supports arbitrary string key access (e.g., `rootForm['address']`).\n * This type makes that dynamic access explicit: each string key maps to a `FieldTree | undefined`.\n */\nexport type FieldTreeRecord = Record<string, FieldTree<unknown> | undefined>;\n\n/**\n * Type representing a FieldTree for an array.\n * Extends FieldTree to add numeric indexing for accessing item FieldTrees.\n */\nexport type ArrayFieldTree<T> = FieldTree<T[]> & {\n readonly [index: number]: FieldTree<T> | undefined;\n};\n\n/**\n * Get the length of an array FieldTree.\n */\nexport function getArrayLength<T>(arrayFieldTree: ArrayFieldTree<T>): number {\n const value = arrayFieldTree().value();\n return Array.isArray(value) ? value.length : 0;\n}\n\n/**\n * Read-only view of a single field's observable state.\n *\n * Whitelisted read signals copied from Angular Signal Forms' `FieldState` so wrappers\n * can observe a field without being able to mutate it. New write-capable members\n * added in future Angular versions are excluded by default (the `Pick` list stays\n * the source of truth).\n *\n * `value` is narrowed from `WritableSignal<TValue>` to `Signal<TValue>` so consumers\n * cannot write through it.\n */\nexport interface ReadonlyFieldTree<TValue = unknown> {\n readonly value: Signal<TValue>;\n readonly valid: Signal<boolean>;\n readonly invalid: Signal<boolean>;\n readonly touched: Signal<boolean>;\n readonly dirty: Signal<boolean>;\n readonly required: Signal<boolean>;\n readonly disabled: Signal<boolean>;\n readonly hidden: Signal<boolean>;\n readonly errors: Signal<readonly unknown[]>;\n}\n\n/**\n * Build a `ReadonlyFieldTree` by extracting the whitelisted read signals from a\n * Signal Forms `FieldTree`. Returns a fresh plain object — no casting, no proxying,\n * so consumers only see the narrow surface and Angular's `WritableSignal` capability\n * on `value` is hidden.\n */\nexport function toReadonlyFieldTree<TValue>(field: FieldTree<TValue>): ReadonlyFieldTree<TValue> {\n const state = field();\n return {\n value: state.value,\n valid: state.valid,\n invalid: state.invalid,\n touched: state.touched,\n dirty: state.dirty,\n required: state.required,\n disabled: state.disabled,\n hidden: state.hidden,\n errors: state.errors,\n };\n}\n\n/**\n * DI-scoped cache for `ReadonlyFieldTree` views, keyed on the source FieldTree\n * identity. A fresh WeakMap per root injector keeps renders isolated under SSR —\n * Angular creates a new root injector per request, so there's no shared state\n * between server renders (same pattern as `COMPONENT_CACHE`).\n *\n * @internal\n */\nexport const READONLY_FIELD_TREE_CACHE = new InjectionToken<WeakMap<FieldTree<unknown>, ReadonlyFieldTree<unknown>>>(\n 'READONLY_FIELD_TREE_CACHE',\n {\n providedIn: 'root',\n factory: () => new WeakMap(),\n },\n);\n\n/**\n * Cached variant of {@link toReadonlyFieldTree}. Each FieldTree instance is a\n * stable reference for the lifetime of its form, so one `ReadonlyFieldTree`\n * view per tree is enough. Callers on hot paths (`pushInputs` on every mapper\n * emission) avoid re-allocating the nine-property view object.\n *\n * @internal\n */\nexport function toReadonlyFieldTreeCached<TValue>(\n cache: WeakMap<FieldTree<unknown>, ReadonlyFieldTree<unknown>>,\n field: FieldTree<TValue>,\n): ReadonlyFieldTree<TValue> {\n const key = field as FieldTree<unknown>;\n const cached = cache.get(key);\n if (cached) return cached as ReadonlyFieldTree<TValue>;\n\n const view = toReadonlyFieldTree(field);\n cache.set(key, view as ReadonlyFieldTree<unknown>);\n return view;\n}\n","import {\n ComponentRef,\n computed,\n DestroyRef,\n Directive,\n EnvironmentInjector,\n inject,\n input,\n Signal,\n signal,\n Type,\n ViewContainerRef,\n} from '@angular/core';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { ResolvedField } from '../utils/resolve-field/resolve-field';\nimport { WRAPPER_AUTO_ASSOCIATIONS } from '../models/wrapper-type';\nimport { DEFAULT_WRAPPERS } from '../models/field-signal-context.token';\nimport { createWrapperAwareInjector, setInputIfDeclared } from '../utils/wrapper-chain/wrapper-chain';\nimport { createWrapperChainController } from '../utils/wrapper-chain/wrapper-chain-controller';\nimport { isSameWrapperChain, resolveWrappers } from '../utils/resolve-wrappers/resolve-wrappers';\nimport { READONLY_FIELD_TREE_CACHE, toReadonlyFieldTreeCached } from '../core/field-tree-utils';\nimport { WrapperFieldInputs } from '../wrappers/wrapper-field-inputs';\n\n/**\n * Structural directive that renders a `ResolvedField` with its effective\n * wrapper chain.\n *\n * Replaces `*ngComponentOutlet` in field-rendering templates. When the field\n * has no wrappers, the component is created directly at the outlet position\n * (no extra DOM nesting). When wrappers apply, they chain outermost-first and\n * the field renders in the innermost slot.\n *\n * Effective wrappers are merged from (outermost → innermost):\n * 1. `WrapperTypeDefinition.types` auto-associations for the field's `type`\n * 2. `FormConfig.defaultWrappers`\n * 3. Field-level `FieldDef.wrappers` (`null` = explicit opt-out; `[]` does not\n * opt out — auto + defaults still apply)\n *\n * Wrapper config keys (minus `type`) are pushed as individual Angular inputs;\n * every wrapper also receives `fieldInputs` — a `WrapperFieldInputs` bag that\n * includes the field's mapper outputs and a `ReadonlyFieldTree` view of its\n * form state.\n *\n * Rendering is gated by `field.renderReady()` — the directive waits until\n * the mapper produces the required inputs before instantiating the component.\n * Once rendered, a transient `renderReady → false` does *not* tear the chain\n * down; the controller keeps the mounted components alive and ignores the\n * flicker. Only a structural change (wrappers or component class) triggers\n * a rebuild.\n *\n * @example\n * ```html\n * \\@for (field of resolvedFields(); track field.key) {\n * <ng-container *dfFieldOutlet=\"field; environmentInjector: envInjector\" />\n * }\n * ```\n */\n@Directive({\n selector: '[dfFieldOutlet]',\n})\nexport class DfFieldOutlet {\n // Named to match the structural directive microsyntax directly\n // (`*dfFieldOutlet=\"field; environmentInjector: env\"`) so no aliasing is needed.\n readonly dfFieldOutlet = input.required<ResolvedField>();\n readonly dfFieldOutletEnvironmentInjector = input<EnvironmentInjector | undefined>(undefined);\n\n private readonly vcrRef = inject(ViewContainerRef);\n private readonly vcr: Signal<ViewContainerRef> = signal(this.vcrRef).asReadonly();\n private readonly destroyRef = inject(DestroyRef);\n private readonly wrapperAutoAssociations = inject(WRAPPER_AUTO_ASSOCIATIONS);\n private readonly defaultWrappersSignal = inject(DEFAULT_WRAPPERS, { optional: true });\n private readonly readonlyFieldCache = inject(READONLY_FIELD_TREE_CACHE);\n\n private fieldRef: ComponentRef<unknown> | undefined;\n /**\n * VCR the `fieldRef`'s host view is currently inserted into (either the outer\n * VCR when there are no wrappers, or the innermost wrapper's `#fieldComponent`\n * slot). Tracked so `beforeRebuild` can detach the view before the outer VCR\n * cascade-destroys it.\n */\n private fieldSlot: ViewContainerRef | undefined;\n /** Focus + caret captured during detach, replayed after re-insert. */\n private focusSnapshot: { element: HTMLElement; selectionStart: number | null; selectionEnd: number | null } | undefined;\n /**\n * Last rawInputs reference pushed to the innermost field. Used to dedupe the\n * rawInputs effect when the same snapshot was already applied as part of the\n * initial render — keeps per-keystroke input updates O(changed-keys) instead\n * of re-walking the whole input bag.\n */\n private lastPushedInputs: Record<string, unknown> | undefined;\n\n private readonly componentIdentity: Signal<Type<unknown>> = computed(() => this.dfFieldOutlet().component);\n private readonly renderReady: Signal<boolean> = computed(() => this.dfFieldOutlet().renderReady());\n private readonly rawInputs = computed(() => this.dfFieldOutlet().inputs());\n\n /**\n * Effective wrapper chain. Element-wise identity comparison keeps the signal\n * stable across `ResolvedField` reference changes that don't actually change\n * the chain — avoids rebuilds on reconciled fields.\n */\n private readonly wrappers = computed(\n () => resolveWrappers(this.dfFieldOutlet().fieldDef, this.defaultWrappersSignal?.(), this.wrapperAutoAssociations),\n { equal: isSameWrapperChain },\n );\n\n /**\n * `fieldInputs` bag handed to every wrapper in the chain. Memoised on\n * `rawInputs` identity so repeated emissions with the same underlying object\n * return the same view and don't cascade OnPush re-evaluations.\n */\n private readonly fieldInputs = computed<WrapperFieldInputs>(() => this.buildFieldInputs(this.rawInputs()));\n\n private readonly defaultEnvInjector = inject(EnvironmentInjector);\n /** Environment injector for the innermost field component — `[environmentInjector]` input takes precedence over the directive's own DI. */\n private readonly fieldEnvInjector = computed(() => this.dfFieldOutletEnvironmentInjector() ?? this.defaultEnvInjector);\n /** Field-level injector (FIELD_SIGNAL_CONTEXT, ARRAY_CONTEXT, …). Threaded to the controller so wrappers can inject it too. */\n private readonly fieldInjector = computed(() => this.dfFieldOutlet().injector);\n\n constructor() {\n createWrapperChainController({\n vcr: this.vcr,\n wrappers: this.wrappers,\n gate: this.renderReady,\n rebuildKey: this.componentIdentity,\n fieldInputs: this.fieldInputs,\n fieldInjector: this.fieldInjector,\n beforeRebuild: () => this.detachFieldRef(),\n renderInnermost: (slot) => {\n const resolved = this.dfFieldOutlet();\n if (this.fieldRef && this.fieldRef.componentType === resolved.component) {\n // Same component class — re-insert the preserved hostView. Browser\n // loses focus on detach, so we replay the snapshot captured in\n // detachFieldRef. Input value persists on the DOM node itself.\n slot.insert(this.fieldRef.hostView);\n this.fieldSlot = slot;\n this.pushRawInputs(this.fieldRef, this.rawInputs());\n this.restoreFocusSnapshot();\n return;\n }\n // Different component class — discard the old ref and create fresh.\n // Merge field + element injectors so the field can inject ancestor\n // wrappers AND form-context tokens (ARRAY_CONTEXT etc.).\n // Clear state before createComponent — if it throws (bad provider,\n // invalid class) we don't want to leak a reference to a destroyed ref\n // that the same-component branch would later try to re-insert.\n this.focusSnapshot = undefined;\n this.lastPushedInputs = undefined;\n const previousRef = this.fieldRef;\n this.fieldRef = undefined;\n this.fieldSlot = undefined;\n previousRef?.destroy();\n this.fieldRef = slot.createComponent(resolved.component, {\n environmentInjector: this.fieldEnvInjector(),\n injector: createWrapperAwareInjector(resolved.injector, slot.injector),\n });\n this.fieldSlot = slot;\n this.pushRawInputs(this.fieldRef, this.rawInputs());\n },\n });\n\n // Push rawInputs to the innermost field. Safe mid-rebuild — renderInnermost\n // re-reads rawInputs synchronously on mount, so skipping here loses nothing.\n explicitEffect([this.rawInputs], ([rawInputs]) => {\n if (!this.fieldRef) return;\n if (this.lastPushedInputs === rawInputs) return;\n this.pushRawInputs(this.fieldRef, rawInputs);\n });\n\n this.destroyRef.onDestroy(() => {\n // Only destroy when detached — vcr.clear() cascades otherwise.\n if (this.fieldRef && !this.fieldSlot) this.fieldRef.destroy();\n this.fieldRef = undefined;\n this.fieldSlot = undefined;\n this.lastPushedInputs = undefined;\n });\n }\n\n private detachFieldRef(): void {\n if (!this.fieldRef) return;\n if (!this.fieldSlot) {\n // Stranded fieldRef — destroy to prevent a leak.\n this.fieldRef.destroy();\n this.fieldRef = undefined;\n return;\n }\n this.captureFocusSnapshot();\n const idx = this.fieldSlot.indexOf(this.fieldRef.hostView);\n if (idx >= 0) this.fieldSlot.detach(idx);\n this.fieldSlot = undefined;\n }\n\n /** Capture active element + selection before the hostView is detached from DOM. */\n private captureFocusSnapshot(): void {\n if (!this.fieldRef) return;\n const hostEl = this.fieldRef.location.nativeElement as HTMLElement;\n const active = document.activeElement;\n if (!(active instanceof HTMLElement) || !hostEl.contains(active)) return;\n const sel = active as HTMLInputElement & HTMLTextAreaElement;\n this.focusSnapshot = {\n element: active,\n selectionStart: typeof sel.selectionStart === 'number' ? sel.selectionStart : null,\n selectionEnd: typeof sel.selectionEnd === 'number' ? sel.selectionEnd : null,\n };\n }\n\n /** Re-apply the pre-detach focus + caret after the hostView is back in the DOM. */\n private restoreFocusSnapshot(): void {\n const snap = this.focusSnapshot;\n this.focusSnapshot = undefined;\n if (!snap || !snap.element.isConnected) return;\n snap.element.focus();\n if (snap.selectionStart !== null && snap.selectionEnd !== null && 'setSelectionRange' in snap.element) {\n (snap.element as HTMLInputElement).setSelectionRange(snap.selectionStart, snap.selectionEnd);\n }\n }\n\n private pushRawInputs(ref: ComponentRef<unknown>, rawInputs: Record<string, unknown>): void {\n // Ref-identity dedupe per key — mappers must emit immutable snapshots.\n const last = this.lastPushedInputs;\n for (const [key, value] of Object.entries(rawInputs)) {\n if (last && last[key] === value) continue;\n setInputIfDeclared(ref, key, value);\n }\n this.lastPushedInputs = rawInputs;\n }\n\n private buildFieldInputs(rawInputs: Record<string, unknown>): WrapperFieldInputs {\n const fieldTreeCandidate = rawInputs['field'];\n // A FieldTree is a callable (() => FieldState). We expose it to wrappers via a narrow\n // read-only view; raw FieldTree is still pushed to the innermost component for writes.\n const readonlyField =\n fieldTreeCandidate && typeof fieldTreeCandidate === 'function'\n ? toReadonlyFieldTreeCached(this.readonlyFieldCache, fieldTreeCandidate as never)\n : undefined;\n // Shallow spread — relies on the mapper contract (see WrapperFieldInputs)\n // that rawInputs are emitted as fresh snapshots, not mutated in place.\n return {\n ...(rawInputs as Record<string, unknown>),\n field: readonlyField,\n } as WrapperFieldInputs;\n }\n}\n","import { Signal } from '@angular/core';\nimport { FieldTree, submit } from '@angular/forms/signals';\nimport { catchError, EMPTY, exhaustMap, firstValueFrom, from, isObservable, Observable } from 'rxjs';\nimport { EventBus } from '../../events/event.bus';\nimport { SubmitEvent } from '../../events/constants/submit.event';\nimport { FormConfig } from '../../models/form-config';\nimport { RegisteredFieldTypes } from '../../models/registry/field-registry';\nimport type { InferFormValue } from '../../models/types/form-value-inference';\nimport type { Logger } from '../../providers/features/logger/logger.interface';\n\n/**\n * Options for creating a submission handler.\n *\n * @typeParam TFields - Array of registered field types available for this form\n * @typeParam TModel - The form value model type (inferred from TFields by default)\n */\nexport interface SubmissionHandlerOptions<\n TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[],\n TModel extends Record<string, unknown> = InferFormValue<TFields> & Record<string, unknown>,\n> {\n /** Event bus instance for listening to submit events */\n eventBus: EventBus;\n /** Signal containing the form configuration */\n configSignal: Signal<FormConfig<TFields>>;\n /** Signal containing the form instance */\n formSignal: Signal<FieldTree<TModel>>;\n /** Signal indicating whether the form is currently valid */\n validSignal: Signal<boolean>;\n /** Logger instance for consistent error reporting */\n logger: Logger;\n}\n\n/**\n * Wraps a submission action to handle both Promise and Observable returns.\n * Converts Observables to Promises for compatibility with Angular Signal Forms' submit().\n *\n * Errors are NOT caught here — they propagate so that submit() can reject its Promise,\n * allowing the caller's catchError to log and keep the submission stream alive.\n *\n * @param action - The submission action function\n * @returns A wrapped function that returns a Promise\n */\nfunction wrapSubmissionAction<TModel extends Record<string, unknown>>(\n action: (formTree: FieldTree<TModel>) => unknown,\n): (formTree: FieldTree<TModel>) => Promise<void> {\n return async (formTree: FieldTree<TModel>): Promise<void> => {\n const result = action(formTree);\n // If the action returns an Observable, convert it to a Promise\n if (isObservable(result)) {\n await firstValueFrom(result);\n return;\n }\n await Promise.resolve(result);\n };\n}\n\n/**\n * Creates an Observable that handles form submission with optional submission action.\n *\n * This utility encapsulates the submission handling logic:\n * - Listens for submit events from the event bus\n * - If a submission.action is configured, wraps it and uses Angular Signal Forms' submit()\n * - Handles both Promise and Observable returns from the action\n * - Uses exhaustMap to ignore new submissions while one is in-flight (first-submit-wins)\n *\n * The returned Observable should be subscribed to with takeUntilDestroyed() in the component.\n *\n * @param options - Configuration options for the submission handler\n * @returns Observable that processes submissions (emits when submission completes)\n *\n * @example\n * ```typescript\n * // In component constructor\n * createSubmissionHandler({\n * eventBus: this.eventBus,\n * configSignal: this.config,\n * formSignal: this.form,\n * })\n * .pipe(takeUntilDestroyed())\n * .subscribe();\n * ```\n */\nexport function createSubmissionHandler<\n TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[],\n TModel extends Record<string, unknown> = InferFormValue<TFields> & Record<string, unknown>,\n>(options: SubmissionHandlerOptions<TFields, TModel>): Observable<unknown> {\n const { eventBus, configSignal, formSignal, validSignal, logger } = options;\n\n // exhaustMap ensures first-submit-wins: a second submit event while the first\n // is in-flight is silently dropped rather than cancelling the running Promise.\n // switchMap would unsubscribe the Observable wrapper but cannot cancel the\n // underlying Promise, causing both side effects to execute.\n return eventBus.on<SubmitEvent>('submit').pipe(\n exhaustMap(() => {\n const submissionConfig = configSignal().submission;\n\n // If no submission action is configured, let the submitted output handle it\n // This maintains backward compatibility for users handling submission manually\n if (!submissionConfig?.action) {\n return EMPTY;\n }\n\n // Guard: match the (submitted) output's safety contract — reject submission\n // when the form is invalid or has pending async validators.\n if (!validSignal()) {\n logger.debug('Submission action skipped: form is not valid (invalid or pending async validators)');\n return EMPTY;\n }\n\n // Type assertion needed: submission.action accepts the form tree but its signature\n // is defined broadly in FormConfig. The actual runtime type is FieldTree<TModel>.\n const wrappedAction = wrapSubmissionAction<TModel>(submissionConfig.action as (formTree: FieldTree<TModel>) => unknown);\n\n // Use Angular Signal Forms' native submit() function\n // This automatically:\n // - Sets form.submitting() to true during execution\n // - Applies server errors to form fields on completion\n // - Sets form.submitting() to false when done\n // catchError keeps the exhaustMap stream alive after action failure —\n // without it, an unhandled error would terminate all future submissions.\n return from(submit(formSignal(), wrappedAction)).pipe(\n catchError((error: unknown) => {\n logger.error('Submission action failed:', error);\n return EMPTY;\n }),\n );\n }),\n );\n}\n","import { InjectionToken } from '@angular/core';\n\n/**\n * Injection token for globally enabling form value emission on events.\n *\n * When set to `true`, all events dispatched through the EventBus will include\n * the current form value in the `formValue` property.\n *\n * This token is configured via `withEventFormValue()` feature function.\n * Per-form overrides can be set via `options.emitFormValueOnEvents` in the form config.\n *\n * @internal\n */\nexport const EMIT_FORM_VALUE_ON_EVENTS = new InjectionToken<boolean>('EMIT_FORM_VALUE_ON_EVENTS', {\n providedIn: 'root',\n factory: () => false,\n});\n","import { Signal } from '@angular/core';\nimport { FieldTree } from '@angular/forms/signals';\n\n/**\n * Registry service that provides access to the root form and its values.\n *\n * Constructed via factory in `provideDynamicFormDI` with signals from\n * `FormStateManager` — no DI injection, no Maps, no lifecycle.\n */\nexport class RootFormRegistryService {\n constructor(\n readonly formValue: Signal<Record<string, unknown>>,\n readonly rootForm: Signal<FieldTree<Record<string, unknown>> | undefined>,\n ) {}\n}\n","import type { Logger } from './logger.interface';\n\n/**\n * No-operation logger implementation.\n * All methods are no-ops - used in production by default.\n */\nexport class NoopLogger implements Logger {\n debug(): void {\n // Intentionally empty\n }\n\n info(): void {\n // Intentionally empty\n }\n\n warn(): void {\n // Intentionally empty\n }\n\n error(): void {\n // Intentionally empty\n }\n}\n","import { inject, Injectable, InjectionToken, Signal, Type } from '@angular/core';\nimport { filter, Observable, Subject } from 'rxjs';\nimport { FormEvent, FormEventConstructor } from './interfaces/form-event';\nimport { EMIT_FORM_VALUE_ON_EVENTS } from '../providers/features/event-form-value/emit-form-value.token';\nimport { RootFormRegistryService } from '../core/registry/root-form-registry.service';\nimport { FORM_OPTIONS } from '../models/field-signal-context.token';\nimport { FormOptions } from '../models/form-config';\nimport { DynamicFormLogger } from '../providers/features/logger/logger.token';\nimport type { Logger } from '../providers/features/logger/logger.interface';\nimport { NoopLogger } from '../providers/features/logger/noop-logger';\n\n/**\n * Safely attempts to inject a dependency using an InjectionToken.\n * Returns the default value if called outside an injection context.\n */\nfunction safeInjectToken<T>(token: InjectionToken<T>, defaultValue: T): T {\n try {\n return inject(token, { optional: true }) ?? defaultValue;\n } catch {\n return defaultValue;\n }\n}\n\n/**\n * Safely attempts to inject a service class.\n * Returns the default value if called outside an injection context.\n */\nfunction safeInjectClass<T>(token: Type<T>, defaultValue: T | null): T | null {\n try {\n return inject(token, { optional: true }) ?? defaultValue;\n } catch {\n return defaultValue;\n }\n}\n\n/**\n * Creates a copy of an event with an additional formValue property.\n * Preserves the event's prototype chain so instanceof checks still work.\n */\nfunction attachFormValue<T extends FormEvent>(event: T, formValue: Record<string, unknown>): T & { formValue: unknown } {\n const prototype = Object.getPrototypeOf(event);\n return Object.assign(Object.create(prototype), event, { formValue });\n}\n\n/**\n * Event bus for form-wide event communication between field components.\n *\n * **Intended for use inside DynamicForm** — i.e. within custom field components,\n * field mappers, or other services that live inside the form's component injector.\n * Inject it directly to dispatch or observe events from within a field:\n *\n * ```typescript\n * // Inside a custom field component\n * export class MyFieldComponent {\n * private readonly eventBus = inject(EventBus);\n *\n * onAction() {\n * this.eventBus.dispatch(arrayEvent('items').append(template));\n * }\n * }\n * ```\n *\n * **If you are outside DynamicForm** (e.g. in a host component or a service that wraps\n * the form), use {@link EventDispatcher} instead. Injecting `EventBus` in a parent\n * component gives you a *different instance* that the form knows nothing about.\n *\n * `EventBus` is scoped to each `DynamicForm` instance via `provideDynamicFormDI()`.\n * It provides type-safe dispatching and RxJS-based subscription for all form events.\n *\n * @see EventDispatcher — for dispatching events from outside the form\n */\n\nconst FALLBACK_LOGGER = new NoopLogger();\n\n@Injectable()\nexport class EventBus {\n private readonly pipeline$ = new Subject<FormEvent>();\n private readonly globalEmitFormValue = safeInjectToken(EMIT_FORM_VALUE_ON_EVENTS, false);\n private readonly rootFormRegistry = safeInjectClass(RootFormRegistryService, null);\n private readonly formOptions = safeInjectToken<Signal<FormOptions | undefined> | null>(FORM_OPTIONS, null);\n private readonly logger = safeInjectToken<Logger>(DynamicFormLogger, FALLBACK_LOGGER);\n\n events$ = this.pipeline$.asObservable();\n\n /**\n * Dispatches a pre-created event instance directly.\n *\n * Use this overload with the `arrayEvent()` factory or any other code that\n * produces a `FormEvent` instance rather than a constructor:\n *\n * ```typescript\n * eventBus.dispatch(arrayEvent('contacts').append(template));\n * eventBus.dispatch(arrayEvent('contacts').pop());\n * ```\n *\n * @param event - A FormEvent instance to dispatch\n */\n dispatch(event: FormEvent): void;\n /**\n * Dispatches an event to all subscribers by instantiating the provided constructor.\n *\n * Creates an instance of the provided event constructor and broadcasts it\n * through the event pipeline to all active subscribers.\n *\n * If `withEventFormValue()` is enabled globally or `options.emitFormValueOnEvents`\n * is set to `true` in the form config, the current form value will be attached\n * to the event's `formValue` property.\n *\n * @param eventConstructor - Constructor function for the event to dispatch\n * @param args - Arguments to pass to the event constructor\n *\n * @example\n * ```typescript\n * // Dispatch a submit event\n * eventBus.dispatch(SubmitEvent);\n *\n * // Dispatch a custom event with args\n * eventBus.dispatch(CustomFormEvent, 'arg1', 42);\n * ```\n */\n // TypeScript limitation: Must use ConstructorParameters which relies on `any` in FormEventConstructor\n dispatch<T extends FormEventConstructor>(eventConstructor: T, ...args: ConstructorParameters<T>): void;\n dispatch<T extends FormEventConstructor>(eventOrConstructor: FormEvent | T, ...args: ConstructorParameters<T>): void {\n if (typeof eventOrConstructor !== 'function' && 'type' in eventOrConstructor) {\n this.emit(eventOrConstructor);\n } else {\n this.emit(new (eventOrConstructor as T)(...args));\n }\n }\n\n /**\n * Dispatches a pre-created event instance directly.\n * Used internally by EventDispatcher to forward events into the bus.\n * @internal\n */\n emitInstance(event: FormEvent): void {\n this.emit(event);\n }\n\n /**\n * Shared emit path for both dispatch() and emitInstance().\n * Attaches form value if configured, then pushes to the pipeline.\n */\n private emit(event: FormEvent): void {\n if (this.shouldEmitFormValue()) {\n const formValue = this.rootFormRegistry?.formValue();\n // Only attach if form value exists and has at least one field.\n // Empty objects {} are not attached - use hasFormValue() to check.\n if (formValue && Object.keys(formValue).length > 0) {\n this.safeEmit(attachFormValue(event, formValue));\n return;\n }\n }\n\n this.safeEmit(event);\n }\n\n /**\n * Emits an event through the pipeline. Catches any synchronous exception that escapes\n * RxJS's own error handling so dispatch() callers are never disrupted by a failing subscriber.\n */\n private safeEmit(event: FormEvent): void {\n try {\n this.pipeline$.next(event);\n } catch (err: unknown) {\n this.logger.error('[Dynamic Forms] Exception in EventBus subscriber during dispatch', err);\n }\n }\n\n /**\n * Determines whether form value should be attached to events.\n *\n * Precedence rules:\n * 1. Per-form setting (if defined) takes precedence\n * 2. Falls back to global setting\n */\n private shouldEmitFormValue(): boolean {\n const formLevelSetting = this.formOptions?.()?.emitFormValueOnEvents;\n return formLevelSetting ?? this.globalEmitFormValue;\n }\n\n /**\n * Subscribes to events of a specific type.\n *\n * @param eventType - The type of event to subscribe to\n * @returns Observable that emits events of the specified type\n */\n on<T extends FormEvent>(eventType: T['type']): Observable<T>;\n /**\n * Subscribes to events of multiple types.\n *\n * @param eventType - Array of event types to subscribe to\n * @returns Observable that emits events matching any of the specified types\n */\n on<T extends FormEvent>(eventType: Array<T['type']>): Observable<T>;\n /**\n * Subscribes to form events with type-safe filtering.\n *\n * Provides a reactive stream of events filtered by type. Supports both single\n * event type subscriptions and multi-type subscriptions for flexible event handling.\n *\n * @param eventType - Event type string or array of event type strings to filter by\n * @returns Observable stream of filtered events\n *\n * @example\n * ```typescript\n * // Subscribe to a single event type\n * eventBus.on<SubmitEvent>('submit').subscribe(event => {\n * console.log('Submit event received');\n * });\n *\n * // Subscribe to multiple event types\n * eventBus.on<SubmitEvent | FormResetEvent | ValidationErrorEvent>(['submit', 'form-reset', 'validation-error']).subscribe(event => {\n * switch (event.type) {\n * case 'submit':\n * handleSubmit();\n * break;\n * case 'form-reset':\n * handleReset();\n * break;\n * case 'validation-error':\n * handleValidationError();\n * break;\n * }\n * });\n * ```\n */\n on<T extends FormEvent>(eventType: T['type'] | Array<T['type']>): Observable<T> {\n if (Array.isArray(eventType)) {\n return this.pipeline$.pipe(filter((event): event is T => eventType.includes(event.type)));\n }\n\n return this.pipeline$.pipe(filter((event): event is T => event.type === eventType));\n }\n}\n","import { FormEvent } from '../interfaces/form-event';\n\nexport class SubmitEvent implements FormEvent {\n readonly type = 'submit' as const;\n}\n","import { FormEvent } from '../interfaces/form-event';\n\nexport class ComponentInitializedEvent implements FormEvent {\n readonly type = 'component-initialized' as const;\n\n constructor(\n public componentType: 'dynamic-form' | 'page' | 'row' | 'group' | 'array' | 'container',\n public componentId: string,\n ) {}\n}\n","import { InjectionToken, Injector, Signal } from '@angular/core';\nimport { toObservable } from '@angular/core/rxjs-interop';\nimport { Observable, of, throwError, TimeoutError } from 'rxjs';\nimport { catchError, filter, map, scan, shareReplay, switchMap, take, timeout } from 'rxjs/operators';\nimport { EventBus } from '../../events/event.bus';\nimport { ComponentInitializedEvent } from '../../events/constants/component-initialized.event';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\n\n/**\n * Injection token for configuring the initialization timeout in milliseconds.\n * Defaults to 10 seconds. When the timeout is reached, a warning is logged\n * and (initialized) emits true as a best-effort fallback.\n */\nexport const INITIALIZATION_TIMEOUT_MS = new InjectionToken<number>('INITIALIZATION_TIMEOUT_MS', {\n providedIn: 'root',\n factory: () => 10_000,\n});\n\n/**\n * Creates an observable that tracks component initialization progress.\n *\n * This function returns an observable that emits when all expected components\n * have been initialized. It uses the scan operator to accumulate initialization\n * events and emits true when the count reaches the expected total.\n *\n * @param eventBus - The event bus instance to subscribe to\n * @param expectedCount - Total number of components expected to initialize\n * @returns Observable<boolean> that emits true when all components are initialized\n *\n * @example\n * ```typescript\n * const eventBus = inject(EventBus);\n * const totalComponents = 5; // 1 dynamic-form + 2 pages + 1 row + 1 group\n *\n * const allInitialized$ = createInitializationTracker(eventBus, totalComponents);\n *\n * allInitialized$.subscribe(isComplete => {\n * if (isComplete) {\n * console.log('All components are initialized!');\n * }\n * });\n * ```\n */\nexport function createInitializationTracker(eventBus: EventBus, expectedCount: number): Observable<boolean> {\n return eventBus.on<ComponentInitializedEvent>('component-initialized').pipe(\n scan((count) => count + 1, 0),\n map((currentCount) => currentCount >= expectedCount),\n filter((isComplete) => isComplete),\n );\n}\n\n/**\n * Creates an observable that tracks component initialization progress with detailed status.\n *\n * This function returns an observable that emits the current count and completion status\n * for each initialization event, providing more granular tracking capabilities.\n *\n * @param eventBus - The event bus instance to subscribe to\n * @param expectedCount - Total number of components expected to initialize\n * @returns Observable with current count, expected count, and completion status\n *\n * @example\n * ```typescript\n * const eventBus = inject(EventBus);\n * const totalComponents = 5;\n *\n * const progress$ = createDetailedInitializationTracker(eventBus, totalComponents);\n *\n * progress$.subscribe(({ currentCount, expectedCount, isComplete }) => {\n * console.log(`Progress: ${currentCount}/${expectedCount} (${isComplete ? 'Complete' : 'In Progress'})`);\n * });\n * ```\n */\nexport function createDetailedInitializationTracker(\n eventBus: EventBus,\n expectedCount: number,\n): Observable<{ currentCount: number; expectedCount: number; isComplete: boolean }> {\n return eventBus.on<ComponentInitializedEvent>('component-initialized').pipe(\n scan((count) => count + 1, 0),\n map((currentCount) => ({\n currentCount,\n expectedCount,\n isComplete: currentCount >= expectedCount,\n })),\n );\n}\n\n/**\n * Options for setting up initialization tracking.\n */\nexport interface InitializationTrackingOptions {\n eventBus: EventBus;\n totalComponentsCount: Signal<number>;\n injector: Injector;\n componentId: string;\n}\n\n/**\n * Creates an observable that tracks when all form components are initialized.\n * Uses shareReplay({ bufferSize: 1, refCount: false }) to ensure exactly one emission\n * that can be received by late subscribers and keeps the subscription alive.\n *\n * Includes a configurable timeout (default 10s via INITIALIZATION_TIMEOUT_MS)\n * so that (initialized) does not hang forever if a container component throws\n * before emitting its initialization event. On timeout, a warning is logged\n * and true is emitted as a best-effort fallback.\n *\n * @param options - Configuration options for initialization tracking\n * @returns Observable<boolean> that emits true when all components are initialized\n *\n * @example\n * ```typescript\n * const eventBus = inject(EventBus);\n * const totalComponents = computed(() => countContainerComponents(fields));\n *\n * readonly initialized$ = setupInitializationTracking({\n * eventBus,\n * totalComponentsCount: totalComponents,\n * injector: this.injector,\n * componentId: 'dynamic-form'\n * });\n * ```\n */\nexport function setupInitializationTracking(options: InitializationTrackingOptions): Observable<boolean> {\n const { eventBus, totalComponentsCount, injector, componentId } = options;\n\n const timeoutMs = injector.get(INITIALIZATION_TIMEOUT_MS);\n const logger = injector.get(DynamicFormLogger);\n\n return toObservable(totalComponentsCount, { injector }).pipe(\n take(1),\n switchMap((count) => {\n let tracking$: Observable<boolean>;\n\n if (count === 1) {\n // Only dynamic-form component, emit immediately when it initializes\n tracking$ = eventBus.on<ComponentInitializedEvent>('component-initialized').pipe(\n filter((event) => event.componentType === 'dynamic-form' && event.componentId === componentId),\n map(() => true),\n take(1),\n );\n } else {\n tracking$ = createInitializationTracker(eventBus, count);\n }\n\n // Timeout guard: emit best-effort true if a container throws before initializing\n return tracking$.pipe(\n timeout(timeoutMs),\n catchError((error: unknown) => {\n if (error instanceof TimeoutError) {\n logger.warn(\n `Initialization timed out after ${timeoutMs}ms. ` +\n `Expected ${count} component(s) to initialize but not all reported in time. ` +\n 'This may indicate a container component threw during initialization. ' +\n 'Emitting (initialized) as best-effort.',\n );\n // Emit true as best-effort so consumers are not stuck waiting forever\n return of(true);\n }\n return throwError(() => error);\n }),\n );\n }),\n shareReplay({ bufferSize: 1, refCount: false }),\n );\n}\n","import { FieldDef } from '../base/field-def';\n\n/**\n * Scalar types supported by hidden fields.\n * These are the primitive value types that can be stored.\n */\nexport type HiddenScalar = string | number | boolean;\n\n/**\n * All value types supported by hidden fields.\n * Supports both scalar values and arrays of scalars for storing\n * multiple IDs or similar data.\n */\nexport type HiddenValue = HiddenScalar | HiddenScalar[];\n\n/**\n * Hidden field definition for storing values without rendering UI.\n *\n * Hidden fields participate in the form schema and contribute to form values,\n * but do not render any visible component. They are useful for:\n * - Storing IDs when updating existing records\n * - Persisting metadata that shouldn't be user-editable\n * - Tracking computed values that need to be submitted\n *\n * Unlike the `hidden` property on other fields (which hides a rendered field),\n * this field type renders nothing at all - it's a componentless field.\n *\n * @example\n * ```typescript\n * // Store a record ID for updates\n * const idField: HiddenField<string> = {\n * type: 'hidden',\n * key: 'id',\n * value: '550e8400-e29b-41d4-a716-446655440000',\n * };\n *\n * // Store multiple tag IDs\n * const tagIdsField: HiddenField<number[]> = {\n * type: 'hidden',\n * key: 'tagIds',\n * value: [1, 2, 3],\n * };\n * ```\n *\n * @typeParam TValue - The type of value stored (must be HiddenValue compatible)\n */\nexport interface HiddenField<TValue extends HiddenValue = HiddenValue> extends FieldDef<never> {\n /** Discriminant for hidden field type */\n type: 'hidden';\n\n /**\n * The value to store in the form.\n * This is required - a hidden field without a value serves no purpose.\n */\n value: TValue;\n}\n\n/**\n * Type guard to check if a field is a hidden field.\n *\n * @param field - The field to check\n * @returns True if the field is a HiddenField\n */\nexport function isHiddenField(field: FieldDef<unknown>): field is HiddenField {\n return field.type === 'hidden';\n}\n","import { FieldComponent, FieldDef } from '../base/field-def';\nimport { GroupAllowedChildren } from '../../models/types/nesting-constraints';\nimport { ContainerLogicConfig } from '../base/container-logic-config';\n\n/**\n * Group field interface for creating logical field groupings that map to object values\n * Groups create nested form structures where child field values are collected into an object\n * This is a programmatic grouping only - users cannot customize this field type\n *\n * TypeScript cannot enforce field nesting rules due to circular dependency limitations.\n * For documentation: Groups should contain rows and leaf fields, but NOT pages or other groups.\n * Runtime validation enforces these rules.\n *\n * Note: Groups are container fields and do not support `meta` since they have no native form element.\n */\nexport interface GroupField<TFields extends readonly GroupAllowedChildren[] = readonly GroupAllowedChildren[]> extends FieldDef<never> {\n type: 'group';\n\n readonly fields: TFields;\n\n /** Groups do not have a label property - they are logical containers only **/\n readonly label?: never;\n\n /** Groups do not support meta - they have no native form element **/\n readonly meta?: never;\n\n /**\n * Logic configurations for conditional group visibility.\n * Only 'hidden' type logic is supported for groups.\n */\n readonly logic?: ContainerLogicConfig[];\n}\n\n/**\n * Type guard for GroupField with proper type narrowing\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type guard must accept any field type\nexport function isGroupField(field: FieldDef<any>): field is GroupField {\n return field.type === 'group' && 'fields' in field;\n}\n\nexport type GroupComponent<T extends GroupAllowedChildren[]> = FieldComponent<GroupField<T>>;\n","import { FieldComponent, FieldDef } from '../base/field-def';\nimport { RowAllowedChildren } from '../../models/types/nesting-constraints';\nimport { isHiddenField } from './hidden-field';\nimport { isGroupField } from './group-field';\nimport { ContainerLogicConfig } from '../base/container-logic-config';\n\n/**\n * Row field interface for creating horizontal layouts\n * This is a special field type that contains other definitions arranged horizontally\n * The row itself doesn't have a value - it's a layout container\n * This is a programmatic field type only - users cannot customize this field type\n *\n * TypeScript cannot enforce field nesting rules due to circular dependency limitations.\n * For documentation: Rows should contain groups and leaf fields, but NOT pages, other rows, or hidden fields.\n * Runtime validation enforces these rules.\n *\n * Note: Rows are container fields and do not support `meta` since they have no native form element.\n */\nexport interface RowField<TFields extends readonly RowAllowedChildren[] = readonly RowAllowedChildren[]> extends FieldDef<never> {\n type: 'row';\n\n /** Child definitions to render within this row */\n readonly fields: TFields;\n\n /** Row fields do not have a label property **/\n readonly label?: never;\n\n /** Rows do not support meta - they have no native form element **/\n readonly meta?: never;\n\n /**\n * Logic configurations for conditional row visibility.\n * Only 'hidden' type logic is supported for rows.\n */\n readonly logic?: ContainerLogicConfig[];\n}\n\n/**\n * Type guard for RowField with proper type narrowing\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type guard must accept any field type\nexport function isRowField(field: FieldDef<any>): field is RowField {\n return field.type === 'row' && 'fields' in field && Array.isArray((field as RowField).fields);\n}\n\n/**\n * Validates that a row field doesn't contain hidden fields.\n * Hidden fields are not allowed in rows because rows are for horizontal layouts,\n * and hidden fields don't render anything.\n *\n * @param rowField The row field to validate\n * @returns true if valid (no hidden fields), false otherwise\n */\nexport function validateRowNesting(rowField: RowField): boolean {\n return !hasHiddenFields(rowField.fields);\n}\n\n/**\n * Recursively checks if fields contain any hidden fields\n * @param fields Array of field definitions to check\n * @returns true if hidden fields found, false otherwise\n */\nfunction hasHiddenFields(fields: readonly FieldDef<unknown>[]): boolean {\n for (const field of fields) {\n if (isHiddenField(field)) {\n return true;\n }\n\n // Check group fields for nested hidden fields\n if (isGroupField(field)) {\n if (hasHiddenFields(field.fields)) {\n return true;\n }\n }\n }\n return false;\n}\n\nexport type RowComponent = FieldComponent<RowField<RowAllowedChildren[]>>;\n","import { FieldDef } from '../base/field-def';\nimport { PageAllowedChildren } from '../../models/types/nesting-constraints';\nimport { isRowField } from './row-field';\nimport { isGroupField } from './group-field';\nimport { ContainerLogicConfig } from '../base/container-logic-config';\n\n/**\n * Page field interface for creating top-level page layouts\n * This is a special field type that contains other field definitions\n * The page itself doesn't have a value - it's a layout container like row\n * Pages can only be used at the top level and cannot be nested\n * This is a programmatic field type only - users cannot customize this field type\n *\n * TypeScript cannot enforce field nesting rules due to circular dependency limitations.\n * For documentation: Pages should contain rows, groups, and leaf fields, but NOT other pages.\n * Runtime validation enforces these rules.\n *\n * Note: Pages are container fields and do not support `meta` since they have no native form element.\n */\nexport interface PageField<TFields extends readonly PageAllowedChildren[] = PageAllowedChildren[]> extends FieldDef<never> {\n type: 'page';\n\n /** Child field definitions to render within this page */\n readonly fields: TFields;\n\n /** Page fields do not have a label property **/\n readonly label?: never;\n\n /** Pages do not support meta - they have no native form element **/\n readonly meta?: never;\n\n /**\n * Logic configurations for conditional page visibility.\n * Only 'hidden' type logic is supported for pages.\n *\n * @example\n * ```typescript\n * {\n * key: 'businessPage',\n * type: 'page',\n * logic: [{\n * type: 'hidden',\n * condition: {\n * type: 'fieldValue',\n * fieldPath: 'accountType',\n * operator: 'notEquals',\n * value: 'business',\n * },\n * }],\n * fields: [...]\n * }\n * ```\n */\n readonly logic?: ContainerLogicConfig[];\n}\n\n/**\n * Type guard for PageField with proper type narrowing\n */\nexport function isPageField(field: FieldDef<unknown>): field is PageField {\n return field.type === 'page' && 'fields' in field && Array.isArray((field as PageField).fields);\n}\n\n/**\n * Validates that a page field doesn't contain nested page fields\n * @param pageField The page field to validate\n * @returns true if valid (no nested pages), false otherwise\n */\nexport function validatePageNesting(pageField: PageField): boolean {\n return !hasNestedPages(pageField.fields);\n}\n\n/**\n * Type guard to check if a field is a container with fields property\n */\nfunction isContainerWithFields(field: FieldDef<unknown>): field is FieldDef<unknown> & { readonly fields: readonly FieldDef<unknown>[] } {\n return (isRowField(field) || isGroupField(field)) && 'fields' in field && Array.isArray((field as { fields: unknown }).fields);\n}\n\n/**\n * Recursively checks if fields contain any nested page fields\n * @param fields Array of field definitions to check\n * @returns true if nested pages found, false otherwise\n */\nfunction hasNestedPages(fields: readonly FieldDef<unknown>[]): boolean {\n for (const field of fields) {\n if (isPageField(field)) {\n return true;\n }\n\n // Check row and group fields for nested pages\n if (isContainerWithFields(field)) {\n if (hasNestedPages(field.fields)) {\n return true;\n }\n }\n }\n return false;\n}\n","import { FieldComponent, FieldDef } from '../base/field-def';\nimport { ArrayAllowedChildren } from '../../models/types/nesting-constraints';\nimport { ContainerLogicConfig } from '../base/container-logic-config';\n\n/**\n * An array item template is an array of allowed children that defines one OBJECT array item's fields.\n * Used for object arrays where each item is `{ key1: value1, key2: value2, ... }`.\n */\nexport type ArrayItemTemplate = readonly ArrayAllowedChildren[];\n\n/**\n * An array item definition can be either:\n * - A single field (ArrayAllowedChildren) for PRIMITIVE array items - extracts field value directly\n * - An array of fields (ArrayItemTemplate) for OBJECT array items - merges fields into object\n *\n * This allows support for:\n * - Primitive arrays: `['tag1', 'tag2']`\n * - Object arrays: `[{ name: 'Alice', email: '...' }]`\n * - Heterogeneous arrays: `[{ value: 'x' }, 'y']` (mixed primitives and objects)\n */\nexport type ArrayItemDefinition = ArrayAllowedChildren | ArrayItemTemplate;\n\n/**\n * Array field interface for creating dynamic field collections that map to array values.\n *\n * Key concepts:\n * - The outer `fields` array defines INITIAL ITEMS (each element is one array item to render)\n * - Each element can be either:\n * - A single FieldDef (primitive item) - the field's value is extracted directly\n * - An array of FieldDefs (object item) - fields are merged into an object\n * - Items can have different field configurations (heterogeneous arrays supported)\n * - Empty `fields: []` means no initial items - user adds via buttons with explicit templates\n * - Initial values are declared via `value` property on each field definition\n *\n * @example\n * // Primitive array: ['angular', 'typescript']\n * {\n * key: 'tags',\n * type: 'array',\n * fields: [\n * { key: 'tag', type: 'input', value: 'angular' }, // Single field = primitive\n * { key: 'tag', type: 'input', value: 'typescript' },\n * ]\n * }\n *\n * @example\n * // Object array: [{ name: 'Alice', email: '...' }]\n * {\n * key: 'contacts',\n * type: 'array',\n * fields: [\n * [ // Array = object\n * { key: 'name', type: 'input', value: 'Alice' },\n * { key: 'email', type: 'input', value: 'alice@example.com' }\n * ],\n * ]\n * }\n *\n * @example\n * // Heterogeneous array: [{ label: 'Structured' }, 'Simple']\n * {\n * key: 'items',\n * type: 'array',\n * fields: [\n * [{ key: 'label', type: 'input', value: 'Structured' }], // Object item\n * { key: 'value', type: 'input', value: 'Simple' }, // Primitive item\n * ]\n * }\n *\n * @example\n * // Empty array (add items via buttons)\n * {\n * key: 'tags',\n * type: 'array',\n * fields: [] // No initial items - user adds via button with template\n * }\n *\n * Nesting constraints: Arrays can contain rows, leaf fields, or groups (for object arrays),\n * but NOT pages or other arrays. Runtime validation enforces these rules.\n *\n * Note: Arrays are container fields and do not support `meta` since they have no native form element.\n */\nexport interface ArrayField<TFields extends readonly ArrayItemDefinition[] = readonly ArrayItemDefinition[]> extends FieldDef<never> {\n type: 'array';\n\n /**\n * Array of item definitions. Each element defines one array item:\n * - Single FieldDef = primitive item (field's value is extracted directly)\n * - Array of FieldDefs = object item (fields are merged into an object)\n * - Empty array `[]` = no initial items (add via buttons with explicit templates)\n * - Items can have different configurations (heterogeneous arrays supported)\n * - Initial values are set via `value` property on each field definition\n */\n readonly fields: TFields;\n\n /** Array fields do not have a label property **/\n readonly label?: never;\n\n /** Arrays do not support meta - they have no native form element **/\n readonly meta?: never;\n\n /**\n * Logic configurations for conditional array visibility.\n * Only 'hidden' type logic is supported for arrays.\n */\n readonly logic?: ContainerLogicConfig[];\n\n /**\n * Minimum number of items required in the array.\n * Validation fails if the array has fewer items than this value.\n */\n readonly minLength?: number;\n\n /**\n * Maximum number of items allowed in the array.\n * Validation fails if the array has more items than this value.\n */\n readonly maxLength?: number;\n}\n\n/**\n * Type guard for ArrayField with proper type narrowing.\n * Validates that the field is an array type with a fields property that is an array.\n * Fields can contain either single FieldDefs (primitive items) or arrays of FieldDefs (object items).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type guard must accept any field type\nexport function isArrayField(field: FieldDef<any>): field is ArrayField {\n return field.type === 'array' && 'fields' in field && Array.isArray(field.fields);\n}\n\nexport type ArrayComponent<T extends ArrayItemTemplate[]> = FieldComponent<ArrayField<T>>;\n\n/**\n * Configuration for auto-generated add/remove buttons in simplified array fields.\n */\nexport interface ArrayButtonConfig {\n /** Custom label for the button */\n readonly label?: string;\n /** Additional properties passed to the button component */\n readonly props?: Record<string, unknown>;\n}\n\n/**\n * Simplified array field interface for common use cases.\n *\n * Instead of manually specifying each item in `fields`, provide a `template` that defines\n * the structure of a single item, and a `value` array with initial data.\n * The library auto-generates add/remove buttons.\n *\n * Discriminant: `template` presence → simplified API; `Array.isArray(template)` → object vs primitive.\n *\n * @example\n * // Primitive array: ['angular', 'typescript']\n * {\n * key: 'tags',\n * type: 'array',\n * template: { key: 'value', type: 'input', label: 'Tag', required: true },\n * value: ['angular', 'typescript']\n * }\n *\n * @example\n * // Object array: [{ name: 'Jane', phone: '555' }]\n * {\n * key: 'contacts',\n * type: 'array',\n * template: [\n * { key: 'name', type: 'input', label: 'Contact Name', required: true },\n * { key: 'phone', type: 'input', label: 'Phone Number' },\n * ],\n * value: [{ name: 'Jane', phone: '555' }]\n * }\n *\n * @example\n * // Button customization / opt-out\n * {\n * key: 'tags',\n * type: 'array',\n * template: { key: 'value', type: 'input', label: 'Tag' },\n * addButton: { label: 'Add Tag', props: { color: 'primary' } },\n * removeButton: false\n * }\n */\nexport interface SimplifiedArrayField extends FieldDef<never> {\n type: 'array';\n\n /**\n * Template defining the structure of a single array item.\n * - Single field (ArrayAllowedChildren) → primitive array (each item is a single value)\n * - Array of fields (readonly ArrayAllowedChildren[]) → object array (each item is an object)\n */\n readonly template: ArrayAllowedChildren | readonly ArrayAllowedChildren[];\n\n /** Initial values for the array. Each element creates one array item. */\n readonly value?: readonly unknown[];\n\n /**\n * Configuration for the auto-generated \"Add\" button, or `false` to disable it.\n * Defaults to a button with label \"Add\".\n */\n readonly addButton?: ArrayButtonConfig | false;\n\n /**\n * Configuration for the auto-generated \"Remove\" button on each item, or `false` to disable it.\n * Defaults to a button with label \"Remove\".\n */\n readonly removeButton?: ArrayButtonConfig | false;\n\n /** Simplified arrays do not support the label property */\n readonly label?: never;\n\n /** Simplified arrays do not support meta */\n readonly meta?: never;\n\n /**\n * Logic configurations for conditional array visibility.\n * Only 'hidden' type logic is supported for arrays.\n */\n readonly logic?: ContainerLogicConfig[];\n\n /**\n * Minimum number of items required in the array.\n * Validation fails if the array has fewer items than this value.\n */\n readonly minLength?: number;\n\n /**\n * Maximum number of items allowed in the array.\n * Validation fails if the array has more items than this value.\n */\n readonly maxLength?: number;\n\n /** Mutually exclusive with `template` — use `fields` for the full API instead */\n readonly fields?: never;\n}\n\n/**\n * Type guard for SimplifiedArrayField.\n * Checks for `type: 'array'` with a `template` property (discriminant from full ArrayField).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type guard must accept any field type\nexport function isSimplifiedArrayField(field: FieldDef<any>): field is SimplifiedArrayField {\n return field.type === 'array' && 'template' in field;\n}\n","import { FieldComponent, FieldDef } from '../base/field-def';\nimport { ContainerAllowedChildren } from '../../models/types/nesting-constraints';\nimport { ContainerLogicConfig } from '../base/container-logic-config';\nimport { WrapperConfig } from '../../models/wrapper-type';\n\n/**\n * Container field interface for wrapping child fields with UI chrome.\n *\n * A container field is a container that renders its children inside a chain\n * of wrapper components. Each wrapper provides visual decoration (sections,\n * headers, expand/collapse, styling) without affecting the form data structure.\n *\n * Like a row field, the container field:\n * - Does not create a new form context\n * - Flattens child values into the parent form\n * - Is purely a visual/layout container\n *\n * Unlike a row field, the container field:\n * - Supports a `wrappers` array that chains wrapper components around the children\n * - Uses imperative `ViewContainerRef.createComponent()` for the wrapper chain\n *\n * TypeScript cannot enforce field nesting rules due to circular dependency limitations.\n * For documentation: Containers follow the same nesting rules as rows — they should\n * contain groups and leaf fields, but NOT pages, other rows, or hidden fields.\n * Runtime validation enforces these rules.\n *\n * @example\n * ```typescript\n * const field: ContainerField = {\n * type: 'container',\n * key: 'contactSection',\n * fields: [\n * { key: 'email', type: 'input', value: '' },\n * { key: 'phone', type: 'input', value: '' },\n * ],\n * wrappers: [\n * { type: 'section', header: 'Contact Info' },\n * ]\n * };\n * ```\n *\n * @example\n * ```typescript\n * // Multiple wrappers chain from outermost to innermost\n * const field: ContainerField = {\n * type: 'container',\n * key: 'styledSection',\n * fields: [{ key: 'name', type: 'input', value: '' }],\n * wrappers: [\n * { type: 'section', header: 'Details' }, // outermost\n * { type: 'style', class: 'highlight' }, // innermost\n * ]\n * };\n * ```\n */\nexport interface ContainerField<\n TFields extends readonly ContainerAllowedChildren[] = readonly ContainerAllowedChildren[],\n TWrapperConfigs extends readonly WrapperConfig[] = readonly WrapperConfig[],\n> extends FieldDef<never> {\n type: 'container';\n\n /** Child definitions to render within this container */\n readonly fields: TFields;\n\n /**\n * Wrapper components to chain around the children.\n * Applied outermost-first: the first wrapper in the array is the outermost.\n * Each wrapper component receives the subsequent wrapper (or children) inside\n * its `#fieldComponent` ViewContainerRef slot.\n */\n readonly wrappers: TWrapperConfigs;\n\n /** Container fields do not have a label property */\n readonly label?: never;\n\n /** Containers do not support meta — they have no native form element */\n readonly meta?: never;\n\n /**\n * Logic configurations for conditional container visibility.\n * Only 'hidden' type logic is supported for containers.\n */\n readonly logic?: ContainerLogicConfig[];\n}\n\n/**\n * Type guard for ContainerField with proper type narrowing\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Type guard must accept any field type\nexport function isContainerTypedField(field: FieldDef<any>): field is ContainerField {\n return field.type === 'container' && 'fields' in field && 'wrappers' in field;\n}\n\nexport type ContainerComponent = FieldComponent<ContainerField<ContainerAllowedChildren[]>>;\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { isPageField } from '../../definitions/default/page-field';\nimport { isRowField } from '../../definitions/default/row-field';\nimport { isGroupField } from '../../definitions/default/group-field';\nimport { isArrayField } from '../../definitions/default/array-field';\nimport { isContainerTypedField } from '../../definitions/default/container-field';\nimport { ContainerFieldTypes, LeafFieldTypes, RegisteredFieldTypes } from '../registry/field-registry';\n\n/**\n * Type guard to check if a field definition has child fields.\n * This is a looser check that works with FieldDef<unknown> without requiring RegisteredFieldTypes.\n */\nexport function hasChildFields<T>(\n field: FieldDef<T>,\n): field is FieldDef<T> & { fields: FieldDef<unknown>[] | Record<string, FieldDef<unknown>> } {\n return 'fields' in field && field.fields != null;\n}\n\n/** Container field type names */\nconst CONTAINER_TYPES = new Set(['page', 'row', 'group', 'array', 'container']);\n\n/**\n * Type guard to check if a field is a container field (page, row, group, or array)\n * Container fields have a 'fields' property and don't contribute values directly.\n * This overload works with RegisteredFieldTypes for full type narrowing.\n */\nexport function isContainerField(field: RegisteredFieldTypes): field is ContainerFieldTypes;\n/**\n * Type guard to check if a field is a container field (page, row, group, or array).\n * This overload works with any FieldDef for looser type checking.\n */\nexport function isContainerField(field: FieldDef<unknown>): boolean;\nexport function isContainerField(field: FieldDef<unknown> | RegisteredFieldTypes): boolean {\n return CONTAINER_TYPES.has(field.type);\n}\n\n/**\n * Type guard to check if a field is a leaf field (value or display field)\n * Leaf fields don't have children and either contribute values or display content\n */\nexport function isLeafField(field: RegisteredFieldTypes): field is LeafFieldTypes {\n return !isContainerField(field);\n}\n\n/**\n * Type guard to check if a field has a value property (value-bearing field)\n * These fields contribute to the form value output\n * Note: Using `unknown` in the Extract condition to match any value type\n */\nexport function isValueBearingField(field: RegisteredFieldTypes): field is Extract<RegisteredFieldTypes, { value: unknown }> {\n return 'value' in field;\n}\n\n/**\n * Type guard to check if a field is excluded from form values (display-only field)\n * Currently this includes text fields and any other fields without a value property\n */\nexport function isDisplayOnlyField(field: RegisteredFieldTypes): boolean {\n return field.type === 'text' || isContainerField(field);\n}\n\n// Re-export the specific type guards for convenience\nexport { isPageField, isRowField, isGroupField, isArrayField, isContainerTypedField };\n","import { Injector, Signal } from '@angular/core';\nimport { toObservable, toSignal } from '@angular/core/rxjs-interop';\nimport { debounceTime, distinctUntilChanged, tap } from 'rxjs';\n\n/**\n * Default debounce duration in milliseconds.\n */\nexport const DEFAULT_DEBOUNCE_MS = 500;\n\n/**\n * Creates a debounced effect that triggers a callback after a signal's value\n * has stabilized for the specified duration.\n *\n * Uses Angular's `toObservable` and `toSignal` with RxJS `debounceTime` for proper debouncing.\n * This approach is cleaner than manual setTimeout management and integrates\n * well with Angular's signal-based reactivity.\n *\n * @param source - The source signal to watch for changes\n * @param callback - Function to call with the debounced value\n * @param options - Configuration options\n * @param options.ms - Debounce duration in milliseconds (default: 500)\n * @param options.injector - Angular injector for the effect context\n *\n * @returns A signal that emits the debounced value (can be ignored if only side effects are needed)\n *\n * @example\n * ```typescript\n * // In a component or service\n * const searchInput = signal('');\n *\n * createDebouncedEffect(\n * searchInput,\n * (value) => console.log('Debounced search:', value),\n * { ms: 300, injector: this.injector }\n * );\n * ```\n *\n * @public\n */\nexport function createDebouncedEffect<T>(\n source: Signal<T>,\n callback: (value: T) => void,\n options: { ms?: number; injector: Injector },\n): Signal<T | undefined> {\n const { ms = DEFAULT_DEBOUNCE_MS, injector } = options;\n\n const source$ = toObservable(source, { injector }).pipe(\n debounceTime(ms),\n distinctUntilChanged(),\n tap((value) => callback(value)),\n );\n\n return toSignal(source$, { injector });\n}\n\n/**\n * Creates a debounced signal that emits values from the source signal\n * only after the value has stabilized for the specified duration.\n *\n * Unlike `createDebouncedEffect`, this doesn't execute a side effect callback.\n * Use this when you just need a debounced version of a signal.\n *\n * @param source - The source signal to debounce\n * @param options - Configuration options\n * @param options.ms - Debounce duration in milliseconds (default: 500)\n * @param options.injector - Angular injector for the effect context\n *\n * @returns A signal that emits the debounced value\n *\n * @example\n * ```typescript\n * const input = signal('');\n * const debouncedInput = createDebouncedSignal(input, { ms: 300, injector });\n *\n * effect(() => {\n * console.log('Debounced value:', debouncedInput());\n * });\n * ```\n *\n * @public\n */\nexport function createDebouncedSignal<T>(source: Signal<T>, options: { ms?: number; injector: Injector }): Signal<T | undefined> {\n const { ms = DEFAULT_DEBOUNCE_MS, injector } = options;\n\n const source$ = toObservable(source, { injector }).pipe(debounceTime(ms), distinctUntilChanged());\n\n return toSignal(source$, { injector });\n}\n","/**\n * Native JavaScript utility functions to replace lodash-es\n * These are simple implementations for common object manipulation patterns\n */\n\nimport { DynamicFormError } from '../errors/dynamic-form-error';\n\n/**\n * Performs a deep equality comparison between two values.\n *\n * Handles:\n * - Primitives (including NaN via Object.is)\n * - Dates (by timestamp)\n * - Arrays (deep element comparison)\n * - Plain objects (deep property comparison)\n * - RegExp (by source and flags)\n * - Map and Set (by entries)\n * - Circular references (via WeakMap tracking)\n *\n * @param a - First value\n * @param b - Second value\n * @returns true if values are deeply equal\n *\n * @example\n * ```typescript\n * isEqual({ a: 1 }, { a: 1 }); // true\n * isEqual([1, 2], [1, 2]); // true\n * isEqual({ a: 1 }, { a: 2 }); // false\n * isEqual(new Date('2024-01-01'), new Date('2024-01-01')); // true\n * isEqual(/abc/gi, /abc/gi); // true\n * ```\n */\nexport function isEqual(a: unknown, b: unknown): boolean {\n return isEqualInternal(a, b, new WeakMap(), new WeakMap());\n}\n\n/**\n * Internal implementation with circular reference tracking.\n * @internal\n */\nfunction isEqualInternal(a: unknown, b: unknown, seenA: WeakMap<object, object>, seenB: WeakMap<object, object>): boolean {\n // Same reference or both null/undefined\n if (a === b) return true;\n\n // Handle NaN (NaN === NaN is false, but we want it to be equal)\n if (typeof a === 'number' && typeof b === 'number') {\n return Object.is(a, b);\n }\n\n // One is null/undefined but not both\n if (a == null || b == null) return false;\n\n // Different types\n if (typeof a !== typeof b) return false;\n\n // Non-object primitives (strings, booleans, symbols, bigints)\n if (typeof a !== 'object') {\n return Object.is(a, b);\n }\n\n // At this point, both a and b are objects (typeof a === 'object')\n const objA = a as object;\n const objB = b as object;\n\n // Check for circular references\n if (seenA.has(objA) || seenB.has(objB)) {\n // If we've seen these objects before, check if they were paired together\n return seenA.get(objA) === objB && seenB.get(objB) === objA;\n }\n\n // Mark these objects as seen (paired together)\n seenA.set(objA, objB);\n seenB.set(objB, objA);\n\n // Different constructors means different types (e.g., Date vs Object)\n if (objA.constructor !== objB.constructor) return false;\n\n // Handle dates\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // Handle RegExp\n if (a instanceof RegExp && b instanceof RegExp) {\n return a.source === b.source && a.flags === b.flags;\n }\n\n // Handle Map\n if (a instanceof Map && b instanceof Map) {\n if (a.size !== b.size) return false;\n for (const [key, value] of a) {\n if (!b.has(key) || !isEqualInternal(value, b.get(key), seenA, seenB)) {\n return false;\n }\n }\n return true;\n }\n\n // Handle Set\n if (a instanceof Set && b instanceof Set) {\n if (a.size !== b.size) return false;\n for (const value of a) {\n if (!b.has(value)) {\n // For non-primitive values in Sets, we need deep comparison\n // This is O(n^2) but Sets rarely contain objects\n if (typeof value === 'object' && value !== null) {\n let found = false;\n for (const bValue of b) {\n if (typeof bValue === 'object' && bValue !== null && isEqualInternal(value, bValue, seenA, seenB)) {\n found = true;\n break;\n }\n }\n if (!found) return false;\n } else {\n return false;\n }\n }\n }\n return true;\n }\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((item, index) => isEqualInternal(item, b[index], seenA, seenB));\n }\n\n // Handle plain objects\n const recordA = a as Record<string | symbol, unknown>;\n const recordB = b as Record<string | symbol, unknown>;\n\n // Get both string and symbol keys\n const keysA = [...Object.keys(recordA), ...Object.getOwnPropertySymbols(recordA)];\n const keysB = [...Object.keys(recordB), ...Object.getOwnPropertySymbols(recordB)];\n\n if (keysA.length !== keysB.length) return false;\n\n // Create a Set for O(1) lookup\n const keySetB = new Set(keysB);\n\n return keysA.every((key) => keySetB.has(key) && isEqualInternal(recordA[key], recordB[key], seenA, seenB));\n}\n\n/**\n * Creates a new object without the specified keys\n * Native replacement for lodash omit()\n *\n * @param obj - Source object\n * @param keys - Keys to omit\n * @returns New object without specified keys\n *\n * @example\n * ```typescript\n * const obj = { a: 1, b: 2, c: 3 };\n * omit(obj, ['b']); // { a: 1, c: 3 }\n * ```\n */\nexport function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {\n const result = { ...obj };\n keys.forEach((key) => delete result[key]);\n return result as Omit<T, K>;\n}\n\n/**\n * Creates an object from an array, keyed by a specified property\n * Native replacement for lodash keyBy()\n *\n * @param array - Source array\n * @param key - Property to use as key\n * @returns Object keyed by the specified property\n *\n * @example\n * ```typescript\n * const users = [{ id: 'a', name: 'Alice' }, { id: 'b', name: 'Bob' }];\n * keyBy(users, 'id'); // { a: { id: 'a', name: 'Alice' }, b: { id: 'b', name: 'Bob' } }\n * ```\n */\nexport function keyBy<T extends object>(array: T[], key: keyof T): Record<string, T> {\n return array.reduce(\n (acc, item) => {\n acc[String(item[key])] = item;\n return acc;\n },\n {} as Record<string, T>,\n );\n}\n\n/**\n * Maps object values through a transformation function\n * Native replacement for lodash mapValues()\n *\n * @param obj - Source object\n * @param fn - Transformation function\n * @returns New object with transformed values\n *\n * @example\n * ```typescript\n * const obj = { a: 1, b: 2 };\n * mapValues(obj, (v) => v * 2); // { a: 2, b: 4 }\n * ```\n */\nexport function mapValues<T, U>(obj: Record<string, T>, fn: (value: T, key: string) => U): Record<string, U> {\n return Object.entries(obj).reduce(\n (acc, [key, value]) => {\n acc[key] = fn(value, key);\n return acc;\n },\n {} as Record<string, U>,\n );\n}\n\n/**\n * Options for memoize function\n */\n/** Default maximum cache size for memoized functions */\nconst DEFAULT_MEMOIZE_MAX_SIZE = 100;\n\nexport interface MemoizeOptions<TFunc extends (...args: never[]) => unknown> {\n /** Optional function to generate cache key from arguments */\n resolver?: (...args: Parameters<TFunc>) => string | number;\n /** Maximum number of entries to keep in cache. Uses LRU eviction when exceeded. Defaults to 100. */\n maxSize?: number;\n}\n\n/**\n * Memoizes a function with LRU cache eviction and optional custom cache key resolver.\n *\n * @param fn - Function to memoize\n * @param resolverOrOptions - Optional key resolver function or options object\n * @returns Memoized function\n *\n * @example\n * ```typescript\n * const expensive = (a: number, b: number) => a + b;\n * const memoized = memoize(expensive); // Uses default maxSize of 100\n *\n * // With custom resolver\n * const withResolver = memoize(expensive, (a, b) => `${a}-${b}`);\n *\n * // With custom maxSize\n * const small = memoize(expensive, { maxSize: 10 });\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function memoize<TFunc extends (...args: any[]) => any>(\n fn: TFunc,\n resolverOrOptions?: ((...args: Parameters<TFunc>) => string | number) | MemoizeOptions<TFunc>,\n): TFunc {\n const options: MemoizeOptions<TFunc> =\n typeof resolverOrOptions === 'function' ? { resolver: resolverOrOptions } : (resolverOrOptions ?? {});\n\n const { resolver, maxSize = DEFAULT_MEMOIZE_MAX_SIZE } = options;\n const cache = new Map<string | number, ReturnType<TFunc>>();\n\n return ((...args: Parameters<TFunc>): ReturnType<TFunc> => {\n const key = resolver ? resolver(...args) : JSON.stringify(args);\n\n const cachedValue = cache.get(key);\n if (cachedValue !== undefined) {\n cache.delete(key);\n cache.set(key, cachedValue);\n return cachedValue;\n }\n\n const result = fn(...args);\n\n if (cache.size >= maxSize) {\n const oldestKey = cache.keys().next().value;\n if (oldestKey !== undefined) {\n cache.delete(oldestKey);\n }\n }\n\n cache.set(key, result);\n return result;\n }) as TFunc;\n}\n\n/**\n * Normalizes a fields collection to an array.\n * Handles both array format and object format (keyed by field key).\n *\n * @param fields - Fields as array or object\n * @returns Fields as array\n */\nexport function normalizeFieldsArray<T>(fields: readonly T[] | Record<string, T>): T[] {\n return Array.isArray(fields) ? [...fields] : Object.values(fields);\n}\n\n/**\n * Gets the keys that differ between two objects.\n *\n * Compares top-level keys and returns those whose values are different.\n * Uses deep equality comparison for nested values.\n *\n * @param previous - Previous object state\n * @param current - Current object state\n * @returns Set of keys that have different values\n *\n * @example\n * ```typescript\n * const prev = { a: 1, b: 2, c: 3 };\n * const curr = { a: 1, b: 5, d: 4 };\n * getChangedKeys(prev, curr); // Set { 'b', 'c', 'd' }\n * ```\n */\nexport function getChangedKeys(\n previous: Record<string, unknown> | null | undefined,\n current: Record<string, unknown> | null | undefined,\n): Set<string> {\n const changedKeys = new Set<string>();\n\n // Handle null/undefined cases\n if (!previous && !current) return changedKeys;\n if (!previous) {\n return new Set(Object.keys(current ?? {}));\n }\n if (!current) {\n return new Set(Object.keys(previous));\n }\n\n // Collect all keys from both objects\n const allKeys = new Set([...Object.keys(previous), ...Object.keys(current)]);\n\n // Check each key for differences\n for (const key of allKeys) {\n const prevValue = previous[key];\n const currValue = current[key];\n\n // Key added or removed\n if (!(key in previous) || !(key in current)) {\n changedKeys.add(key);\n continue;\n }\n\n // Value changed\n if (!isEqual(prevValue, currValue)) {\n changedKeys.add(key);\n }\n }\n\n return changedKeys;\n}\n\n/**\n * Fast 32-bit FNV-1a hash for strings.\n * Used as a cache key to avoid expensive string concatenation in memoize resolvers.\n *\n * @param str - String to hash\n * @returns 32-bit integer hash\n */\nexport function simpleStringHash(str: string): number {\n let hash = 0x811c9dc5; // FNV offset basis\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash = (hash * 0x01000193) | 0; // FNV prime, keep as 32-bit int\n }\n return hash;\n}\n\n/**\n * Compile-time exhaustiveness check for discriminated unions.\n *\n * Place in the `default` branch of a `switch` over a union's discriminant.\n * TypeScript narrows the value to `never` only when every member is handled;\n * adding a new member without a matching `case` produces a type error here.\n *\n * At runtime, throws if somehow reached (defensive guard).\n *\n * @example\n * ```ts\n * switch (action.type) {\n * case 'a': return handleA(action);\n * case 'b': return handleB(action);\n * default: return assertNever(action);\n * }\n * ```\n */\nexport function assertNever(value: never): never {\n throw new DynamicFormError(`Unexpected value: ${JSON.stringify(value)}`);\n}\n","import { Injectable } from '@angular/core';\nimport { CustomFunction, CustomFunctionOptions, CustomFunctionScope } from '../expressions/custom-function-types';\nimport type { AsyncConditionFunction, AsyncDerivationFunction } from '../expressions/async-custom-function-types';\nimport { AsyncCustomValidator, CustomValidator, HttpCustomValidator } from '../validation/validator-types';\n\n/**\n * Registry service for custom functions and validators\n *\n * This service maintains six separate registries:\n *\n * 1. **Custom Functions** - For conditional expressions (when/readonly/disabled)\n * - Used in: when conditions, readonly logic, disabled logic\n * - Return type: any value (typically boolean)\n * - Example: `isAdult: (ctx) => ctx.age >= 18`\n *\n * 2. **Custom Validators** - For synchronous validation using Angular's public FieldContext API\n * - Used in: validators array on fields\n * - Return type: ValidationError | ValidationError[] | null\n * - Example: `noSpaces: (ctx) => ctx.value().includes(' ') ? { kind: 'noSpaces' } : null`\n *\n * 3. **Async Validators** - For asynchronous validation (debouncing, database lookups, etc.)\n * - Used in: validators array on fields with type 'async'\n * - Return type: Observable<ValidationError | ValidationError[] | null>\n * - Example: `checkUsername: (ctx) => userService.checkAvailability(ctx.value())`\n *\n * 4. **HTTP Validators** - For HTTP-based validation with automatic request cancellation\n * - Used in: validators array on fields with type 'http'\n * - Configuration object with url, method, mapResponse, etc.\n * - Example: `{ url: '/api/check', method: 'GET', mapResponse: ... }`\n *\n * 5. **Async Derivation Functions** - For asynchronous value derivation via Promise/Observable\n * - Used in: derivation config with `asyncFunctionName`\n * - Return type: Promise<unknown> | Observable<unknown>\n * - Example: `fetchPrice: (ctx) => priceService.get(ctx.formValue.productId)`\n *\n * 6. **Async Condition Functions** - For asynchronous boolean conditions via Promise/Observable\n * - Used in: condition config with `type: 'async'` and `asyncFunctionName`\n * - Return type: Promise<boolean> | Observable<boolean>\n * - Example: `checkAdmin: (ctx) => authService.hasRole(ctx.formValue.userId, 'admin')`\n *\n * @example\n * ```typescript\n * // Register a custom function for expressions\n * registry.registerCustomFunction('isAdult', (ctx) => ctx.age >= 18);\n *\n * // Use in field configuration\n * {\n * key: 'alcoholPreference',\n * when: { function: 'isAdult' }\n * }\n *\n * // Register a custom validator\n * registry.registerValidator('noSpaces', (ctx) => {\n * const value = ctx.value();\n * return typeof value === 'string' && value.includes(' ')\n * ? { kind: 'noSpaces' }\n * : null;\n * });\n *\n * // Use in field configuration\n * {\n * key: 'username',\n * validators: [{ type: 'custom', functionName: 'noSpaces' }],\n * validationMessages: {\n * noSpaces: 'Spaces are not allowed'\n * }\n * }\n * ```\n */\n@Injectable()\nexport class FunctionRegistryService {\n private readonly customFunctions = new Map<string, CustomFunction>();\n private readonly customFunctionScopes = new Map<string, CustomFunctionScope>();\n private readonly derivationFunctions = new Map<string, CustomFunction>();\n private readonly asyncDerivationFunctions = new Map<string, AsyncDerivationFunction>();\n private readonly asyncConditionFunctions = new Map<string, AsyncConditionFunction>();\n private readonly validators = new Map<string, CustomValidator>();\n private readonly asyncValidators = new Map<string, AsyncCustomValidator>();\n private readonly httpValidators = new Map<string, HttpCustomValidator>();\n\n /**\n * Register a custom function for conditional expressions\n *\n * Custom functions are used for control flow logic (when/readonly/disabled),\n * NOT for validation. They return any value, typically boolean.\n *\n * @param name - Unique identifier for the function\n * @param fn - Function that receives EvaluationContext and returns any value\n * @param options - Optional configuration for the function\n *\n * @example\n * ```typescript\n * // Form-level function (default) - may access other fields\n * registry.registerCustomFunction('isAdult', (ctx) => ctx.formValue.age >= 18);\n *\n * // Field-level function - only uses current field value (performance optimization)\n * registry.registerCustomFunction('isEmpty', (ctx) => !ctx.fieldValue, { scope: 'field' });\n * ```\n */\n registerCustomFunction(name: string, fn: CustomFunction, options?: CustomFunctionOptions): void {\n this.customFunctions.set(name, fn);\n // Store scope (default to 'form' for conservative cross-field detection)\n this.customFunctionScopes.set(name, options?.scope ?? 'form');\n }\n\n /**\n * Get the scope of a registered custom function.\n *\n * @param name - The function name\n * @returns The function scope, or undefined if not registered\n */\n getCustomFunctionScope(name: string): CustomFunctionScope | undefined {\n return this.customFunctionScopes.get(name);\n }\n\n /**\n * Check if a custom function is field-scoped (no cross-field dependencies).\n *\n * @param name - The function name\n * @returns true if the function is field-scoped, false if form-scoped or not registered\n */\n isFieldScopedFunction(name: string): boolean {\n return this.customFunctionScopes.get(name) === 'field';\n }\n\n /**\n * Get all custom functions as an object\n */\n getCustomFunctions(): Record<string, CustomFunction> {\n return Object.fromEntries(this.customFunctions);\n }\n\n /**\n * Clear all custom functions and their scopes\n */\n clearCustomFunctions(): void {\n this.customFunctions.clear();\n this.customFunctionScopes.clear();\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Derivation Functions\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Register a derivation function for value derivation logic.\n *\n * Derivation functions compute derived values and are called when a\n * `DerivationLogicConfig` references them by `functionName`.\n *\n * @param name - Unique identifier for the function\n * @param fn - Function that receives EvaluationContext and returns the derived value\n *\n * @example\n * ```typescript\n * registry.registerDerivationFunction('getCurrencyForCountry', (ctx) => {\n * const countryToCurrency = { 'USA': 'USD', 'Germany': 'EUR', 'UK': 'GBP' };\n * return countryToCurrency[ctx.formValue.country] ?? 'USD';\n * });\n * ```\n */\n registerDerivationFunction(name: string, fn: CustomFunction): void {\n this.derivationFunctions.set(name, fn);\n }\n\n /**\n * Get a derivation function by name\n */\n getDerivationFunction(name: string): CustomFunction | undefined {\n return this.derivationFunctions.get(name);\n }\n\n /**\n * Get all derivation functions as an object\n */\n getDerivationFunctions(): Record<string, CustomFunction> {\n return Object.fromEntries(this.derivationFunctions);\n }\n\n /**\n * Set derivation functions from a config object.\n * Only updates functions if their references have changed.\n *\n * @param derivations - Object mapping function names to derivation functions\n */\n setDerivationFunctions(derivations: Record<string, CustomFunction> | undefined): void {\n this.setRegistryIfChanged(this.derivationFunctions, derivations);\n }\n\n /**\n * Clear all derivation functions\n */\n clearDerivationFunctions(): void {\n this.derivationFunctions.clear();\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Async Derivation Functions\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Register an async derivation function.\n *\n * Async derivation functions perform asynchronous operations (service calls,\n * complex pipelines) and return the derived value via a Promise or Observable.\n *\n * @param name - Unique identifier for the function\n * @param fn - Function that receives EvaluationContext and returns Promise/Observable\n */\n registerAsyncDerivationFunction(name: string, fn: AsyncDerivationFunction): void {\n this.asyncDerivationFunctions.set(name, fn);\n }\n\n /**\n * Get an async derivation function by name\n */\n getAsyncDerivationFunction(name: string): AsyncDerivationFunction | undefined {\n return this.asyncDerivationFunctions.get(name);\n }\n\n /**\n * Get all async derivation functions as an object\n */\n getAsyncDerivationFunctions(): Record<string, AsyncDerivationFunction> {\n return Object.fromEntries(this.asyncDerivationFunctions);\n }\n\n /**\n * Set async derivation functions from a config object.\n * Only updates functions if their references have changed.\n *\n * @param fns - Object mapping function names to async derivation functions\n */\n setAsyncDerivationFunctions(fns: Record<string, AsyncDerivationFunction> | undefined): void {\n this.setRegistryIfChanged(this.asyncDerivationFunctions, fns);\n }\n\n /**\n * Clear all async derivation functions\n */\n clearAsyncDerivationFunctions(): void {\n this.asyncDerivationFunctions.clear();\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Async Condition Functions\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Register an async condition function.\n *\n * Async condition functions perform asynchronous operations and return a boolean.\n *\n * @param name - Unique identifier for the function\n * @param fn - Function that receives EvaluationContext and returns Promise/Observable of boolean\n */\n registerAsyncConditionFunction(name: string, fn: AsyncConditionFunction): void {\n this.asyncConditionFunctions.set(name, fn);\n }\n\n /**\n * Get an async condition function by name\n */\n getAsyncConditionFunction(name: string): AsyncConditionFunction | undefined {\n return this.asyncConditionFunctions.get(name);\n }\n\n /**\n * Get all async condition functions as an object\n */\n getAsyncConditionFunctions(): Record<string, AsyncConditionFunction> {\n return Object.fromEntries(this.asyncConditionFunctions);\n }\n\n /**\n * Set async condition functions from a config object.\n * Only updates functions if their references have changed.\n *\n * @param fns - Object mapping function names to async condition functions\n */\n setAsyncConditionFunctions(fns: Record<string, AsyncConditionFunction> | undefined): void {\n this.setRegistryIfChanged(this.asyncConditionFunctions, fns);\n }\n\n /**\n * Clear all async condition functions\n */\n clearAsyncConditionFunctions(): void {\n this.asyncConditionFunctions.clear();\n }\n\n /**\n * Register a custom validator using Angular's public FieldContext API\n *\n * Validators receive the full FieldContext, allowing access to:\n * - Current field value: `ctx.value()`\n * - Field state: `ctx.state` (errors, touched, dirty, etc.)\n * - Other field values: `ctx.valueOf(path)` (public API!)\n * - Other field states: `ctx.stateOf(path)`\n * - Parameters from JSON configuration via second argument\n *\n * @param name - Unique identifier for the validator\n * @param fn - Validator function (ctx, params?) => ValidationError | ValidationError[] | null\n *\n * @example Single Field Validation\n * ```typescript\n * registry.registerValidator('noSpaces', (ctx) => {\n * const value = ctx.value();\n * if (typeof value === 'string' && value.includes(' ')) {\n * return { kind: 'noSpaces' };\n * }\n * return null;\n * });\n * ```\n *\n * @example Cross-Field Validation (Public API)\n * ```typescript\n * registry.registerValidator('lessThan', (ctx, params) => {\n * const value = ctx.value();\n * const compareToPath = params?.field as string;\n *\n * // Use valueOf() to access other fields - public API!\n * const otherValue = ctx.valueOf(compareToPath as any);\n *\n * if (otherValue !== undefined && value >= otherValue) {\n * return { kind: 'notLessThan' };\n * }\n * return null;\n * });\n * ```\n *\n * @example Multiple Errors (Cross-Field Validation)\n * ```typescript\n * registry.registerValidator('validateDateRange', (ctx) => {\n * const errors: ValidationError[] = [];\n * const startDate = ctx.valueOf('startDate' as any);\n * const endDate = ctx.valueOf('endDate' as any);\n *\n * if (!startDate) errors.push({ kind: 'startDateRequired' });\n * if (!endDate) errors.push({ kind: 'endDateRequired' });\n * if (startDate && endDate && startDate > endDate) {\n * errors.push({ kind: 'invalidDateRange' });\n * }\n *\n * return errors.length > 0 ? errors : null;\n * });\n * ```\n */\n registerValidator(name: string, fn: CustomValidator): void {\n this.validators.set(name, fn);\n }\n\n /**\n * Get a validator by name\n */\n getValidator(name: string): CustomValidator | undefined {\n return this.validators.get(name);\n }\n\n /**\n * Clear all validators\n */\n clearValidators(): void {\n this.validators.clear();\n }\n\n /**\n * Register an async validator using Angular's public validateAsync() API\n *\n * Async validators return Observables for asynchronous validation logic.\n * Use for debouncing, database lookups, or complex async business logic.\n *\n * @param name - Unique identifier for the async validator\n * @param fn - Async validator function (ctx, params?) => Observable<ValidationError | ValidationError[] | null>\n *\n * @example Debounced Username Check\n * ```typescript\n * registry.registerAsyncValidator('checkUsernameAvailable', (ctx) => {\n * const username = ctx.value();\n * return of(username).pipe(\n * debounceTime(300),\n * switchMap(name => userService.checkAvailability(name)),\n * map(available => available ? null : { kind: 'usernameTaken' })\n * );\n * });\n * ```\n *\n * @example Async Cross-Field Validation\n * ```typescript\n * registry.registerAsyncValidator('validatePasswordStrength', (ctx) => {\n * const password = ctx.value();\n * const email = ctx.valueOf('email' as any);\n * return passwordService.checkStrength(password, email).pipe(\n * map(result => result.strong ? null : { kind: 'weakPassword' })\n * );\n * });\n * ```\n */\n registerAsyncValidator(name: string, fn: AsyncCustomValidator): void {\n this.asyncValidators.set(name, fn);\n }\n\n /**\n * Get an async validator by name\n */\n getAsyncValidator(name: string): AsyncCustomValidator | undefined {\n return this.asyncValidators.get(name);\n }\n\n /**\n * Clear all async validators\n */\n clearAsyncValidators(): void {\n this.asyncValidators.clear();\n }\n\n /**\n * Register an HTTP validator configuration using Angular's public validateHttp() API\n *\n * HTTP validators provide optimized HTTP validation with automatic request cancellation,\n * caching, and debouncing. Preferred over AsyncCustomValidator for HTTP requests.\n *\n * @param name - Unique identifier for the HTTP validator\n * @param config - HTTP validator configuration object\n *\n * @example Username Availability Check\n * ```typescript\n * registry.registerHttpValidator('checkUsername', {\n * url: (ctx) => `/api/users/check-username?username=${encodeURIComponent(ctx.value())}`,\n * method: 'GET',\n * mapResponse: (response, ctx) => {\n * return response.available ? null : { kind: 'usernameTaken' };\n * }\n * });\n * ```\n *\n * @example POST Request with Body\n * ```typescript\n * registry.registerHttpValidator('validateAddress', {\n * url: '/api/validate-address',\n * method: 'POST',\n * body: (ctx) => ({\n * street: ctx.valueOf('street' as any),\n * city: ctx.valueOf('city' as any),\n * zipCode: ctx.value()\n * }),\n * mapResponse: (response) => {\n * return response.valid ? null : { kind: 'invalidAddress' };\n * },\n * debounceTime: 500\n * });\n * ```\n */\n registerHttpValidator(name: string, config: HttpCustomValidator): void {\n this.httpValidators.set(name, config);\n }\n\n /**\n * Get an HTTP validator by name\n */\n getHttpValidator(name: string): HttpCustomValidator | undefined {\n return this.httpValidators.get(name);\n }\n\n /**\n * Clear all HTTP validators\n */\n clearHttpValidators(): void {\n this.httpValidators.clear();\n }\n\n /**\n * Generic helper to set registry values only if they have changed\n * @param registry - The Map to update\n * @param values - Object mapping keys to values\n */\n private setRegistryIfChanged<T>(registry: Map<string, T>, values: Record<string, T> | undefined): void {\n if (!values) return;\n\n const entries = Object.entries(values);\n const hasChanges = entries.some(([name, value]) => registry.get(name) !== value);\n\n if (hasChanges) {\n entries.forEach(([name, value]) => registry.set(name, value));\n }\n }\n\n /**\n * Set validators from a config object\n * Only updates validators if their references have changed\n *\n * @param validators - Object mapping validator names to validator functions\n */\n setValidators(validators: Record<string, CustomValidator> | undefined): void {\n this.setRegistryIfChanged(this.validators, validators);\n }\n\n /**\n * Set async validators from a config object\n * Only updates validators if their references have changed\n *\n * @param asyncValidators - Object mapping validator names to async validator configs\n */\n setAsyncValidators(asyncValidators: Record<string, AsyncCustomValidator> | undefined): void {\n this.setRegistryIfChanged(this.asyncValidators, asyncValidators);\n }\n\n /**\n * Set HTTP validators from a config object\n * Only updates validators if their references have changed\n *\n * @param httpValidators - Object mapping validator names to HTTP validator configs\n */\n setHttpValidators(httpValidators: Record<string, HttpCustomValidator> | undefined): void {\n this.setRegistryIfChanged(this.httpValidators, httpValidators);\n }\n\n /**\n * Clear everything (functions and all validators)\n */\n clearAll(): void {\n this.clearCustomFunctions();\n this.clearDerivationFunctions();\n this.clearAsyncDerivationFunctions();\n this.clearAsyncConditionFunctions();\n this.clearValidators();\n this.clearAsyncValidators();\n this.clearHttpValidators();\n }\n}\n","import { Injectable } from '@angular/core';\nimport { SchemaDefinition } from '../../models/schemas/schema-definition';\n\n@Injectable()\nexport class SchemaRegistryService {\n private readonly registeredSchemas = new Map<string, SchemaDefinition>();\n\n /**\n * Register a reusable schema\n */\n registerSchema(schema: SchemaDefinition): void {\n this.registeredSchemas.set(schema.name, schema);\n }\n\n /**\n * Get registered schema by name\n */\n getSchema(name: string): SchemaDefinition | undefined {\n return this.registeredSchemas.get(name);\n }\n\n /**\n * Get all registered schemas\n */\n getAllSchemas(): Map<string, SchemaDefinition> {\n return new Map(this.registeredSchemas);\n }\n\n /**\n * Clear all registered schemas\n */\n clearSchemas(): void {\n this.registeredSchemas.clear();\n }\n\n /**\n * Resolve schema from string reference or direct definition\n */\n resolveSchema(schema: string | SchemaDefinition): SchemaDefinition | null {\n if (typeof schema === 'string') {\n return this.getSchema(schema) || null;\n }\n return schema;\n }\n}\n","import { InjectionToken } from '@angular/core';\n\n/**\n * Tracks deprecated API usages that have already been warned about to prevent log spam.\n * Scoped to a single form instance via DI.\n *\n * This follows the same pattern as DerivationWarningTracker — DI-scoped rather than\n * module-scoped to avoid SSR issues where state would be shared across requests.\n *\n * @public\n */\nexport interface DeprecationWarningTracker {\n /** Set of deprecation keys we've already warned about */\n warnedKeys: Set<string>;\n}\n\n/**\n * Injection token for the deprecation warning tracker.\n * Provided at form component level for instance-scoped tracking.\n *\n * @public\n */\nexport const DEPRECATION_WARNING_TRACKER = new InjectionToken<DeprecationWarningTracker>('DeprecationWarningTracker');\n\n/**\n * Creates a fresh deprecation warning tracker instance.\n *\n * @returns A new DeprecationWarningTracker with an empty warnedKeys Set\n *\n * @public\n */\nexport function createDeprecationWarningTracker(): DeprecationWarningTracker {\n return { warnedKeys: new Set<string>() };\n}\n","/**\n * Compares two values using the specified comparison operator.\n *\n * Supports various comparison types including equality, numerical comparisons,\n * string operations, and regular expression matching. Type coercion is applied\n * for numerical and string operations as needed.\n *\n * @param actual - The value to compare\n * @param expected - The value to compare against\n * @param operator - Comparison operator to use\n * @returns True if the comparison succeeds, false otherwise\n *\n * @example\n * ```typescript\n * // Equality checks\n * compareValues(10, 10, 'equals') // true\n * compareValues('test', 'other', 'notEquals') // true\n *\n * // Numerical comparisons\n * compareValues(15, 10, 'greater') // true\n * compareValues('5', 3, 'greaterOrEqual') // true (coerced to numbers)\n *\n * // String operations\n * compareValues('hello world', 'world', 'contains') // true\n * compareValues('prefix-test', 'prefix', 'startsWith') // true\n * compareValues('test.jpg', '.jpg', 'endsWith') // true\n *\n * // Regular expression matching\n * compareValues('test123', '^test\\\\d+$', 'matches') // true\n * compareValues('invalid', '[invalid', 'matches') // false (invalid regex)\n * ```\n */\nexport function compareValues(actual: unknown, expected: unknown, operator: string): boolean {\n switch (operator) {\n case 'equals':\n return actual === expected;\n case 'notEquals':\n return actual !== expected;\n case 'greater':\n return Number(actual) > Number(expected);\n case 'less':\n return Number(actual) < Number(expected);\n case 'greaterOrEqual':\n return Number(actual) >= Number(expected);\n case 'lessOrEqual':\n return Number(actual) <= Number(expected);\n case 'contains':\n return String(actual).includes(String(expected));\n case 'startsWith':\n return String(actual).startsWith(String(expected));\n case 'endsWith':\n return String(actual).endsWith(String(expected));\n case 'matches':\n try {\n return new RegExp(String(expected)).test(String(actual));\n } catch {\n return false;\n }\n default:\n return false;\n }\n}\n\n/**\n * Retrieves a nested value from an object using dot notation path.\n *\n * Safely traverses object properties using a dot-separated path string.\n * Returns undefined if any part of the path is missing or if the traversal\n * encounters a non-object value.\n *\n * @param obj - The object to traverse\n * @param path - Dot-separated path to the desired property\n * @returns The value at the specified path, or undefined if not found\n *\n * @example\n * ```typescript\n * const data = {\n * user: {\n * profile: {\n * name: 'John',\n * age: 30\n * },\n * settings: { theme: 'dark' }\n * }\n * };\n *\n * getNestedValue(data, 'user.profile.name') // 'John'\n * getNestedValue(data, 'user.settings.theme') // 'dark'\n * getNestedValue(data, 'user.profile.email') // undefined\n * getNestedValue(data, 'nonexistent.path') // undefined\n * getNestedValue(null, 'any.path') // undefined\n * ```\n */\nexport function getNestedValue(obj: unknown, path: string): unknown {\n return path.split('.').reduce((current: unknown, key: string) => {\n return current && typeof current === 'object' ? (current as Record<string, unknown>)[key] : undefined;\n }, obj);\n}\n\n/**\n * Checks whether a nested property exists in an object using dot notation path.\n *\n * Unlike `getNestedValue`, this distinguishes between a property that exists\n * with value `undefined` and a property path that doesn't exist at all.\n *\n * @param obj - The object to check\n * @param path - Dot-separated path to the property\n * @returns True if the property exists (even if its value is undefined)\n */\nexport function hasNestedProperty(obj: unknown, path: string): boolean {\n const keys = path.split('.');\n let current: unknown = obj;\n\n for (let i = 0; i < keys.length - 1; i++) {\n if (!current || typeof current !== 'object') return false;\n current = (current as Record<string, unknown>)[keys[i]];\n }\n\n if (!current || typeof current !== 'object') return false;\n return keys[keys.length - 1] in (current as Record<string, unknown>);\n}\n","import { type Signal, isSignal, untracked } from '@angular/core';\nimport type { FieldState, FieldTree } from '@angular/forms/signals';\nimport type { FieldStateInfo, FormFieldStateMap } from '../../models/expressions/field-state-context';\nimport type { FieldTreeRecord } from '../field-tree-utils';\n\n/**\n * Known state properties on an Angular Signal Forms FieldState.\n * Each is a Signal<boolean> on the FieldState interface.\n */\nconst STATE_PROPERTIES = ['touched', 'dirty', 'valid', 'invalid', 'pending', 'hidden', 'readonly', 'disabled'] as const;\n\ntype StateProperty = (typeof STATE_PROPERTIES)[number];\n\n/**\n * Reads a boolean signal from a FieldState, respecting the reactive flag.\n *\n * @internal\n */\nfunction readStateSignal(fieldState: FieldState<unknown>, prop: StateProperty, reactive: boolean): boolean {\n const signalFn: Signal<boolean> | undefined = fieldState[prop];\n if (!signalFn || !isSignal(signalFn)) return false;\n return reactive ? !!signalFn() : !!untracked(signalFn);\n}\n\n/**\n * Resolves a field source (FieldTree or FieldState) to its FieldState.\n *\n * Accepts either:\n * - A FieldTree (signal or callable Proxy from form tree) — called to get the FieldState\n * - A direct FieldState object (from FieldContext) — used directly\n *\n * FieldTree accessors may be Angular signals (pass `isSignal()`) or Proxy-wrapped\n * callables (fail `isSignal()` but pass `typeof === 'function'`). Both are handled\n * by the callable check.\n *\n * @internal\n */\nfunction resolveFieldState(\n fieldSource: FieldTree<unknown> | FieldState<unknown> | undefined,\n reactive: boolean,\n): FieldState<unknown> | undefined {\n if (!fieldSource) return undefined;\n\n // FieldTree: signal or callable Proxy — invoke to get the FieldState\n if (typeof fieldSource === 'function') {\n return reactive ? (fieldSource as FieldTree<unknown>)() : untracked(fieldSource as FieldTree<unknown>);\n }\n\n // Direct FieldState object (from FieldContext)\n if (typeof fieldSource === 'object') {\n return fieldSource as FieldState<unknown>;\n }\n\n return undefined;\n}\n\n/**\n * Creates a lazy FieldStateInfo that only reads state properties when accessed.\n *\n * This prevents reactive cycles when fieldState/formFieldState is used inside\n * logic conditions (readonly, hidden, disabled). Eagerly reading all properties\n * (e.g., `valid`, `readonly`) would create circular dependencies when the\n * logic condition itself controls one of those properties.\n *\n * Accepts either:\n * - A FieldTree (signal accessor from form tree) — called to get the FieldState\n * - A direct FieldState object (from FieldContext) — used directly\n *\n * @param fieldSource - A FieldTree or direct FieldState instance\n * @param reactive - If true, reads signals reactively (creates dependencies).\n * If false, reads signals with `untracked()` (no dependencies).\n * @returns A FieldStateInfo proxy with lazy property access, or undefined if the source is invalid\n *\n * @internal\n */\nexport function readFieldStateInfo(\n fieldSource: FieldTree<unknown> | FieldState<unknown> | undefined,\n reactive: boolean,\n): FieldStateInfo | undefined {\n const state = resolveFieldState(fieldSource, reactive);\n if (!state || typeof state !== 'object') return undefined;\n\n const knownProperties = new Set<string>([...STATE_PROPERTIES, 'pristine']);\n\n return new Proxy({} as FieldStateInfo, {\n get(_target, prop: string): boolean {\n if (prop === 'pristine') {\n return !readStateSignal(state, 'dirty', reactive);\n }\n if (STATE_PROPERTIES.includes(prop as StateProperty)) {\n return readStateSignal(state, prop as StateProperty, reactive);\n }\n return false;\n },\n has(_target, prop: string): boolean {\n return knownProperties.has(prop);\n },\n });\n}\n\n/**\n * Creates a Proxy-based FormFieldStateMap for accessing any field's state by key.\n *\n * Property access like `[key]` navigates to `rootForm[key]` and returns\n * a FieldStateInfo snapshot for that field.\n *\n * Uses an internal Map cache for identity stability within a single\n * access chain (avoids redundant snapshot allocations).\n *\n * @param rootForm - The root FieldTree of the form\n * @param reactive - If true, reads signals reactively (creates dependencies).\n * If false, reads signals with `untracked()` (no dependencies).\n * @returns A FormFieldStateMap proxy\n *\n * @internal\n */\nexport function createFormFieldStateMap(rootForm: FieldTree<unknown>, reactive: boolean): FormFieldStateMap {\n const cache = new Map<string, FieldStateInfo | undefined>();\n\n return new Proxy({} as FormFieldStateMap, {\n get(_target, key: string): FieldStateInfo | undefined {\n if (cache.has(key)) {\n return cache.get(key);\n }\n\n const fieldAccessor = navigateToFieldAccessor(rootForm, key);\n const snapshot = readFieldStateInfo(fieldAccessor, reactive);\n cache.set(key, snapshot);\n return snapshot;\n },\n has(_target, key: string): boolean {\n return navigateToFieldAccessor(rootForm, key) !== undefined;\n },\n });\n}\n\n/**\n * Navigates the form tree to find a field accessor (FieldTree) for the given key path.\n *\n * Supports dot-notation for nested paths (e.g., 'address.city').\n * Follows the same bracket-notation navigation pattern as `applyValueToForm`\n * in `derivation-applicator.ts`.\n *\n * @internal\n */\nfunction navigateToFieldAccessor(rootForm: FieldTree<unknown>, keyPath: string): FieldTree<unknown> | undefined {\n if (!keyPath) return undefined;\n\n const parts = keyPath.split('.');\n // FieldTree<T> = (() => FieldState<T>) & Subfields<T>, so sub-fields\n // are directly on the FieldTree — no need to call it during navigation\n let current = rootForm as FieldTreeRecord;\n\n for (let i = 0; i < parts.length - 1; i++) {\n const next = current[parts[i]];\n if (!next) return undefined;\n current = next as FieldTreeRecord;\n }\n\n return current[parts[parts.length - 1]];\n}\n","import { untracked } from '@angular/core';\nimport { FieldContext } from '@angular/forms/signals';\n\n/**\n * Safely reads `pathKeys` from a FieldContext.\n * Returns an empty array if `pathKeys` is not available (e.g., in tests or older Angular versions).\n *\n * Always reads with `untracked()` because `pathKeys` is stable for the lifetime of a field —\n * array items don't change index after creation, so there's no need to establish a reactive\n * dependency on this signal.\n */\nexport function safeReadPathKeys(fieldContext: FieldContext<unknown>): readonly string[] {\n if (!('pathKeys' in fieldContext) || typeof fieldContext.pathKeys !== 'function') {\n return [];\n }\n return untracked(() => fieldContext.pathKeys());\n}\n","import { inject, Injectable, isSignal, Signal, untracked } from '@angular/core';\nimport { ChildFieldContext, FieldContext, FieldState, FieldTree } from '@angular/forms/signals';\nimport { EvaluationContext } from '../../models/expressions/evaluation-context';\nimport { EXTERNAL_DATA } from '../../models/field-signal-context.token';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\nimport { RootFormRegistryService } from './root-form-registry.service';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { DEPRECATION_WARNING_TRACKER } from '../../utils/deprecation-warning-tracker';\nimport { getNestedValue } from '../expressions/value-utils';\nimport { readFieldStateInfo, createFormFieldStateMap } from '../derivation/field-state-extractor';\nimport { safeReadPathKeys } from '../../utils/safe-read-path-keys';\n\nfunction isChildFieldContext<TValue>(context: FieldContext<TValue>): context is ChildFieldContext<TValue> {\n return 'key' in context && isSignal(context.key);\n}\n\n/**\n * Extracts the FieldState from a FieldContext using the public `.state` property.\n *\n * FieldContext.state is a FieldState object that has all signal properties\n * (dirty, touched, valid, etc.) needed for field state snapshots.\n *\n * IMPORTANT: Always reads with `untracked()` because accessing `.state` on a\n * FieldContext can trigger reactive reads inside Angular's internal computation\n * graph. Without `untracked()`, validators would cycle (validator → state → valid\n * → validator) and logic conditions like `hidden()` would cycle (hidden → state →\n * hidden). The FieldState object reference is stable — individual signal properties\n * within it are read reactively or untracked by the Proxy as needed.\n */\nfunction extractFieldState(fieldContext: FieldContext<unknown>): FieldState<unknown> | undefined {\n return untracked(() => {\n if (!fieldContext || !('state' in fieldContext)) return undefined;\n return fieldContext.state;\n });\n}\n\n/**\n * Detects whether a field lives inside an array by examining its `pathKeys`.\n *\n * Array item fields have paths like `['addresses', '0', 'street']` where\n * a numeric segment indicates an array index. Returns the array key and\n * numeric index when detected, or `undefined` for non-array fields.\n *\n * For nested arrays (e.g., `['orders', '0', 'items', '1', 'name']`), walks backwards\n * to find the innermost array context — scoping `formValue` to that item.\n * `localKey` is always the last segment (the field's own key within its parent item).\n */\nfunction detectArrayScope(pathKeys: readonly string[]): { arrayKey: string; index: number; localKey: string } | undefined {\n // Need at least 3 segments: arrayKey, index, fieldKey\n if (pathKeys.length < 3) return undefined;\n\n // Walk from the end to find the nearest array context.\n // pathKeys looks like ['addresses', '0', 'street'] or\n // ['nested', 'addresses', '1', 'city']\n for (let i = pathKeys.length - 2; i >= 1; i--) {\n const maybeIndex = Number(pathKeys[i]);\n if (Number.isInteger(maybeIndex) && maybeIndex >= 0) {\n return {\n arrayKey: pathKeys.slice(0, i).join('.'),\n index: maybeIndex,\n localKey: pathKeys[pathKeys.length - 1],\n };\n }\n }\n\n return undefined;\n}\n\n/**\n * Service that provides field evaluation context by combining\n * field context with root form registry information.\n *\n * This service should be provided at the component level to ensure proper\n * isolation between different form instances.\n */\n@Injectable()\nexport class FieldContextRegistryService {\n private rootFormRegistry = inject(RootFormRegistryService);\n private logger = inject(DynamicFormLogger);\n private deprecationTracker = inject(DEPRECATION_WARNING_TRACKER, { optional: true });\n private externalDataSignal = inject(EXTERNAL_DATA, { optional: true });\n\n /**\n * Creates an evaluation context for a field by combining:\n * - The field's current value\n * - The root form value from the registry\n * - The field path (if available from form context)\n * - Custom functions (if provided)\n */\n createEvaluationContext<TValue>(\n fieldContext: FieldContext<TValue>,\n customFunctions?: Record<string, (context: EvaluationContext) => unknown>,\n ): EvaluationContext {\n // Use untracked() to read the field value WITHOUT creating a reactive dependency.\n // This prevents infinite loops when logic functions are evaluated inside computed signals.\n const fieldValue = untracked(() => fieldContext.value());\n\n // Get form value wrapped in untracked() to prevent reactive dependencies.\n // This allows validators and dynamic values to access form values without\n // causing infinite loops.\n const rootFormValue = untracked(() => this.rootFormRegistry.formValue());\n const localKey = this.extractFieldPath(fieldContext);\n const pathKeys = safeReadPathKeys(fieldContext);\n const arrayScope = detectArrayScope(pathKeys);\n\n if (arrayScope) {\n return this.buildArrayScopedContext(rootFormValue, arrayScope, fieldValue, customFunctions, false, fieldContext);\n }\n\n // Use getters for fieldState/formFieldState to defer signal reads until\n // the expression actually accesses them. Validators that only use fieldValue\n // will never trigger these getters, avoiding reactive cycles in Angular's\n // internal signal graph (validator → state → valid → validator).\n const rootFormSignal = this.rootFormRegistry.rootForm;\n return {\n fieldValue,\n formValue: rootFormValue,\n fieldPath: localKey,\n customFunctions: customFunctions || {},\n externalData: this.resolveExternalData(false),\n logger: this.logger,\n deprecationTracker: this.deprecationTracker ?? undefined,\n get fieldState() {\n return readFieldStateInfo(extractFieldState(fieldContext), false);\n },\n get formFieldState() {\n return createFormFieldStateMap(untracked(rootFormSignal) as FieldTree<unknown>, false);\n },\n };\n }\n\n /**\n * Extracts the field path (key) for a given field context.\n */\n private extractFieldPath(fieldContext: FieldContext<unknown>): string {\n if (isChildFieldContext(fieldContext)) {\n try {\n return String(fieldContext.key());\n } catch (error) {\n this.logger.warn('Unable to extract field key:', error);\n }\n }\n\n // For root fields or when key is not available\n return '';\n }\n\n /**\n * Builds an evaluation context scoped to a specific array item.\n *\n * When a field lives inside an array (e.g., `addresses.0.street`), its logic conditions\n * need `formValue` scoped to the array item so that `fieldValue` lookups like\n * `hasApartment` resolve against the item rather than the root form.\n *\n * Falls back to root form behavior when the array data is missing or the index is\n * out of bounds.\n */\n private buildArrayScopedContext<TValue>(\n rootFormValue: Record<string, unknown>,\n arrayScope: { arrayKey: string; index: number; localKey: string },\n fieldValue: TValue,\n customFunctions: Record<string, (context: EvaluationContext) => unknown> | undefined,\n reactive: boolean,\n fieldContext?: FieldContext<unknown>,\n ): EvaluationContext {\n const { arrayKey, index, localKey } = arrayScope;\n\n // Navigate to the array (supports nested paths like 'nested.addresses')\n const arrayData = getNestedValue(rootFormValue, arrayKey);\n let scopedFormValue: Record<string, unknown> | undefined;\n\n if (Array.isArray(arrayData) && index >= 0 && index < arrayData.length) {\n const item = arrayData[index];\n if (item != null && typeof item === 'object') {\n scopedFormValue = item as Record<string, unknown>;\n }\n }\n\n // Use getters to defer fieldState/formFieldState construction.\n // Same rationale as createEvaluationContext — avoids reactive cycles\n // when expressions don't actually access these properties.\n const rootFormSignal = this.rootFormRegistry.rootForm;\n const fieldStateGetter = fieldContext ? () => readFieldStateInfo(extractFieldState(fieldContext), reactive) : () => undefined;\n const formFieldStateGetter = () =>\n createFormFieldStateMap((reactive ? rootFormSignal() : untracked(rootFormSignal)) as FieldTree<unknown>, reactive);\n\n // Fall back to root form value if array item lookup fails\n if (!scopedFormValue) {\n return {\n fieldValue,\n formValue: rootFormValue,\n fieldPath: localKey,\n customFunctions: customFunctions || {},\n externalData: this.resolveExternalData(reactive),\n logger: this.logger,\n deprecationTracker: this.deprecationTracker ?? undefined,\n get fieldState() {\n return fieldStateGetter();\n },\n get formFieldState() {\n return formFieldStateGetter();\n },\n };\n }\n\n return {\n fieldValue,\n formValue: scopedFormValue,\n rootFormValue,\n arrayIndex: index,\n arrayPath: arrayKey,\n fieldPath: `${arrayKey}.${index}.${localKey}`,\n customFunctions: customFunctions || {},\n externalData: this.resolveExternalData(reactive),\n logger: this.logger,\n deprecationTracker: this.deprecationTracker ?? undefined,\n get fieldState() {\n return fieldStateGetter();\n },\n get formFieldState() {\n return formFieldStateGetter();\n },\n };\n }\n\n /**\n * Resolves external data signals to their current values.\n *\n * @param reactive - If true, reads signals reactively (creates dependencies).\n * If false, reads signals with untracked() (no dependencies).\n * @returns Record of resolved external data values, or undefined if no external data.\n */\n private resolveExternalData(reactive: boolean): Record<string, unknown> | undefined {\n const externalDataSignal = this.externalDataSignal;\n if (!externalDataSignal) return undefined;\n\n const externalDataRecord = reactive ? externalDataSignal() : untracked(() => externalDataSignal());\n\n if (!externalDataRecord) {\n return undefined;\n }\n\n const resolved: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(externalDataRecord)) {\n if (!isSignal(value)) {\n throw new DynamicFormError(`externalData[\"${key}\"] must be a Signal. Got: ${typeof value}. Wrap it with signal(yourValue).`);\n }\n resolved[key] = reactive ? (value as Signal<unknown>)() : untracked(() => (value as Signal<unknown>)());\n }\n\n return resolved;\n }\n\n /**\n * Creates a REACTIVE evaluation context for logic functions.\n *\n * Unlike createEvaluationContext, this method does NOT use untracked(),\n * which allows logic functions (hidden, readonly, disabled, required) to\n * create reactive dependencies on form values.\n *\n * When a dependent field value changes, the logic function will be re-evaluated.\n *\n * NOTE: This should ONLY be used for logic functions, not validators.\n * Validators should use createEvaluationContext with untracked() to prevent\n * infinite reactive loops. Validators with cross-field dependencies should be\n * hoisted to form-level using validateTree.\n */\n createReactiveEvaluationContext<TValue>(\n fieldContext: FieldContext<TValue>,\n customFunctions?: Record<string, (context: EvaluationContext) => unknown>,\n ): EvaluationContext {\n const fieldValue = fieldContext.value();\n const rootFormValue = this.rootFormRegistry.formValue();\n const pathKeys = safeReadPathKeys(fieldContext);\n const arrayScope = detectArrayScope(pathKeys);\n\n if (arrayScope) {\n return this.buildArrayScopedContext(rootFormValue, arrayScope, fieldValue, customFunctions, true, fieldContext);\n }\n\n const localKey = this.extractFieldPath(fieldContext);\n const rootFormSignal = this.rootFormRegistry.rootForm;\n\n return {\n fieldValue,\n formValue: rootFormValue,\n fieldPath: localKey,\n customFunctions: customFunctions || {},\n externalData: this.resolveExternalData(true),\n logger: this.logger,\n deprecationTracker: this.deprecationTracker ?? undefined,\n get fieldState() {\n return readFieldStateInfo(extractFieldState(fieldContext), true);\n },\n get formFieldState() {\n return createFormFieldStateMap(rootFormSignal() as FieldTree<unknown>, true);\n },\n };\n }\n\n /**\n * Creates an evaluation context for display-only components (text fields, pages)\n * that don't have their own FieldContext.\n *\n * This is useful for:\n * - Text fields (display-only, not part of form schema)\n * - Pages (containers that need to evaluate visibility logic)\n *\n * Uses reactive form value access to allow logic re-evaluation when form values change.\n *\n * NOTE: This method does NOT support array-scoped context because display-only\n * components don't have a FieldContext (and therefore no `pathKeys` signal to\n * detect array scope from). If display-only components are placed inside arrays,\n * their logic conditions will evaluate against the root form value.\n *\n * @param fieldPath - The key/path of the display-only component\n * @param customFunctions - Optional custom functions for expression evaluation\n */\n createDisplayOnlyContext(\n fieldPath: string,\n customFunctions?: Record<string, (context: EvaluationContext) => unknown>,\n ): EvaluationContext {\n const formValue = this.rootFormRegistry.formValue();\n const rootFormSignal = this.rootFormRegistry.rootForm;\n\n return {\n fieldValue: undefined,\n formValue,\n fieldPath,\n customFunctions: customFunctions || {},\n externalData: this.resolveExternalData(true),\n logger: this.logger,\n deprecationTracker: this.deprecationTracker ?? undefined,\n get formFieldState() {\n return createFormFieldStateMap(rootFormSignal() as FieldTree<unknown>, true);\n },\n };\n }\n}\n","/**\n * Utilities for parsing and manipulating field paths in dynamic forms.\n *\n * Field paths follow these formats:\n * - Simple: \"fieldName\"\n * - Nested: \"parent.child.grandchild\"\n * - Array indexed: \"items.0.quantity\" or \"items[0].quantity\"\n * - Array placeholder: \"items.$.quantity\" ($ = any index)\n *\n * @module path-utils\n */\n\n/**\n * Result of parsing an array derivation path.\n *\n * @public\n */\nexport interface ArrayPathInfo {\n /** The array field path (e.g., \"items\" or \"orders.lineItems\") */\n arrayPath: string;\n\n /** The relative field path within the array item (e.g., \"quantity\" or \"lineTotal\") */\n relativePath: string;\n\n /** Whether this is a valid array path (contains .$. separator) */\n isArrayPath: boolean;\n}\n\n/**\n * Parses an array derivation path into its components.\n *\n * Array paths use the `$` placeholder to represent \"any index\".\n * Format: \"arrayPath.$.relativePath\"\n *\n * @param path - The path to parse (e.g., \"items.$.quantity\")\n * @returns Parsed path info with arrayPath and relativePath\n *\n * @example\n * ```typescript\n * parseArrayPath('items.$.quantity')\n * // { arrayPath: 'items', relativePath: 'quantity', isArrayPath: true }\n *\n * parseArrayPath('orders.lineItems.$.total')\n * // { arrayPath: 'orders.lineItems', relativePath: 'total', isArrayPath: true }\n *\n * parseArrayPath('simpleField')\n * // { arrayPath: '', relativePath: '', isArrayPath: false }\n * ```\n *\n * @public\n */\nexport function parseArrayPath(path: string): ArrayPathInfo {\n const ARRAY_PLACEHOLDER = '.$.';\n const placeholderIndex = path.indexOf(ARRAY_PLACEHOLDER);\n\n if (placeholderIndex === -1) {\n return {\n arrayPath: '',\n relativePath: '',\n isArrayPath: false,\n };\n }\n\n return {\n arrayPath: path.substring(0, placeholderIndex),\n relativePath: path.substring(placeholderIndex + ARRAY_PLACEHOLDER.length),\n isArrayPath: true,\n };\n}\n\n/**\n * Resolves an array placeholder path to a concrete indexed path.\n *\n * @param path - The path with $ placeholder (e.g., \"items.$.quantity\")\n * @param index - The array index to substitute\n * @returns Resolved path with index (e.g., \"items.0.quantity\")\n *\n * @example\n * ```typescript\n * resolveArrayPath('items.$.quantity', 2)\n * // 'items.2.quantity'\n *\n * resolveArrayPath('orders.lineItems.$.total', 0)\n * // 'orders.lineItems.0.total'\n * ```\n *\n * @public\n */\nexport function resolveArrayPath(path: string, index: number): string {\n const info = parseArrayPath(path);\n if (!info.isArrayPath) {\n return path;\n }\n return `${info.arrayPath}.${index}.${info.relativePath}`;\n}\n\n/**\n * Checks if a path contains an array placeholder.\n *\n * @param path - The path to check\n * @returns True if the path contains .$.\n *\n * @public\n */\nexport function isArrayPlaceholderPath(path: string): boolean {\n return path.includes('.$.');\n}\n\n/**\n * Extracts the array path from a path that may contain an array placeholder.\n *\n * @param path - The path to extract from\n * @returns The array path, or empty string if not an array path\n *\n * @example\n * ```typescript\n * extractArrayPath('items.$.quantity')\n * // 'items'\n *\n * extractArrayPath('orders.lineItems.$.total')\n * // 'orders.lineItems'\n *\n * extractArrayPath('simpleField')\n * // ''\n * ```\n *\n * @public\n */\nexport function extractArrayPath(path: string): string {\n return parseArrayPath(path).arrayPath;\n}\n\n/**\n * Splits a path into segments, supporting both dot notation and bracket notation.\n *\n * Handles:\n * - Dot notation: `parent.child.grandchild`\n * - Bracket notation: `items[0].quantity`\n * - Mixed notation: `items[0].address.city`\n *\n * @param path - The path to split\n * @returns Array of path segments\n *\n * @example\n * ```typescript\n * splitPath('parent.child.grandchild')\n * // ['parent', 'child', 'grandchild']\n *\n * splitPath('items.0.quantity')\n * // ['items', '0', 'quantity']\n *\n * splitPath('items[0].quantity')\n * // ['items', '0', 'quantity']\n *\n * splitPath('a[0][1].b')\n * // ['a', '0', '1', 'b']\n * ```\n *\n * @public\n */\nexport function splitPath(path: string): string[] {\n if (!path) return [];\n // Convert bracket notation [n] to .n, then split by dots\n // Filter out empty segments from leading/trailing/consecutive dots\n return path\n .replace(/\\[(\\d+)\\]/g, '.$1')\n .split('.')\n .filter(Boolean);\n}\n\n/**\n * Joins path segments into a dot-separated path.\n *\n * @param segments - The path segments to join\n * @returns Joined path string\n *\n * @public\n */\nexport function joinPath(segments: string[]): string {\n return segments.join('.');\n}\n\n/**\n * Gets the parent path from a nested path.\n *\n * @param path - The path to get parent from\n * @returns The parent path, or empty string if no parent\n *\n * @example\n * ```typescript\n * getParentPath('parent.child.grandchild')\n * // 'parent.child'\n *\n * getParentPath('topLevel')\n * // ''\n * ```\n *\n * @public\n */\nexport function getParentPath(path: string): string {\n const segments = splitPath(path);\n if (segments.length <= 1) return '';\n return joinPath(segments.slice(0, -1));\n}\n\n/**\n * Gets the last segment (leaf) from a path.\n *\n * @param path - The path to get leaf from\n * @returns The last segment\n *\n * @example\n * ```typescript\n * getLeafPath('parent.child.grandchild')\n * // 'grandchild'\n *\n * getLeafPath('topLevel')\n * // 'topLevel'\n * ```\n *\n * @public\n */\nexport function getLeafPath(path: string): string {\n const segments = splitPath(path);\n return segments[segments.length - 1] ?? '';\n}\n\n// ============================================================================\n// Multi-Array Path Utilities\n// ============================================================================\n\n/**\n * Result of parsing a path with multiple array placeholders.\n *\n * @public\n */\nexport interface MultiArrayPathInfo {\n /** Whether this path contains array placeholders */\n isArrayPath: boolean;\n\n /** Number of array placeholders in the path */\n placeholderCount: number;\n\n /** Path segments (excluding $ placeholders) */\n segments: string[];\n\n /** The positions of '$' in the split path (by part index) */\n placeholderPositions: number[];\n}\n\n/**\n * Parses a path that may contain multiple array placeholders.\n *\n * This supports deeply nested array structures like `orders.$.items.$.quantity`\n * where multiple levels of arrays need to be traversed.\n *\n * @param path - Path with zero or more $ placeholders\n * @returns Parsed path information\n *\n * @example\n * ```typescript\n * parseMultiArrayPath('orders.$.items.$.quantity')\n * // {\n * // isArrayPath: true,\n * // placeholderCount: 2,\n * // segments: ['orders', 'items', 'quantity'],\n * // placeholderPositions: [1, 3]\n * // }\n *\n * parseMultiArrayPath('items.$.name')\n * // {\n * // isArrayPath: true,\n * // placeholderCount: 1,\n * // segments: ['items', 'name'],\n * // placeholderPositions: [1]\n * // }\n *\n * parseMultiArrayPath('simpleField')\n * // {\n * // isArrayPath: false,\n * // placeholderCount: 0,\n * // segments: ['simpleField'],\n * // placeholderPositions: []\n * // }\n * ```\n *\n * @public\n */\nexport function parseMultiArrayPath(path: string): MultiArrayPathInfo {\n const parts = path.split('.');\n const segments: string[] = [];\n const placeholderPositions: number[] = [];\n\n for (let i = 0; i < parts.length; i++) {\n if (parts[i] === '$') {\n placeholderPositions.push(i);\n } else {\n segments.push(parts[i]);\n }\n }\n\n return {\n isArrayPath: placeholderPositions.length > 0,\n placeholderCount: placeholderPositions.length,\n segments,\n placeholderPositions,\n };\n}\n\n/**\n * Resolves a path with multiple array placeholders using provided indices.\n *\n * Each `$` placeholder is replaced with the corresponding index from the\n * indices array, in order.\n *\n * @param path - Path with $ placeholders (e.g., 'orders.$.items.$.quantity')\n * @param indices - Array of indices to substitute (e.g., [0, 2])\n * @returns Resolved path (e.g., 'orders.0.items.2.quantity')\n *\n * @throws Error if number of indices doesn't match number of placeholders\n *\n * @example\n * ```typescript\n * resolveMultiArrayPath('orders.$.items.$.quantity', [0, 2])\n * // 'orders.0.items.2.quantity'\n *\n * resolveMultiArrayPath('items.$.name', [5])\n * // 'items.5.name'\n * ```\n *\n * @public\n */\nexport function resolveMultiArrayPath(path: string, indices: number[]): string {\n const parts = path.split('.');\n let indexPointer = 0;\n\n const resolved = parts.map((part) => {\n if (part === '$') {\n if (indexPointer >= indices.length) {\n throw new Error(\n `Not enough indices provided for path '${path}'. ` +\n `Expected ${parts.filter((p) => p === '$').length} indices, got ${indices.length}.`,\n );\n }\n return String(indices[indexPointer++]);\n }\n return part;\n });\n\n if (indexPointer < indices.length) {\n throw new Error(`Too many indices provided for path '${path}'. ` + `Expected ${indexPointer} indices, got ${indices.length}.`);\n }\n\n return resolved.join('.');\n}\n\n/**\n * Counts the number of array placeholders in a path.\n *\n * @param path - The path to analyze\n * @returns Number of $ placeholders in the path\n *\n * @example\n * ```typescript\n * countArrayPlaceholders('orders.$.items.$.quantity')\n * // 2\n *\n * countArrayPlaceholders('items.$.name')\n * // 1\n *\n * countArrayPlaceholders('simpleField')\n * // 0\n * ```\n *\n * @public\n */\nexport function countArrayPlaceholders(path: string): number {\n return path.split('.').filter((part) => part === '$').length;\n}\n","import { DynamicFormError } from '../../../errors/dynamic-form-error';\n\n/**\n * Token types for expression parsing\n */\nexport enum TokenType {\n // Literals\n NUMBER = 'NUMBER',\n STRING = 'STRING',\n TRUE = 'TRUE',\n FALSE = 'FALSE',\n NULL = 'NULL',\n UNDEFINED = 'UNDEFINED',\n\n // Identifiers\n IDENTIFIER = 'IDENTIFIER',\n\n // Operators\n PLUS = 'PLUS',\n MINUS = 'MINUS',\n MULTIPLY = 'MULTIPLY',\n DIVIDE = 'DIVIDE',\n MODULO = 'MODULO',\n\n // Comparison\n EQUAL = 'EQUAL',\n NOT_EQUAL = 'NOT_EQUAL',\n GREATER = 'GREATER',\n LESS = 'LESS',\n GREATER_EQUAL = 'GREATER_EQUAL',\n LESS_EQUAL = 'LESS_EQUAL',\n\n // Logical\n AND = 'AND',\n OR = 'OR',\n NOT = 'NOT',\n\n // Punctuation\n DOT = 'DOT',\n COMMA = 'COMMA',\n LPAREN = 'LPAREN',\n RPAREN = 'RPAREN',\n LBRACKET = 'LBRACKET',\n RBRACKET = 'RBRACKET',\n\n // Special\n EOF = 'EOF',\n}\n\n/**\n * Token with type, value, and position\n */\nexport interface Token {\n type: TokenType;\n value: string;\n position: number;\n}\n\n/**\n * AST Node types\n */\nexport type ASTNode = LiteralNode | IdentifierNode | MemberAccessNode | BinaryOpNode | UnaryOpNode | CallExpressionNode | ArrayLiteralNode;\n\nexport interface LiteralNode {\n type: 'Literal';\n value: string | number | boolean | null | undefined;\n}\n\nexport interface IdentifierNode {\n type: 'Identifier';\n name: string;\n}\n\nexport interface MemberAccessNode {\n type: 'MemberAccess';\n object: ASTNode;\n property: string;\n}\n\nexport interface BinaryOpNode {\n type: 'BinaryOp';\n operator: string;\n left: ASTNode;\n right: ASTNode;\n}\n\nexport interface UnaryOpNode {\n type: 'UnaryOp';\n operator: string;\n operand: ASTNode;\n}\n\nexport interface CallExpressionNode {\n type: 'CallExpression';\n callee: ASTNode;\n arguments: ASTNode[];\n}\n\nexport interface ArrayLiteralNode {\n type: 'ArrayLiteral';\n elements: ASTNode[];\n}\n\n/**\n * Parser error with position information\n */\nexport class ExpressionParserError extends DynamicFormError {\n constructor(\n message: string,\n public position: number,\n public expression: string,\n ) {\n super(`${message} at position ${position} in expression: ${expression}`);\n this.name = 'ExpressionParserError';\n }\n}\n","import { Token, TokenType, ExpressionParserError } from './types';\n\n/**\n * Tokenizes an expression string into tokens\n */\nexport class Tokenizer {\n private position = 0;\n private readonly expression: string;\n\n constructor(expression: string) {\n this.expression = expression;\n }\n\n /**\n * Tokenize the entire expression\n */\n tokenize(): Token[] {\n const tokens: Token[] = [];\n\n while (this.position < this.expression.length) {\n this.skipWhitespace();\n\n if (this.position >= this.expression.length) {\n break;\n }\n\n const token = this.nextToken();\n tokens.push(token);\n }\n\n tokens.push({ type: TokenType.EOF, value: '', position: this.position });\n return tokens;\n }\n\n private skipWhitespace(): void {\n while (this.position < this.expression.length && /\\s/.test(this.expression[this.position])) {\n this.position++;\n }\n }\n\n private nextToken(): Token {\n const char = this.expression[this.position];\n\n // String literals\n if (char === '\"' || char === \"'\") {\n return this.readString(char);\n }\n\n // Numbers\n if (/[0-9]/.test(char)) {\n return this.readNumber();\n }\n\n // Identifiers and keywords\n if (/[a-zA-Z_$]/.test(char)) {\n return this.readIdentifierOrKeyword();\n }\n\n // Operators and punctuation\n return this.readOperatorOrPunctuation();\n }\n\n private readString(quote: string): Token {\n const start = this.position;\n this.position++; // Skip opening quote\n\n let value = '';\n while (this.position < this.expression.length) {\n const char = this.expression[this.position];\n\n if (char === quote) {\n this.position++; // Skip closing quote\n return { type: TokenType.STRING, value, position: start };\n }\n\n if (char === '\\\\' && this.position + 1 < this.expression.length) {\n // Handle escape sequences\n this.position++;\n const nextChar = this.expression[this.position];\n switch (nextChar) {\n case 'n':\n value += '\\n';\n break;\n case 't':\n value += '\\t';\n break;\n case 'r':\n value += '\\r';\n break;\n case '\\\\':\n value += '\\\\';\n break;\n case quote:\n value += quote;\n break;\n default:\n value += nextChar;\n }\n this.position++;\n } else {\n value += char;\n this.position++;\n }\n }\n\n throw new ExpressionParserError('Unterminated string literal', start, this.expression);\n }\n\n private readNumber(): Token {\n const start = this.position;\n let value = '';\n\n while (this.position < this.expression.length && /[0-9.]/.test(this.expression[this.position])) {\n value += this.expression[this.position];\n this.position++;\n }\n\n if (!/^\\d+(\\.\\d+)?$/.test(value)) {\n throw new ExpressionParserError(`Invalid number: ${value}`, start, this.expression);\n }\n\n return { type: TokenType.NUMBER, value, position: start };\n }\n\n private readIdentifierOrKeyword(): Token {\n const start = this.position;\n let value = '';\n\n while (this.position < this.expression.length && /[a-zA-Z0-9_$]/.test(this.expression[this.position])) {\n value += this.expression[this.position];\n this.position++;\n }\n\n // Check for keywords\n const type = this.getKeywordType(value);\n return { type, value, position: start };\n }\n\n private getKeywordType(value: string): TokenType {\n switch (value) {\n case 'true':\n return TokenType.TRUE;\n case 'false':\n return TokenType.FALSE;\n case 'null':\n return TokenType.NULL;\n case 'undefined':\n return TokenType.UNDEFINED;\n default:\n return TokenType.IDENTIFIER;\n }\n }\n\n private readOperatorOrPunctuation(): Token {\n const start = this.position;\n const char = this.expression[this.position];\n const nextChar = this.position + 1 < this.expression.length ? this.expression[this.position + 1] : '';\n const thirdChar = this.position + 2 < this.expression.length ? this.expression[this.position + 2] : '';\n\n // Three-character operators - check these first!\n const threeChar = char + nextChar + thirdChar;\n if (threeChar === '===') {\n this.position += 3;\n return { type: TokenType.EQUAL, value: '===', position: start };\n }\n if (threeChar === '!==') {\n this.position += 3;\n return { type: TokenType.NOT_EQUAL, value: '!==', position: start };\n }\n\n // Two-character operators\n const twoChar = char + nextChar;\n switch (twoChar) {\n case '==':\n this.position += 2;\n return { type: TokenType.EQUAL, value: '==', position: start };\n case '!=':\n this.position += 2;\n return { type: TokenType.NOT_EQUAL, value: '!=', position: start };\n case '>=':\n this.position += 2;\n return { type: TokenType.GREATER_EQUAL, value: '>=', position: start };\n case '<=':\n this.position += 2;\n return { type: TokenType.LESS_EQUAL, value: '<=', position: start };\n case '&&':\n this.position += 2;\n return { type: TokenType.AND, value: '&&', position: start };\n case '||':\n this.position += 2;\n return { type: TokenType.OR, value: '||', position: start };\n }\n\n // Single-character operators and punctuation\n this.position++;\n switch (char) {\n case '+':\n return { type: TokenType.PLUS, value: '+', position: start };\n case '-':\n return { type: TokenType.MINUS, value: '-', position: start };\n case '*':\n return { type: TokenType.MULTIPLY, value: '*', position: start };\n case '/':\n return { type: TokenType.DIVIDE, value: '/', position: start };\n case '%':\n return { type: TokenType.MODULO, value: '%', position: start };\n case '>':\n return { type: TokenType.GREATER, value: '>', position: start };\n case '<':\n return { type: TokenType.LESS, value: '<', position: start };\n case '!':\n return { type: TokenType.NOT, value: '!', position: start };\n case '.':\n return { type: TokenType.DOT, value: '.', position: start };\n case ',':\n return { type: TokenType.COMMA, value: ',', position: start };\n case '(':\n return { type: TokenType.LPAREN, value: '(', position: start };\n case ')':\n return { type: TokenType.RPAREN, value: ')', position: start };\n case '[':\n return { type: TokenType.LBRACKET, value: '[', position: start };\n case ']':\n return { type: TokenType.RBRACKET, value: ']', position: start };\n default:\n throw new ExpressionParserError(`Unexpected character: ${char}`, start, this.expression);\n }\n }\n}\n","import { Token, TokenType, ASTNode, ExpressionParserError } from './types';\nimport { Tokenizer } from './tokenizer';\n\n/**\n * Parses tokens into an Abstract Syntax Tree (AST)\n * Uses recursive descent parsing with operator precedence\n */\nexport class Parser {\n private tokens: Token[] = [];\n private current = 0;\n private readonly expression: string;\n\n constructor(expression: string) {\n this.expression = expression;\n }\n\n /**\n * Parse the expression into an AST\n */\n parse(): ASTNode {\n const tokenizer = new Tokenizer(this.expression);\n this.tokens = tokenizer.tokenize();\n this.current = 0;\n\n if (this.isAtEnd()) {\n throw new ExpressionParserError('Empty expression', 0, this.expression);\n }\n\n const result = this.parseExpression();\n\n if (!this.isAtEnd()) {\n const token = this.peek();\n throw new ExpressionParserError(\n `Unexpected token '${token.value}' at position ${token.position} — expression has trailing content`,\n token.position,\n this.expression,\n );\n }\n\n return result;\n }\n\n private parseExpression(): ASTNode {\n return this.parseLogicalOr();\n }\n\n private parseLogicalOr(): ASTNode {\n let node = this.parseLogicalAnd();\n\n while (this.match(TokenType.OR)) {\n const operator = this.previous().value;\n const right = this.parseLogicalAnd();\n node = { type: 'BinaryOp', operator, left: node, right };\n }\n\n return node;\n }\n\n private parseLogicalAnd(): ASTNode {\n let node = this.parseEquality();\n\n while (this.match(TokenType.AND)) {\n const operator = this.previous().value;\n const right = this.parseEquality();\n node = { type: 'BinaryOp', operator, left: node, right };\n }\n\n return node;\n }\n\n private parseEquality(): ASTNode {\n let node = this.parseComparison();\n\n while (this.match(TokenType.EQUAL, TokenType.NOT_EQUAL)) {\n const operator = this.previous().value;\n const right = this.parseComparison();\n node = { type: 'BinaryOp', operator, left: node, right };\n }\n\n return node;\n }\n\n private parseComparison(): ASTNode {\n let node = this.parseAddition();\n\n while (this.match(TokenType.GREATER, TokenType.GREATER_EQUAL, TokenType.LESS, TokenType.LESS_EQUAL)) {\n const operator = this.previous().value;\n const right = this.parseAddition();\n node = { type: 'BinaryOp', operator, left: node, right };\n }\n\n return node;\n }\n\n private parseAddition(): ASTNode {\n let node = this.parseMultiplication();\n\n while (this.match(TokenType.PLUS, TokenType.MINUS)) {\n const operator = this.previous().value;\n const right = this.parseMultiplication();\n node = { type: 'BinaryOp', operator, left: node, right };\n }\n\n return node;\n }\n\n private parseMultiplication(): ASTNode {\n let node = this.parseUnary();\n\n while (this.match(TokenType.MULTIPLY, TokenType.DIVIDE, TokenType.MODULO)) {\n const operator = this.previous().value;\n const right = this.parseUnary();\n node = { type: 'BinaryOp', operator, left: node, right };\n }\n\n return node;\n }\n\n private parseUnary(): ASTNode {\n if (this.match(TokenType.NOT, TokenType.MINUS, TokenType.PLUS)) {\n const operator = this.previous().value;\n const operand = this.parseUnary();\n return { type: 'UnaryOp', operator, operand };\n }\n\n return this.parsePostfix();\n }\n\n private parsePostfix(): ASTNode {\n let node = this.parsePrimary();\n\n while (true) {\n if (this.match(TokenType.DOT)) {\n // Member access: obj.property\n if (!this.check(TokenType.IDENTIFIER)) {\n throw new ExpressionParserError('Expected property name after \".\"', this.peek().position, this.expression);\n }\n const property = this.advance().value;\n node = { type: 'MemberAccess', object: node, property };\n } else if (this.match(TokenType.LPAREN)) {\n // Function call: func()\n const args = this.parseArgumentList();\n this.consume(TokenType.RPAREN, 'Expected \")\" after arguments');\n node = { type: 'CallExpression', callee: node, arguments: args };\n } else {\n break;\n }\n }\n\n return node;\n }\n\n private parsePrimary(): ASTNode {\n // Literals\n if (this.match(TokenType.TRUE)) {\n return { type: 'Literal', value: true };\n }\n\n if (this.match(TokenType.FALSE)) {\n return { type: 'Literal', value: false };\n }\n\n if (this.match(TokenType.NULL)) {\n return { type: 'Literal', value: null };\n }\n\n if (this.match(TokenType.UNDEFINED)) {\n return { type: 'Literal', value: undefined };\n }\n\n if (this.match(TokenType.NUMBER)) {\n return { type: 'Literal', value: parseFloat(this.previous().value) };\n }\n\n if (this.match(TokenType.STRING)) {\n return { type: 'Literal', value: this.previous().value };\n }\n\n // Array literal\n if (this.match(TokenType.LBRACKET)) {\n const elements = this.parseArrayElements();\n this.consume(TokenType.RBRACKET, 'Expected \"]\" after array elements');\n return { type: 'ArrayLiteral', elements };\n }\n\n // Identifier\n if (this.match(TokenType.IDENTIFIER)) {\n return { type: 'Identifier', name: this.previous().value };\n }\n\n // Grouped expression\n if (this.match(TokenType.LPAREN)) {\n const expr = this.parseExpression();\n this.consume(TokenType.RPAREN, 'Expected \")\" after expression');\n return expr;\n }\n\n throw new ExpressionParserError(`Unexpected token: ${this.peek().value}`, this.peek().position, this.expression);\n }\n\n private parseArgumentList(): ASTNode[] {\n const args: ASTNode[] = [];\n\n if (!this.check(TokenType.RPAREN)) {\n do {\n args.push(this.parseExpression());\n } while (this.match(TokenType.COMMA));\n }\n\n return args;\n }\n\n private parseArrayElements(): ASTNode[] {\n const elements: ASTNode[] = [];\n\n if (!this.check(TokenType.RBRACKET)) {\n do {\n elements.push(this.parseExpression());\n } while (this.match(TokenType.COMMA));\n }\n\n return elements;\n }\n\n private match(...types: TokenType[]): boolean {\n for (const type of types) {\n if (this.check(type)) {\n this.advance();\n return true;\n }\n }\n return false;\n }\n\n private check(type: TokenType): boolean {\n if (this.isAtEnd()) return false;\n return this.peek().type === type;\n }\n\n private advance(): Token {\n if (!this.isAtEnd()) this.current++;\n return this.previous();\n }\n\n private isAtEnd(): boolean {\n return this.peek().type === TokenType.EOF;\n }\n\n private peek(): Token {\n return this.tokens[this.current];\n }\n\n private previous(): Token {\n return this.tokens[this.current - 1];\n }\n\n private consume(type: TokenType, message: string): Token {\n if (this.check(type)) return this.advance();\n\n throw new ExpressionParserError(message, this.peek().position, this.expression);\n }\n}\n","import { ASTNode, ExpressionParserError } from './types';\n\n/**\n * Evaluation context for safe expression evaluation\n */\nexport interface EvaluationScope {\n [key: string]: unknown;\n}\n\n/**\n * Security Model: Whitelist-only approach for method calls\n *\n * A method is considered SAFE if it meets ALL criteria:\n * 1. Pure data access/transformation (no side effects)\n * 2. No code execution capabilities\n * 3. No global state modification\n * 4. No prototype chain modification\n * 5. No information disclosure about system internals\n *\n * Methods NOT included (unsafe):\n * - constructor: Could enable code execution via Function constructor\n * - valueOf: Could enable type confusion attacks\n * - __proto__, __defineGetter__, etc: Direct prototype manipulation\n * - hasOwnProperty, isPrototypeOf, propertyIsEnumerable: Leak object structure\n * - toLocaleString: Could expose locale/system information\n */\n\n/**\n * Type-safe method whitelists derived from TypeScript primitive types\n * Only methods explicitly listed here are allowed - this is a whitelist-only approach\n */\nconst STRING_SAFE_METHODS: ReadonlyArray<keyof string> = [\n 'charAt',\n 'charCodeAt',\n 'concat',\n 'endsWith',\n 'includes',\n 'indexOf',\n 'lastIndexOf',\n 'match',\n 'padEnd',\n 'padStart',\n 'repeat',\n 'replace',\n 'search',\n 'slice',\n 'split',\n 'startsWith',\n 'substring',\n 'toLowerCase',\n 'toUpperCase',\n 'trim',\n 'trimEnd',\n 'trimStart',\n 'toString',\n] as const;\n\nconst NUMBER_SAFE_METHODS: ReadonlyArray<keyof number> = ['toExponential', 'toFixed', 'toPrecision', 'toString'] as const;\n\nconst ARRAY_SAFE_METHODS: ReadonlyArray<keyof Array<unknown>> = [\n 'concat',\n 'every',\n 'filter',\n 'find',\n 'findIndex',\n 'flat',\n 'flatMap',\n 'includes',\n 'indexOf',\n 'join',\n 'lastIndexOf',\n 'map',\n 'reduce',\n 'reduceRight',\n 'slice',\n 'some',\n 'toString',\n 'entries',\n 'keys',\n 'values',\n] as const;\n\nconst DATE_SAFE_METHODS: ReadonlyArray<keyof Date> = [\n 'getDate',\n 'getDay',\n 'getFullYear',\n 'getHours',\n 'getMilliseconds',\n 'getMinutes',\n 'getMonth',\n 'getSeconds',\n 'getTime',\n 'getTimezoneOffset',\n 'getUTCDate',\n 'getUTCDay',\n 'getUTCFullYear',\n 'getUTCHours',\n 'getUTCMilliseconds',\n 'getUTCMinutes',\n 'getUTCMonth',\n 'getUTCSeconds',\n 'toDateString',\n 'toISOString',\n 'toJSON',\n 'toString',\n 'toTimeString',\n 'toUTCString',\n] as const;\n\n/**\n * Whitelist of safe methods that can be called on values\n * Using Set for O(1) lookup performance\n */\nconst SAFE_METHODS: Record<string, ReadonlySet<string>> = {\n string: new Set(STRING_SAFE_METHODS as readonly string[]),\n number: new Set(NUMBER_SAFE_METHODS as readonly string[]),\n array: new Set(ARRAY_SAFE_METHODS as readonly string[]),\n date: new Set(DATE_SAFE_METHODS as readonly string[]),\n};\n\n/**\n * Blacklist of property names that should not be accessible\n * These properties can leak information about object structure or enable attacks\n */\nconst BLOCKED_PROPERTIES = new Set<string>([\n 'constructor',\n '__proto__',\n 'prototype',\n '__defineGetter__',\n '__defineSetter__',\n '__lookupGetter__',\n '__lookupSetter__',\n]);\n\n/**\n * Safely evaluates an AST node with a given context\n */\nexport class Evaluator {\n private readonly scope: EvaluationScope;\n private readonly expression: string;\n\n constructor(scope: EvaluationScope, expression: string) {\n this.scope = scope;\n this.expression = expression;\n }\n\n /**\n * Evaluate an AST node\n */\n evaluate(node: ASTNode): unknown {\n switch (node.type) {\n case 'Literal':\n return node.value;\n\n case 'Identifier':\n return this.evaluateIdentifier(node.name);\n\n case 'MemberAccess':\n return this.evaluateMemberAccess(node);\n\n case 'BinaryOp':\n return this.evaluateBinaryOp(node);\n\n case 'UnaryOp':\n return this.evaluateUnaryOp(node);\n\n case 'CallExpression':\n return this.evaluateCallExpression(node);\n\n case 'ArrayLiteral':\n return this.evaluateArrayLiteral(node);\n\n default:\n throw new ExpressionParserError(`Unknown node type: ${(node as { type: string }).type}`, 0, this.expression);\n }\n }\n\n private evaluateIdentifier(name: string): unknown {\n if (name in this.scope) {\n return this.scope[name];\n }\n return undefined;\n }\n\n private evaluateMemberAccess(node: { object: ASTNode; property: string }): unknown {\n const obj = this.evaluate(node.object);\n\n if (obj === null || obj === undefined) {\n return undefined;\n }\n\n // Block access to dangerous properties that could leak information or enable attacks\n if (BLOCKED_PROPERTIES.has(node.property)) {\n throw new ExpressionParserError(`Property \"${node.property}\" is not accessible for security reasons`, 0, this.expression);\n }\n\n // Allow property access on plain objects and primitives\n if (typeof obj === 'object' || typeof obj === 'string' || typeof obj === 'number') {\n return (obj as Record<string, unknown>)[node.property];\n }\n\n return undefined;\n }\n\n private evaluateBinaryOp(node: { operator: string; left: ASTNode; right: ASTNode }): unknown {\n // Handle short-circuit evaluation for logical operators\n if (node.operator === '&&') {\n const left = this.evaluate(node.left);\n return left ? this.evaluate(node.right) : left;\n }\n if (node.operator === '||') {\n const left = this.evaluate(node.left);\n return left ? left : this.evaluate(node.right);\n }\n\n // For all other operators, evaluate both sides\n const left = this.evaluate(node.left);\n const right = this.evaluate(node.right);\n\n switch (node.operator) {\n // Arithmetic\n case '+':\n return (left as number) + (right as number);\n case '-':\n return (left as number) - (right as number);\n case '*':\n return (left as number) * (right as number);\n case '/':\n if (right === 0) return null;\n return (left as number) / (right as number);\n case '%':\n if (right === 0) return null;\n return (left as number) % (right as number);\n\n // Comparison - using == and != intentionally for loose equality\n case '==':\n return left == right;\n case '===':\n return left === right;\n case '!=':\n return left != right;\n case '!==':\n return left !== right;\n case '>':\n return (left as number) > (right as number);\n case '<':\n return (left as number) < (right as number);\n case '>=':\n return (left as number) >= (right as number);\n case '<=':\n return (left as number) <= (right as number);\n\n default:\n throw new ExpressionParserError(`Unknown binary operator: ${node.operator}`, 0, this.expression);\n }\n }\n\n private evaluateUnaryOp(node: { operator: string; operand: ASTNode }): unknown {\n const operand = this.evaluate(node.operand);\n\n switch (node.operator) {\n case '!':\n return !operand;\n case '-':\n return -(operand as number);\n case '+':\n return +(operand as number);\n default:\n throw new ExpressionParserError(`Unknown unary operator: ${node.operator}`, 0, this.expression);\n }\n }\n\n private evaluateCallExpression(node: { callee: ASTNode; arguments: ASTNode[] }): unknown {\n // Only allow method calls (member access), not arbitrary function calls\n if (node.callee.type !== 'MemberAccess') {\n throw new ExpressionParserError('Only method calls are allowed, not arbitrary function calls', 0, this.expression);\n }\n\n const obj = this.evaluate(node.callee.object);\n const methodName = node.callee.property;\n\n // Block access to dangerous properties (must check before method call)\n if (BLOCKED_PROPERTIES.has(methodName)) {\n throw new ExpressionParserError(`Property \"${methodName}\" is not accessible for security reasons`, 0, this.expression);\n }\n\n // Check if the method is in the instance method whitelist\n if (!this.isMethodSafe(obj, methodName)) {\n throw new ExpressionParserError(`Method \"${methodName}\" is not allowed for security reasons`, 0, this.expression);\n }\n\n // Evaluate arguments\n const args = node.arguments.map((arg) => this.evaluate(arg));\n\n // Call the method with proper `this` binding\n const method = (obj as Record<string, unknown>)[methodName];\n if (typeof method === 'function') {\n // Use .call() to properly bind `this` context\n return (method as (...args: unknown[]) => unknown).call(obj, ...args);\n }\n\n return undefined;\n }\n\n private evaluateArrayLiteral(node: { elements: ASTNode[] }): unknown {\n return node.elements.map((element) => this.evaluate(element));\n }\n\n private isMethodSafe(obj: unknown, methodName: string): boolean {\n if (obj === null || obj === undefined) {\n return false;\n }\n\n const type = Array.isArray(obj) ? 'array' : obj instanceof Date ? 'date' : typeof obj;\n\n const safeMethods = SAFE_METHODS[type];\n if (!safeMethods) {\n return false;\n }\n\n return safeMethods.has(methodName);\n }\n}\n","import { Parser } from './parser';\nimport { Evaluator, EvaluationScope } from './evaluator';\nimport { ASTNode, ExpressionParserError } from './types';\n\n/**\n * Maximum cache size to prevent memory issues\n */\nconst MAX_AST_CACHE_SIZE = 1000;\n\n/**\n * LRU Cache implementation for AST nodes\n * Tracks access order to evict least-recently-used entries\n */\nclass LRUCache<K, V> {\n private cache = new Map<K, V>();\n private maxSize: number;\n\n constructor(maxSize: number) {\n this.maxSize = maxSize;\n }\n\n get(key: K): V | undefined {\n const value = this.cache.get(key);\n if (value !== undefined) {\n // Move to end (most recently used)\n this.cache.delete(key);\n this.cache.set(key, value);\n }\n return value;\n }\n\n set(key: K, value: V): void {\n // Delete if exists to update position\n if (this.cache.has(key)) {\n this.cache.delete(key);\n }\n\n // Add to end (most recently used)\n this.cache.set(key, value);\n\n // Evict least recently used if over limit\n if (this.cache.size > this.maxSize) {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) {\n this.cache.delete(firstKey);\n }\n }\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n get size(): number {\n return this.cache.size;\n }\n}\n\n/**\n * Cache for parsed AST nodes to improve performance\n */\nconst astCache = new LRUCache<string, ASTNode>(MAX_AST_CACHE_SIZE);\n\n/**\n * Secure expression parser that uses AST-based evaluation\n *\n * This parser provides:\n * - Security: No arbitrary code execution, only whitelisted operations\n * - Performance: AST caching for repeated expressions\n * - Better errors: Clear error messages with position information\n * - Type safety: Strongly typed AST and evaluation\n */\nexport class ExpressionParser {\n /**\n * Parse an expression string into an AST\n * Results are cached for performance using LRU eviction\n */\n static parse(expression: string): ASTNode {\n // Check cache first\n const cached = astCache.get(expression);\n if (cached) {\n return cached;\n }\n\n // Parse the expression\n const parser = new Parser(expression);\n const ast = parser.parse();\n\n // Cache the result (LRU cache handles eviction automatically)\n astCache.set(expression, ast);\n\n return ast;\n }\n\n /**\n * Evaluate an expression with a given scope\n */\n static evaluate(expression: string, scope: EvaluationScope): unknown {\n try {\n const ast = this.parse(expression);\n const evaluator = new Evaluator(scope, expression);\n return evaluator.evaluate(ast);\n } catch (error) {\n if (error instanceof ExpressionParserError) {\n throw error;\n }\n // Wrap other errors for consistency\n throw new ExpressionParserError(\n `Error evaluating expression: ${error instanceof Error ? error.message : String(error)}`,\n 0,\n expression,\n );\n }\n }\n\n /**\n * Clear the AST cache\n */\n static clearCache(): void {\n astCache.clear();\n }\n\n /**\n * Get cache statistics\n */\n static getCacheStats(): { size: number; maxSize: number } {\n return {\n size: astCache.size,\n maxSize: MAX_AST_CACHE_SIZE,\n };\n }\n}\n","import {\n AndCondition,\n ConditionalExpression,\n FieldValueCondition,\n JavascriptCondition,\n OrCondition,\n} from '../../models/expressions/conditional-expression';\nimport { EvaluationContext } from '../../models/expressions/evaluation-context';\nimport { compareValues, getNestedValue, hasNestedProperty } from './value-utils';\nimport { ExpressionParser } from './parser/expression-parser';\n\n/**\n * Evaluate conditional expression\n * Uses secure AST-based parsing for JavaScript expressions\n */\nexport function evaluateCondition(expression: ConditionalExpression, context: EvaluationContext): boolean {\n switch (expression.type) {\n case 'fieldValue':\n return evaluateFieldValueCondition(expression, context);\n\n case 'javascript':\n return evaluateJavaScriptExpression(expression, context);\n\n case 'custom': {\n const customFn = context.customFunctions?.[expression.functionName];\n if (!customFn) {\n context.logger.error('Custom function not found:', expression.functionName);\n return false;\n }\n\n try {\n return !!customFn(context);\n } catch (error) {\n context.logger.error('Error executing custom function:', expression.functionName, error);\n return false;\n }\n }\n\n case 'and':\n return evaluateAndCondition(expression, context);\n\n case 'or':\n return evaluateOrCondition(expression, context);\n\n case 'http':\n context.logger.warn(\n '[Dynamic Forms] HTTP conditions are resolved asynchronously via createHttpConditionLogicFunction(). ' +\n 'When used inside and/or composites, the HTTP result is not available synchronously. Returning false.',\n );\n return false;\n\n case 'async':\n context.logger.warn(\n 'Async Condition - resolved asynchronously via createAsyncConditionLogicFunction(). ' +\n 'When used inside and/or composites, the async result is not available synchronously. Returning false.',\n );\n return false;\n\n default:\n return false;\n }\n}\n\nfunction evaluateFieldValueCondition(expression: FieldValueCondition, context: EvaluationContext): boolean {\n // Guard against missing fieldPath — invalid config, return false\n if (!expression.fieldPath) return false;\n\n // Try scoped formValue first (handles sibling field lookups within array items).\n // Fall back to rootFormValue for fields outside the current array scope.\n // Use hasNestedProperty to distinguish \"field exists with value undefined\"\n // from \"field path doesn't exist\" — prevents incorrect fallback when an\n // optional array item field is intentionally undefined.\n const fieldValue = hasNestedProperty(context.formValue, expression.fieldPath)\n ? getNestedValue(context.formValue, expression.fieldPath)\n : context.rootFormValue\n ? getNestedValue(context.rootFormValue, expression.fieldPath)\n : undefined;\n return compareValues(fieldValue, expression.value, expression.operator);\n}\n\nfunction evaluateJavaScriptExpression(expression: JavascriptCondition, context: EvaluationContext): boolean {\n try {\n // Use secure AST-based expression parser instead of dynamic code execution\n const result = ExpressionParser.evaluate(expression.expression, context);\n return !!result;\n } catch (error) {\n context.logger.error('Error evaluating JavaScript expression:', expression.expression, error);\n return false;\n }\n}\n\nfunction evaluateAndCondition(expression: AndCondition, context: EvaluationContext): boolean {\n if (expression.conditions.length === 0) return false;\n // All conditions must be true for AND logic\n return expression.conditions.every((condition) => evaluateCondition(condition, context));\n}\n\nfunction evaluateOrCondition(expression: OrCondition, context: EvaluationContext): boolean {\n if (expression.conditions.length === 0) return false;\n // At least one condition must be true for OR logic\n return expression.conditions.some((condition) => evaluateCondition(condition, context));\n}\n","import { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport type { FormFieldStateMap } from '../../models/expressions/field-state-context';\nimport { HttpRequestConfig } from '../../models/http/http-request-config';\nimport { DerivationLogicConfig, LogicTrigger } from '../../models/logic/logic-config';\n\n/**\n * Entry representing a collected derivation from field definitions.\n *\n * Created during form initialization when traversing field definitions\n * to collect all derivation rules (both shorthand and full logic configs).\n *\n * All derivations are self-targeting: the `fieldKey` is both where the\n * derivation is defined AND where the computed value will be set.\n *\n * @public\n */\nexport interface DerivationEntry {\n /**\n * The key of the field where this derivation is defined and targets.\n *\n * Derivations always target the field they are defined on (self-targeting).\n * For array fields, this may include a placeholder path like 'items.$.lineTotal'\n * which is resolved to actual indices at runtime.\n */\n fieldKey: string;\n\n /**\n * Field keys that this derivation depends on.\n *\n * Extracted from conditions and expressions.\n * Used for:\n * - Cycle detection\n * - Reactive dependency tracking\n * - Determining evaluation order\n */\n dependsOn: string[];\n\n /**\n * Condition that determines when this derivation applies.\n *\n * Defaults to `true` (always apply) if not specified.\n */\n condition: ConditionalExpression | boolean;\n\n /**\n * Static value to set on this field.\n *\n * Mutually exclusive with `expression` and `functionName`.\n */\n value?: unknown;\n\n /**\n * JavaScript expression to evaluate for the derived value.\n *\n * Mutually exclusive with `value` and `functionName`.\n */\n expression?: string;\n\n /**\n * Name of a registered custom derivation function.\n *\n * Mutually exclusive with `value`, `expression`, and `http`.\n */\n functionName?: string;\n\n /**\n * HTTP request configuration for server-driven derivations.\n *\n * Mutually exclusive with `value`, `expression`, `functionName`, and `asyncFunctionName`.\n * Processed asynchronously in a dedicated RxJS stream, not in the sync loop.\n */\n http?: HttpRequestConfig;\n\n /**\n * Name of a registered async derivation function.\n *\n * Mutually exclusive with `value`, `expression`, `functionName`, and `http`.\n * Processed asynchronously in a dedicated RxJS stream, not in the sync loop.\n */\n asyncFunctionName?: string;\n\n /**\n * Expression to extract the derived value from an HTTP response.\n *\n * Required when `http` is set.\n */\n responseExpression?: string;\n\n /**\n * When to evaluate the derivation.\n *\n * - `onChange`: Evaluate immediately when dependencies change (default)\n * - `debounced`: Evaluate after value has stabilized for debounceMs\n *\n * @default 'onChange'\n */\n trigger: LogicTrigger;\n\n /**\n * Debounce duration in milliseconds.\n *\n * Only used when `trigger` is 'debounced'.\n * @default 500\n */\n debounceMs?: number;\n\n /**\n * Whether this derivation was created from the shorthand `derivation` property.\n *\n * Shorthand derivations use a string expression directly on the field.\n */\n isShorthand: boolean;\n\n /**\n * The original logic config if this entry was created from a full logic config.\n */\n originalConfig?: DerivationLogicConfig;\n\n /**\n * Optional debug name for easier identification in logs.\n *\n * Copied from the originalConfig if provided. When set, this name\n * appears in verbose derivation logs instead of the field key.\n */\n debugName?: string;\n\n /**\n * When true, the derivation stops running after the user manually\n * edits the target field.\n *\n * Uses the field's `dirty()` signal — derivations write directly to\n * `value.set()` which does not trigger `markAsDirty()`, so\n * `dirty === true` reliably indicates user modification.\n */\n stopOnUserOverride?: boolean;\n\n /**\n * When true (and `stopOnUserOverride` is also true), clears the\n * user-override flag when any dependency of this derivation changes,\n * allowing the derivation to run again.\n */\n reEngageOnDependencyChange?: boolean;\n}\n\n/**\n * Collection of all derivation entries from a form's field definitions.\n *\n * This interface is intentionally minimal - it contains only the core data.\n *\n * @public\n */\nexport interface DerivationCollection {\n /**\n * All derivation entries collected from field definitions,\n * sorted in topological order for efficient processing.\n */\n entries: DerivationEntry[];\n}\n\n/**\n * Result of cycle detection in the derivation graph.\n *\n * @public\n */\nexport interface CycleDetectionResult {\n /**\n * Whether a cycle was detected.\n */\n hasCycle: boolean;\n\n /**\n * Field paths involved in the cycle, if one was detected.\n *\n * Example: ['country', 'currency', 'country'] for a country -> currency -> country cycle.\n */\n cyclePath?: string[];\n\n /**\n * Bidirectional derivation pairs detected (A↔B patterns).\n *\n * These are allowed and stabilize via equality checks, but may oscillate\n * with floating-point precision issues (e.g., currency conversions).\n *\n * Format: ['fieldA↔fieldB', 'fieldC↔fieldD']\n */\n bidirectionalPairs?: string[];\n\n /**\n * Human-readable error message describing the cycle.\n */\n errorMessage?: string;\n}\n\n/**\n * Context for tracking derivation chain during runtime.\n *\n * Prevents infinite loops by tracking which derivations have already\n * been applied in the current update cycle.\n *\n * @internal\n */\nexport interface DerivationChainContext {\n /**\n * Set of derivation keys that have already been applied.\n *\n * Key format: \"fieldKey\"\n *\n * For array derivations, the caller is responsible for resolving\n * array placeholders (e.g., 'items.$.lineTotal' -> 'items.0.lineTotal')\n * before adding to this set.\n */\n appliedDerivations: Set<string>;\n\n /**\n * Current iteration count in the derivation processing loop.\n */\n iteration: number;\n\n /**\n * Set of field keys that changed in this cycle.\n *\n * Used by `reEngageOnDependencyChange` to determine whether to\n * clear a user-override flag. `undefined` on initial onChange evaluation\n * (when no prior value exists to compare against).\n */\n changedFields?: Set<string>;\n\n /**\n * Cached FormFieldStateMap for this cycle.\n *\n * Created once per `applyDerivations` call and reused across all entry\n * evaluations to avoid allocating a new Proxy + Map per entry.\n */\n formFieldState?: FormFieldStateMap;\n}\n\n/**\n * Creates an empty derivation collection.\n *\n * @returns Empty collection ready for population\n *\n * @internal\n */\nexport function createEmptyDerivationCollection(): DerivationCollection {\n return { entries: [] };\n}\n\n/**\n * Creates a new derivation chain context for tracking applied derivations.\n *\n * @returns Fresh context for a new derivation cycle\n *\n * @internal\n */\nexport function createDerivationChainContext(): DerivationChainContext {\n return {\n appliedDerivations: new Set(),\n iteration: 0,\n };\n}\n\n/**\n * Creates a unique key for a derivation entry.\n *\n * Since derivations are self-targeting, the key is simply the field key.\n * This function exists for semantic clarity and to provide a single point\n * of change if the key format needs to be extended in the future.\n *\n * Note: For array derivations, callers must resolve placeholders\n * (e.g., 'items.$.lineTotal' -> 'items.0.lineTotal') before calling this.\n *\n * @param fieldKey - The field key (with array index already resolved)\n * @returns Unique key for the derivation\n *\n * @internal\n */\nexport function createDerivationKey(fieldKey: string): string {\n return fieldKey;\n}\n\n/**\n * Parses a derivation key back into field key.\n *\n * @param key - The derivation key to parse\n * @returns Object containing the field key\n *\n * @internal\n */\nexport function parseDerivationKey(key: string): { fieldKey: string } {\n return { fieldKey: key };\n}\n\n/**\n * Result of processing all pending derivations.\n *\n * @public\n */\nexport interface DerivationProcessingResult {\n /** Number of derivations successfully applied */\n appliedCount: number;\n\n /** Number of derivations skipped (condition not met or value unchanged) */\n skippedCount: number;\n\n /** Number of derivations that failed with errors */\n errorCount: number;\n\n /**\n * Number of derivations that encountered warnings (e.g., missing target field).\n *\n * These are not counted as errors because they may be intentional (conditional fields)\n * but indicate potential configuration issues if unexpected.\n */\n warnCount: number;\n\n /** Total iterations performed */\n iterations: number;\n\n /** Whether max iterations was reached (potential loop) */\n maxIterationsReached: boolean;\n}\n","/**\n * Centralized constants for the derivation system.\n *\n * These constants configure the behavior of derivation processing,\n * caching, and path handling. Centralizing them enables:\n * - Easy configuration changes\n * - Consistent values across all derivation modules\n * - Clear documentation of magic numbers\n *\n * @module\n */\n\n/**\n * Maximum number of derivation iterations before stopping to prevent infinite loops.\n *\n * The value of 10 is chosen based on:\n * - Most derivation chains are 2-3 levels deep (A→B→C)\n * - Complex forms with conditional cascades rarely exceed 5-6 levels\n * - 10 provides headroom for bidirectional sync patterns (A↔B) which may need\n * 2 iterations per pair to stabilize\n * - Higher values delay detection of actual infinite loops\n * - Lower values risk false positives on legitimate deep chains\n *\n * If you hit this limit legitimately, consider:\n * 1. Restructuring derivations to reduce chain depth\n * 2. Using explicit `dependsOn` to control evaluation order\n * 3. Breaking complex derivations into computed signals outside the form\n */\nexport const MAX_DERIVATION_ITERATIONS = 10;\n\n/**\n * Placeholder string for array index in derivation paths.\n *\n * Used in paths like `items.$.quantity` to represent \"each item in the array\".\n * The `$` is resolved to actual indices at runtime during array derivation processing.\n */\nexport const ARRAY_PLACEHOLDER = '.$.';\n\n/**\n * Maximum size of the expression AST cache.\n *\n * Expressions are parsed into Abstract Syntax Trees (AST) once and cached\n * to avoid re-parsing on each evaluation. The cache uses LRU eviction.\n *\n * 1000 entries handles:\n * - Large forms with many derivation expressions\n * - Multiple form instances with different expressions\n * - Memory efficiency (AST nodes are relatively small)\n */\nexport const MAX_AST_CACHE_SIZE = 1000;\n\n/**\n * Delimiter used to create unique derivation keys from source and target field keys.\n *\n * Uses null character (\\x00) which is extremely unlikely to appear in field names,\n * avoiding collision issues that could occur with common delimiters like ':'.\n */\nexport const DERIVATION_KEY_DELIMITER = '\\x00';\n","import { isWritableSignal, untracked } from '@angular/core';\nimport type { FieldState, FieldTree } from '@angular/forms/signals';\nimport type { FieldTreeRecord } from '../field-tree-utils';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport { DerivationWarningTracker } from './derivation-warning-tracker';\n\n/**\n * Error message prefix for derivation-related errors.\n * @internal\n */\nconst ERROR_PREFIX = '[Derivation]';\n\n/**\n * Navigates the form tree to resolve a field instance at the given path.\n *\n * Walks the tree following the same pattern as `setFieldValue`:\n * each segment is looked up on the current node, and signal accessors\n * are called to get the next level.\n *\n * @returns The field instance object, or `undefined` if the path is invalid\n *\n * @internal\n */\nexport function resolveFieldInstance(rootForm: FieldTree<unknown>, fieldPath: string): FieldState<unknown> | undefined {\n const parts = fieldPath.split('.');\n let current = rootForm as FieldTreeRecord;\n\n for (let i = 0; i < parts.length - 1; i++) {\n const next = current[parts[i]];\n if (!next) return undefined;\n current = next as FieldTreeRecord;\n }\n\n const fieldAccessor = current[parts[parts.length - 1]];\n if (!fieldAccessor) return undefined;\n\n return untracked(fieldAccessor);\n}\n\n/**\n * Reads the dirty() signal from a field at the given path.\n *\n * Returns `true` if the field is dirty, `false` if pristine,\n * or `undefined` if the field cannot be found.\n *\n * @internal\n */\nexport function readFieldDirty(rootForm: FieldTree<unknown>, fieldPath: string): boolean | undefined {\n const fieldInstance = resolveFieldInstance(rootForm, fieldPath);\n if (!fieldInstance) return undefined;\n return untracked(fieldInstance.dirty);\n}\n\n/**\n * Resets a field's dirty/touched state at the given path.\n *\n * Used for re-engagement: when a dependency changes, clear the user override\n * so the derivation can re-apply.\n *\n * Uses the public `reset()` API on FieldState, which clears both\n * dirty and touched without changing the field's value.\n *\n * @internal\n */\nexport function resetFieldState(rootForm: FieldTree<unknown>, fieldPath: string): void {\n const fieldInstance = resolveFieldInstance(rootForm, fieldPath);\n if (!fieldInstance) return;\n fieldInstance.reset();\n}\n\n/**\n * Applies a value to the form at the specified path.\n *\n * Uses bracket notation to access child FieldTrees, following the same pattern\n * as group-field and array-field components. Fields are accessed as signals\n * and their value is set via the `.value.set()` method.\n *\n * Handles nested paths and array paths with '$' placeholder.\n *\n * @internal\n */\nexport function applyValueToForm(\n targetPath: string,\n value: unknown,\n rootForm: FieldTree<unknown>,\n logger?: Logger,\n warningTracker?: DerivationWarningTracker,\n): boolean {\n // Handle simple top-level fields\n if (!targetPath.includes('.')) {\n return setFieldValue(rootForm as FieldTreeRecord, targetPath, value, logger, warningTracker);\n }\n\n // Handle nested paths (e.g., 'address.city' or 'items.$.quantity')\n const parts = targetPath.split('.');\n let current = rootForm as FieldTreeRecord;\n\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n\n // Handle array index placeholder '$'\n if (part === '$') {\n // This case should be resolved at collection time\n // If we still have '$', we need to skip for now\n return false;\n }\n\n // Navigate to the next level using bracket notation\n const next = current[part];\n if (!next) {\n warnMissingField(targetPath, logger, warningTracker);\n return false; // Path doesn't exist\n }\n current = next as FieldTreeRecord;\n }\n\n // Set the final value\n const finalPart = parts[parts.length - 1];\n return setFieldValue(current, finalPart, value, logger, warningTracker);\n}\n\n/**\n * Sets a field value using the Angular Signal Forms pattern.\n *\n * Accesses the child field via bracket notation, drills down to find\n * the WritableSignal, and uses isWritableSignal for type-safe signal detection.\n *\n * Angular Signal Forms structure:\n * - form[key] is a callable function (field accessor)\n * - form[key]() returns the field instance with { value: WritableSignal<T> }\n * - form[key]().value.set(newValue) sets the value\n *\n * @returns true if the value was successfully set, false if field not found\n *\n * @internal\n */\nfunction setFieldValue(\n parent: FieldTreeRecord,\n fieldKey: string,\n value: unknown,\n logger?: Logger,\n warningTracker?: DerivationWarningTracker,\n): boolean {\n const fieldAccessor = parent[fieldKey];\n\n if (!fieldAccessor) {\n warnMissingField(fieldKey, logger, warningTracker);\n return false;\n }\n\n // Call the FieldTree to get the FieldState\n const fieldInstance = untracked(fieldAccessor);\n\n if (!fieldInstance || typeof fieldInstance !== 'object') {\n warnMissingField(fieldKey, logger, warningTracker);\n return false;\n }\n\n // Get the value signal and verify it's a WritableSignal\n const valueSignal = fieldInstance.value;\n\n if (isWritableSignal(valueSignal)) {\n // Writing directly to value.set() does NOT trigger markAsDirty() —\n // only user interaction through setControlValue() does. So derivation-applied\n // values leave the field pristine, and dirty() reliably indicates user edits.\n valueSignal.set(value);\n return true;\n } else {\n warnMissingField(fieldKey, logger, warningTracker);\n return false;\n }\n}\n\n/**\n * Logs a warning for a missing target field (once per field per form instance).\n *\n * Uses the provided warning tracker to avoid log spam. If no tracker is provided,\n * the warning will be logged every time.\n *\n * @internal\n */\nexport function warnMissingField(fieldKey: string, logger?: Logger, warningTracker?: DerivationWarningTracker): void {\n // If tracker is provided, check if we've already warned about this field\n if (warningTracker) {\n if (warningTracker.warnedFields.has(fieldKey)) {\n return;\n }\n warningTracker.warnedFields.add(fieldKey);\n }\n\n logger?.warn(\n `${ERROR_PREFIX} Target field '${fieldKey}' not found in form. ` +\n `Ensure the field is defined in your form configuration. ` +\n `This warning is shown once per field.`,\n );\n}\n","import { Signal, untracked } from '@angular/core';\nimport type { FieldTree } from '@angular/forms/signals';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { EvaluationContext } from '../../models/expressions/evaluation-context';\nimport type { FieldStateInfo } from '../../models/expressions/field-state-context';\nimport type { FieldTreeRecord } from '../field-tree-utils';\nimport { isEqual } from '../../utils/object-utils';\nimport { parseArrayPath, resolveArrayPath, isArrayPlaceholderPath } from '../../utils/path-utils/path-utils';\nimport { CustomFunction } from '../expressions/custom-function-types';\nimport { evaluateCondition } from '../expressions/condition-evaluator';\nimport { ExpressionParser } from '../expressions/parser/expression-parser';\nimport { getNestedValue } from '../expressions/value-utils';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport {\n createDerivationChainContext,\n createDerivationKey,\n DerivationChainContext,\n DerivationCollection,\n DerivationEntry,\n DerivationProcessingResult,\n} from './derivation-types';\nimport { DerivationWarningTracker } from './derivation-warning-tracker';\nimport { MAX_DERIVATION_ITERATIONS } from './derivation-constants';\nimport { DerivationLogger } from './derivation-logger.service';\nimport { readFieldStateInfo, createFormFieldStateMap } from './field-state-extractor';\nimport { applyValueToForm, readFieldDirty, resetFieldState } from './field-value-utils';\n\n// Re-export for backwards compatibility\nexport type { DerivationProcessingResult } from './derivation-types';\n\n/**\n * Context required for applying derivations.\n *\n * @public\n */\nexport interface DerivationApplicatorContext {\n /** The current form value (signal) */\n formValue: Signal<Record<string, unknown>>;\n\n /** Root form field tree for value updates */\n rootForm: FieldTree<unknown>;\n\n /** Registered custom derivation functions */\n derivationFunctions?: Record<string, CustomFunction>;\n\n /** Custom functions for expression evaluation */\n customFunctions?: Record<string, CustomFunction>;\n\n /**\n * External data resolved from form config signals.\n * Made available in evaluation context as `externalData`.\n */\n externalData?: Record<string, unknown>;\n\n /** Logger for diagnostic output */\n logger: Logger;\n\n /**\n * Instance-scoped warning tracker to prevent log spam.\n * If not provided, warnings will be logged every time.\n */\n warningTracker?: DerivationWarningTracker;\n\n /**\n * Derivation logger for debug output.\n * Created via `createDerivationLogger()` factory.\n */\n derivationLogger: DerivationLogger;\n\n /**\n * Maximum number of iterations for derivation chain processing.\n * Falls back to MAX_DERIVATION_ITERATIONS constant if not provided.\n */\n maxIterations?: number;\n}\n\n/**\n * Result of a single derivation application.\n *\n * @internal\n */\ninterface DerivationResult {\n /** Whether the derivation was applied */\n applied: boolean;\n\n /** The field key */\n fieldKey: string;\n\n /** The computed value */\n newValue?: unknown;\n\n /** Error message if application failed */\n error?: string;\n\n /** Warning message (e.g., missing target field) - not a failure, but noteworthy */\n warning?: string;\n}\n\n/**\n * Applies all pending derivations from a collection.\n *\n * This function processes derivations in order, evaluating conditions\n * and computing values. It handles loop prevention through:\n * 1. Chain tracking (prevents same derivation from running twice in one cycle)\n * 2. Value equality checks (skips if target already has computed value)\n * 3. Max iteration limit (safety fallback)\n *\n * @param collection - The collected derivation entries\n * @param context - Context for applying derivations\n * @param changedFields - Set of field keys that changed (for filtering)\n * @returns Result of the derivation processing\n *\n * @example\n * ```typescript\n * const result = applyDerivations(collection, {\n * formValue: formValueSignal,\n * rootForm: form(),\n * derivationFunctions: customFnConfig?.derivations,\n * logger: inject(DynamicFormLogger),\n * });\n *\n * if (result.maxIterationsReached) {\n * console.warn('Possible derivation loop detected');\n * }\n * ```\n *\n * @public\n */\nexport function applyDerivations(\n collection: DerivationCollection,\n context: DerivationApplicatorContext,\n changedFields?: Set<string>,\n): DerivationProcessingResult {\n const chainContext = createDerivationChainContext();\n chainContext.changedFields = changedFields;\n // Cache formFieldState map per cycle to avoid allocating a new Proxy + Map per entry\n chainContext.formFieldState = createFormFieldStateMap(context.rootForm, false);\n const { derivationLogger } = context;\n const maxIterations = context.maxIterations ?? MAX_DERIVATION_ITERATIONS;\n let appliedCount = 0;\n let skippedCount = 0;\n let errorCount = 0;\n let warnCount = 0;\n\n // Filter entries based on changed fields\n const entriesToProcess = changedFields ? getEntriesForChangedFields(collection.entries, changedFields) : collection.entries;\n\n // Log cycle start in verbose mode\n derivationLogger.cycleStart('onChange', entriesToProcess.length);\n\n // Process derivations iteratively until no more changes\n let hasChanges = true;\n\n while (hasChanges && chainContext.iteration < maxIterations) {\n chainContext.iteration++;\n hasChanges = false;\n\n // Log iteration in verbose mode\n derivationLogger.iteration(chainContext.iteration);\n\n for (const entry of entriesToProcess) {\n const result = tryApplyDerivation(entry, context, chainContext);\n\n if (result.applied) {\n appliedCount++;\n hasChanges = true;\n } else if (result.error) {\n errorCount++;\n } else if (result.warning) {\n warnCount++;\n skippedCount++;\n } else {\n skippedCount++;\n }\n }\n }\n\n // Build result\n const processingResult: DerivationProcessingResult = {\n appliedCount,\n skippedCount,\n errorCount,\n warnCount,\n iterations: chainContext.iteration,\n maxIterationsReached: chainContext.iteration >= maxIterations,\n };\n\n if (processingResult.maxIterationsReached) {\n derivationLogger.maxIterationsReached(processingResult, 'onChange');\n }\n\n // Log summary\n derivationLogger.summary(processingResult, 'onChange');\n\n return processingResult;\n}\n\n/**\n * Gets entries that should be processed based on changed fields.\n *\n * Filters entries by checking if any of their dependencies are in the changed fields set.\n * Also includes all wildcard (*) entries since they depend on any form change.\n *\n * **Parent-key matching:** Since `changedFields` contains root-level keys (e.g., `'address'`),\n * but derivation entries may target or depend on nested paths (e.g., `'address.city'`),\n * this function checks `startsWith(changed + '.')` to include entries whose field or\n * dependencies live under a changed parent. This is intentionally broad — false positives\n * are acceptable for filtering because entries are still guarded by value-equality checks\n * (`isEqual`) in `tryApplyDerivation` and will be skipped if the value hasn't changed.\n *\n * Note: Performance is O(n) where n = total entries. For large forms with many\n * derivations, consider optimizing with indexed lookup maps.\n *\n * @internal\n */\nfunction getEntriesForChangedFields(entries: DerivationEntry[], changedFields: Set<string>): DerivationEntry[] {\n return entries.filter((entry) => {\n // Entries with no dependencies or wildcard dependencies always run\n if (entry.dependsOn.length === 0 || entry.dependsOn.includes('*')) {\n return true;\n }\n\n // Check if any dependency matches a changed field directly\n if (entry.dependsOn.some((dep) => changedFields.has(dep))) {\n return true;\n }\n\n // For array entries (fieldKey contains '$'), check if the entry's parent\n // array key changed. Array derivations have relative dependencies\n // (e.g., 'quantity') but changedFields contains root keys (e.g., 'lineItems').\n for (const changed of changedFields) {\n // Check if this entry lives under a changed parent (array or nested)\n if (entry.fieldKey.startsWith(changed + '.')) return true;\n // Check if a dependency is nested under a changed parent\n if (entry.dependsOn.some((dep) => dep.startsWith(changed + '.'))) return true;\n }\n\n return false;\n });\n}\n\n/**\n * Attempts to apply a single derivation.\n *\n * **Important:** When a derivation's condition evaluates to `false`, the previously\n * derived value is NOT automatically cleared. If you need to reset a field when a\n * condition becomes false, use a separate derivation with an inverted condition\n * that sets the desired fallback value.\n *\n * @example\n * ```typescript\n * // Two derivations for conditional value with cleanup:\n * // When country is USA, set phonePrefix to '+1'\n * { key: 'phonePrefix', logic: [{ type: 'derivation', condition: { field: 'country', operator: '==', value: 'USA' }, value: '+1' }] }\n * // When country is NOT USA, clear phonePrefix\n * { key: 'phonePrefix', logic: [{ type: 'derivation', condition: { field: 'country', operator: '!=', value: 'USA' }, value: '' }] }\n * ```\n *\n * @internal\n */\nfunction tryApplyDerivation(\n entry: DerivationEntry,\n context: DerivationApplicatorContext,\n chainContext: DerivationChainContext,\n): DerivationResult {\n const { derivationLogger } = context;\n\n // HTTP and async entries are processed asynchronously in their own streams — skip in sync loop\n if (entry.http || entry.asyncFunctionName) {\n return { applied: false, fieldKey: entry.fieldKey };\n }\n\n // Check if this is an array field derivation (has '$' placeholder)\n if (isArrayPlaceholderPath(entry.fieldKey)) {\n return tryApplyArrayDerivation(entry, context, chainContext);\n }\n\n const derivationKey = createDerivationKey(entry.fieldKey);\n\n // Check if already applied in this cycle\n if (chainContext.appliedDerivations.has(derivationKey)) {\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'already-applied',\n });\n return { applied: false, fieldKey: entry.fieldKey };\n }\n\n // Check stopOnUserOverride — skip if the user has manually edited the target field\n if (shouldSkipForUserOverride(entry, entry.fieldKey, context, chainContext)) {\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'user-override',\n });\n return { applied: false, fieldKey: entry.fieldKey };\n }\n\n // Create evaluation context\n const formValue = untracked(() => context.formValue());\n const evalContext = createEvaluationContext(entry, formValue, context, chainContext);\n\n // Evaluate condition\n if (!evaluateDerivationCondition(entry.condition, evalContext)) {\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'condition-false',\n });\n return { applied: false, fieldKey: entry.fieldKey };\n }\n\n // Compute derived value\n let newValue: unknown;\n try {\n newValue = computeDerivedValue(entry, evalContext, context);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n context.logger.error(formatDerivationError(entry, 'compute', errorMessage));\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'error',\n error: errorMessage,\n });\n return {\n applied: false,\n fieldKey: entry.fieldKey,\n error: errorMessage,\n };\n }\n\n // Check if value actually changed using exact equality.\n // Note: This uses isEqual which performs deep comparison with exact IEEE 754\n // equality for numbers. Bidirectional derivations with floating-point math\n // may oscillate due to rounding errors. Use explicit rounding in expressions\n // or integer arithmetic to avoid this issue.\n const currentValue = getNestedValue(formValue, entry.fieldKey);\n if (isEqual(currentValue, newValue)) {\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'value-unchanged',\n });\n return { applied: false, fieldKey: entry.fieldKey };\n }\n\n // Apply the value\n try {\n const wasApplied = applyValueToForm(entry.fieldKey, newValue, context.rootForm, context.logger, context.warningTracker);\n\n if (wasApplied) {\n chainContext.appliedDerivations.add(derivationKey);\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'applied',\n previousValue: currentValue,\n newValue,\n });\n return { applied: true, fieldKey: entry.fieldKey, newValue };\n } else {\n // Field not found - this is a warning, not an error\n // The warning was already logged by warnMissingField\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'target-not-found',\n });\n return {\n applied: false,\n fieldKey: entry.fieldKey,\n warning: `Field '${entry.fieldKey}' not found`,\n };\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n context.logger.error(formatDerivationError(entry, 'apply', errorMessage));\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'error',\n error: errorMessage,\n });\n return {\n applied: false,\n fieldKey: entry.fieldKey,\n error: errorMessage,\n };\n }\n}\n\n/**\n * Handles array field derivations with '$' placeholder.\n *\n * Iterates over all array items and applies the derivation for each,\n * resolving '$' to the actual index and creating scoped evaluation contexts.\n *\n * @internal\n */\nfunction tryApplyArrayDerivation(\n entry: DerivationEntry,\n context: DerivationApplicatorContext,\n chainContext: DerivationChainContext,\n): DerivationResult {\n const formValue = untracked(() => context.formValue());\n\n // Parse the field path using path utilities\n const pathInfo = parseArrayPath(entry.fieldKey);\n if (!pathInfo.isArrayPath) {\n return { applied: false, fieldKey: entry.fieldKey, error: 'Invalid array derivation path' };\n }\n\n const { arrayPath } = pathInfo;\n\n // Get the array from form values\n const arrayValue = getNestedValue(formValue, arrayPath);\n if (!Array.isArray(arrayValue)) {\n return { applied: false, fieldKey: entry.fieldKey };\n }\n\n let appliedAny = false;\n\n // Process each array item\n for (let i = 0; i < arrayValue.length; i++) {\n const resolvedPath = resolveArrayPath(entry.fieldKey, i);\n const derivationKey = createDerivationKey(resolvedPath);\n\n // Skip if already applied in this cycle\n if (chainContext.appliedDerivations.has(derivationKey)) {\n continue;\n }\n\n // Check stopOnUserOverride for array items using dirty() signal\n if (shouldSkipForUserOverride(entry, resolvedPath, context, chainContext)) {\n context.derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: resolvedPath,\n result: 'skipped',\n skipReason: 'user-override',\n });\n continue;\n }\n\n // Create evaluation context scoped to this array item\n const arrayItem = arrayValue[i] as Record<string, unknown>;\n const evalContext = createArrayItemEvaluationContext(entry, arrayItem, formValue, i, arrayPath, context, chainContext);\n\n // Evaluate condition\n if (!evaluateDerivationCondition(entry.condition, evalContext)) {\n continue;\n }\n\n // Compute derived value\n let newValue: unknown;\n try {\n newValue = computeDerivedValue(entry, evalContext, context);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n context.logger.error(formatDerivationError(entry, 'compute', `[index ${i}] ${errorMessage}`));\n continue;\n }\n\n // Check if value actually changed\n const currentValue = getNestedValue(formValue, resolvedPath);\n if (isEqual(currentValue, newValue)) {\n continue;\n }\n\n // Apply the value\n try {\n applyValueToForm(resolvedPath, newValue, context.rootForm, context.logger, context.warningTracker);\n chainContext.appliedDerivations.add(derivationKey);\n appliedAny = true;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n context.logger.error(formatDerivationError(entry, 'apply', `[index ${i}] ${errorMessage}`));\n }\n }\n\n return { applied: appliedAny, fieldKey: entry.fieldKey };\n}\n\n/**\n * Creates an evaluation context for derivation processing.\n *\n * @internal\n */\nfunction createEvaluationContext(\n entry: DerivationEntry,\n formValue: Record<string, unknown>,\n context: DerivationApplicatorContext,\n chainContext: DerivationChainContext,\n): EvaluationContext {\n const fieldValue = getNestedValue(formValue, entry.fieldKey);\n\n // Create field state snapshot for this specific field (non-reactive)\n const fieldAccessor = (context.rootForm as FieldTreeRecord)[entry.fieldKey];\n const fieldState = fieldAccessor ? readFieldStateInfo(fieldAccessor, false) : undefined;\n\n return {\n fieldValue,\n formValue,\n fieldPath: entry.fieldKey,\n customFunctions: context.customFunctions,\n externalData: context.externalData,\n logger: context.logger,\n fieldState,\n formFieldState: chainContext.formFieldState,\n };\n}\n\n/**\n * Creates an evaluation context scoped to a specific array item.\n *\n * For array derivations, `formValue` in the expression should reference\n * the current array item's values, not the root form values.\n *\n * @internal\n */\nfunction createArrayItemEvaluationContext(\n entry: DerivationEntry,\n arrayItem: Record<string, unknown>,\n rootFormValue: Record<string, unknown>,\n itemIndex: number,\n arrayPath: string,\n context: DerivationApplicatorContext,\n chainContext: DerivationChainContext,\n): EvaluationContext {\n // For array item expressions, formValue should be the array item\n // This allows expressions like 'formValue.quantity * formValue.unitPrice'\n // to work within the context of each array item\n\n // Create field state snapshot for the specific array item field\n // Navigate: rootForm[arrayPath][index][fieldKey]\n const pathInfo = parseArrayPath(entry.fieldKey);\n let fieldState: FieldStateInfo | undefined;\n\n if (pathInfo.isArrayPath && pathInfo.relativePath) {\n const rootFormRecord = context.rootForm as FieldTreeRecord;\n const arrayAccessor = rootFormRecord[arrayPath];\n if (arrayAccessor) {\n const arrayItems = arrayAccessor as FieldTreeRecord;\n const itemAccessor = arrayItems[String(itemIndex)];\n if (itemAccessor) {\n const itemFields = itemAccessor as FieldTreeRecord;\n const fieldAccessor = itemFields[pathInfo.relativePath];\n if (fieldAccessor) {\n fieldState = readFieldStateInfo(fieldAccessor, false);\n }\n }\n }\n }\n\n return {\n fieldValue: arrayItem,\n formValue: arrayItem,\n fieldPath: `${arrayPath}.${itemIndex}`,\n customFunctions: context.customFunctions,\n externalData: context.externalData,\n logger: context.logger,\n // Provide access to root form value for cross-scope references\n rootFormValue,\n arrayIndex: itemIndex,\n arrayPath,\n fieldState,\n formFieldState: chainContext.formFieldState,\n };\n}\n\n/**\n * Evaluates the derivation condition.\n *\n * @internal\n */\nfunction evaluateDerivationCondition(condition: ConditionalExpression | boolean, context: EvaluationContext): boolean {\n if (typeof condition === 'boolean') {\n return condition;\n }\n\n return evaluateCondition(condition, context);\n}\n\n/**\n * Computes the derived value based on the entry configuration.\n *\n * @internal\n */\nfunction computeDerivedValue(\n entry: DerivationEntry,\n evalContext: EvaluationContext,\n applicatorContext: DerivationApplicatorContext,\n): unknown {\n // Static value\n if (entry.value !== undefined) {\n return entry.value;\n }\n\n // Expression\n if (entry.expression) {\n return ExpressionParser.evaluate(entry.expression, evalContext);\n }\n\n // Custom function\n if (entry.functionName) {\n const fn = applicatorContext.derivationFunctions?.[entry.functionName];\n if (!fn) {\n throw new Error(`Derivation function '${entry.functionName}' not found in customFnConfig.derivations`);\n }\n return fn(evalContext);\n }\n\n // No value source specified\n throw new Error(`Derivation for ${entry.fieldKey} has no value source. ` + `Specify 'value', 'expression', or 'functionName'.`);\n}\n\n/**\n * Error message prefix for derivation-related errors.\n * @internal\n */\nconst ERROR_PREFIX = '[Derivation]';\n\n/**\n * Creates a standardized error message for derivation errors.\n * @internal\n */\nfunction formatDerivationError(entry: DerivationEntry, phase: 'compute' | 'apply' | 'condition', message: string): string {\n const source = entry.expression\n ? `expression: \"${entry.expression.substring(0, 50)}${entry.expression.length > 50 ? '...' : ''}\"`\n : entry.functionName\n ? `function: \"${entry.functionName}\"`\n : entry.value !== undefined\n ? 'static value'\n : 'unknown source';\n\n return `${ERROR_PREFIX} Failed to ${phase} derivation (field: ${entry.fieldKey}, ${source}): ${message}`;\n}\n\n/**\n * Checks whether any of the entry's dependencies appear in the changed fields set.\n *\n * **Known limitation for array derivations:** `changedFields` contains root-level keys\n * (e.g., `'lineItems'`) produced by `getChangedKeys()`, but array derivation dependencies\n * use relative names (e.g., `['quantity', 'unitPrice']`). This means `reEngageOnDependencyChange`\n * only fires for root-level dependencies (e.g., `'discountRate'`) — NOT for intra-item\n * dependencies like `'quantity'` within the same array item.\n *\n * Adding parent-key matching (checking if `entry.fieldKey.startsWith(changed + '.')`)\n * was attempted but causes false positives: editing the TARGET field also triggers\n * `changedFields = {'lineItems'}`, which would reset dirty immediately and break\n * `stopOnUserOverride`. Fixing this requires per-field change tracking instead of\n * per-root-key tracking — a more significant architectural change.\n *\n * @internal\n */\nfunction hasDependencyChanged(entry: DerivationEntry, changedFields: Set<string>): boolean {\n return entry.dependsOn.some((dep) => dep === '*' || changedFields.has(dep));\n}\n\n/**\n * Checks whether a derivation should be skipped due to the user having manually\n * edited the target field. Handles re-engagement when `reEngageOnDependencyChange`\n * is set and a dependency has changed.\n *\n * @returns `true` if the derivation should be skipped, `false` otherwise\n *\n * @internal\n */\nfunction shouldSkipForUserOverride(\n entry: DerivationEntry,\n resolvedFieldKey: string,\n context: DerivationApplicatorContext,\n chainContext: DerivationChainContext,\n): boolean {\n if (!entry.stopOnUserOverride) return false;\n\n const isDirty = readFieldDirty(context.rootForm, resolvedFieldKey) ?? false;\n\n // If the field isn't dirty, no override to skip — and no re-engagement needed.\n // This also avoids wasteful resetFieldState calls on initial form render where\n // changedFields contains all keys (from startWith(null) + pairwise()) but fields\n // are all pristine.\n if (!isDirty) return false;\n\n // Re-engagement: reset dirty state if a dependency changed, allowing re-derivation\n if (entry.reEngageOnDependencyChange && chainContext.changedFields) {\n if (hasDependencyChanged(entry, chainContext.changedFields)) {\n resetFieldState(context.rootForm, resolvedFieldKey);\n // Re-read after reset — field is now pristine, so derivation proceeds\n return false;\n }\n }\n\n // Field is dirty and no re-engagement triggered — skip derivation\n return true;\n}\n\n/**\n * Processes derivations for a specific trigger type.\n *\n * Filters entries by trigger type and applies them.\n *\n * @param collection - The collected derivation entries\n * @param trigger - The trigger type to filter by\n * @param context - Context for applying derivations\n * @param changedFields - Set of field keys that changed (for filtering)\n * @returns Result of the derivation processing\n *\n * @public\n */\nexport function applyDerivationsForTrigger(\n collection: DerivationCollection,\n trigger: 'onChange' | 'debounced',\n context: DerivationApplicatorContext,\n changedFields?: Set<string>,\n): DerivationProcessingResult {\n // Filter entries by trigger type, excluding HTTP and async entries (processed in async streams)\n const filteredEntries = collection.entries.filter((entry) => {\n if (entry.http || entry.asyncFunctionName) return false;\n if (trigger === 'onChange') {\n return !entry.trigger || entry.trigger === 'onChange';\n }\n return entry.trigger === trigger;\n });\n\n // Create a minimal collection with filtered entries\n const filteredCollection: DerivationCollection = {\n entries: filteredEntries,\n };\n\n return applyDerivations(filteredCollection, context, changedFields);\n}\n\n/**\n * Gets all debounced derivation entries from a collection.\n *\n * Use this to extract debounced entries for separate processing with debounce timers.\n *\n * @param collection - The collected derivation entries\n * @returns Array of debounced derivation entries\n *\n * @public\n */\nexport function getDebouncedDerivationEntries(collection: DerivationCollection): DerivationEntry[] {\n return collection.entries.filter((entry) => entry.trigger === 'debounced');\n}\n","import { ConditionalExpression } from '../expressions/conditional-expression';\nimport { HttpRequestConfig } from '../http/http-request-config';\n\n/**\n * Special form-state conditions for button disabled logic.\n *\n * These conditions evaluate form or page-level state rather than field values,\n * and are primarily used for controlling button disabled states.\n *\n * @example\n * ```typescript\n * // Disable submit button when form is invalid or submitting\n * {\n * key: 'submit',\n * type: 'submit',\n * label: 'Submit',\n * logic: [\n * { type: 'disabled', condition: 'formInvalid' },\n * { type: 'disabled', condition: 'formSubmitting' },\n * ]\n * }\n *\n * // Disable next button when current page is invalid\n * nextButton({\n * key: 'next',\n * label: 'Next',\n * logic: [\n * { type: 'disabled', condition: 'pageInvalid' },\n * ]\n * })\n * ```\n *\n * @public\n */\nexport type FormStateCondition =\n /** True when form.valid() === false */\n | 'formInvalid'\n /** True when form.submitting() === true */\n | 'formSubmitting'\n /** True when fields on the current page are invalid (for paged forms) */\n | 'pageInvalid';\n\n/**\n * Logic type for controlling field state (hidden, readonly, disabled, required).\n *\n * @public\n */\nexport type StateLogicType = 'hidden' | 'readonly' | 'disabled' | 'required';\n\n/**\n * Base configuration for conditional field state logic.\n *\n * @internal\n */\ninterface BaseStateLogicConfig {\n /**\n * Logic type identifier for field state.\n *\n * - `hidden`: Hide the field from view (still participates in form state)\n * - `readonly`: Make the field read-only\n * - `disabled`: Disable user interaction\n * - `required`: Make the field required\n */\n type: StateLogicType;\n\n /**\n * Condition that determines when this logic applies.\n *\n * Can be:\n * - `boolean`: Static value (always applies or never applies)\n * - `ConditionalExpression`: Expression evaluated against field/form values\n * - `FormStateCondition`: Special form/page state check (for buttons)\n *\n * @example\n * ```typescript\n * // Static condition\n * condition: true\n *\n * // Field value condition\n * condition: {\n * type: 'fieldValue',\n * fieldPath: 'status',\n * operator: 'equals',\n * value: 'locked'\n * }\n *\n * // Form state condition (for buttons)\n * condition: 'formSubmitting'\n * ```\n */\n condition: ConditionalExpression | boolean | FormStateCondition;\n}\n\n/**\n * State logic that evaluates immediately on change (default).\n *\n * @internal\n */\ninterface ImmediateStateLogicConfig extends BaseStateLogicConfig {\n /**\n * Trigger for immediate evaluation.\n * @default 'onChange'\n */\n trigger?: 'onChange';\n /** Not allowed for onChange trigger */\n debounceMs?: never;\n}\n\n/**\n * State logic that evaluates after a debounce period.\n *\n * @internal\n */\ninterface DebouncedStateLogicConfig extends BaseStateLogicConfig {\n /**\n * Trigger for debounced evaluation.\n * Evaluates after the value has stabilized for the debounce duration.\n */\n trigger: 'debounced';\n /**\n * Debounce duration in milliseconds.\n * @default 500\n */\n debounceMs?: number;\n}\n\n/**\n * Configuration for conditional field state logic.\n *\n * Defines how field behavior changes based on conditions.\n * Supports hiding, disabling, making readonly, or requiring fields\n * based on form state or field values.\n *\n * @example\n * ```typescript\n * // Hide email field when contact method is not email\n * {\n * type: 'hidden',\n * condition: {\n * type: 'fieldValue',\n * fieldPath: 'contactMethod',\n * operator: 'notEquals',\n * value: 'email'\n * }\n * }\n *\n * // Disable button when form is submitting\n * {\n * type: 'disabled',\n * condition: 'formSubmitting'\n * }\n *\n * // Debounced visibility (avoids flicker during rapid typing)\n * {\n * type: 'hidden',\n * trigger: 'debounced',\n * debounceMs: 300,\n * condition: {\n * type: 'fieldValue',\n * fieldPath: 'search',\n * operator: 'isEmpty'\n * }\n * }\n * ```\n *\n * @public\n */\nexport type StateLogicConfig = ImmediateStateLogicConfig | DebouncedStateLogicConfig;\n\n/**\n * Trigger timing for when logic is evaluated.\n *\n * - `onChange`: Evaluate immediately when any dependency changes (default)\n * - `debounced`: Evaluate after the value has stabilized for a duration\n *\n * Use `debounced` for self-transforms (lowercase, trim) or to avoid\n * UI flicker during rapid typing.\n *\n * @public\n */\nexport type LogicTrigger = 'onChange' | 'debounced';\n\n/**\n * Shared fields that appear on all derivation logic config variants.\n *\n * @internal\n */\ninterface SharedDerivationFields {\n /**\n * Logic type identifier for value derivation.\n */\n type: 'derivation';\n\n /**\n * Target property name for property derivation.\n *\n * When set, this derivation targets a field property (like `minDate`, `options`,\n * `label`, `placeholder`) instead of the field's value. The derivation is routed\n * to the property derivation pipeline.\n *\n * When absent, the derivation targets the field's value (default behavior).\n *\n * **Depth limit (max 2 levels):** Only simple and single-dot-nested paths are\n * supported. Paths with 2+ dots (e.g., `'a.b.c'`) will throw at runtime.\n *\n * @example\n * ```typescript\n * // Property derivation (new unified API)\n * {\n * key: 'endDate',\n * type: 'datepicker',\n * logic: [{\n * type: 'derivation',\n * targetProperty: 'minDate',\n * expression: 'formValue.startDate'\n * }]\n * }\n *\n * // Value derivation (no targetProperty — existing behavior)\n * {\n * key: 'total',\n * type: 'input',\n * logic: [{\n * type: 'derivation',\n * expression: 'formValue.quantity * formValue.unitPrice'\n * }]\n * }\n * ```\n */\n targetProperty?: string;\n\n /**\n * Optional name for this derivation for debugging purposes.\n *\n * When provided, this name appears in derivation debug logs,\n * making it easier to identify specific derivations in complex forms.\n *\n * @example\n * ```typescript\n * {\n * key: 'lineTotal',\n * type: 'input',\n * logic: [{\n * type: 'derivation',\n * debugName: 'Calculate line total',\n * expression: 'formValue.quantity * formValue.unitPrice'\n * }]\n * }\n * ```\n */\n debugName?: string;\n\n /**\n * Condition that determines when this derivation applies.\n *\n * Can be:\n * - `boolean`: Static value (always applies or never applies)\n * - `ConditionalExpression`: Expression evaluated against field/form values\n *\n * Defaults to `true` (always apply).\n *\n * Note: FormStateCondition is not supported for derivations.\n *\n * @example\n * ```typescript\n * // Always compute (default)\n * condition: true\n *\n * // Conditional derivation\n * condition: {\n * type: 'fieldValue',\n * fieldPath: 'country',\n * operator: 'equals',\n * value: 'USA'\n * }\n * ```\n */\n condition?: ConditionalExpression | boolean;\n\n /**\n * When true, the derivation stops running after the user manually\n * edits the target field.\n *\n * This is useful for \"smart defaults\" — values that should be\n * auto-filled initially but respected once the user explicitly changes them.\n *\n * Uses the field's `dirty()` signal to detect user modification.\n * Derivations write directly to `value.set()` which does not trigger\n * `markAsDirty()`, so `dirty === true` reliably indicates a user edit.\n *\n * @example\n * ```typescript\n * // Auto-fill display name from first + last name, but stop if user edits it\n * {\n * key: 'displayName',\n * logic: [{\n * type: 'derivation',\n * expression: 'formValue.firstName + \" \" + formValue.lastName',\n * stopOnUserOverride: true\n * }]\n * }\n * ```\n */\n stopOnUserOverride?: boolean;\n\n /**\n * When true (and `stopOnUserOverride` is also true), clears the\n * user-override flag when any dependency of this derivation changes,\n * allowing the derivation to run again.\n *\n * This is useful when a user override should only persist until the\n * underlying data changes — e.g., when switching countries, the\n * phone prefix should re-derive even if the user previously edited it.\n *\n * @example\n * ```typescript\n * {\n * key: 'phonePrefix',\n * logic: [{\n * type: 'derivation',\n * value: '+1',\n * condition: { type: 'fieldValue', fieldPath: 'country', operator: 'equals', value: 'USA' },\n * stopOnUserOverride: true,\n * reEngageOnDependencyChange: true,\n * dependsOn: ['country']\n * }]\n * }\n * ```\n */\n reEngageOnDependencyChange?: boolean;\n}\n\n/**\n * Trigger variants for derivation timing.\n * @internal\n */\ntype ImmediateDerivationTrigger = { trigger?: 'onChange'; debounceMs?: never };\ntype DebouncedDerivationTrigger = { trigger: 'debounced'; debounceMs?: number };\n\n// ============================================================================\n// HTTP derivation mode (source: 'http' — required; dependsOn/responseExpression — required)\n// ============================================================================\n\n/**\n * Base for HTTP derivations. `source: 'http'` is required.\n * TypeScript enforces `dependsOn` and `responseExpression` at the type level.\n *\n * @internal\n */\ninterface HttpDerivationBase extends SharedDerivationFields {\n /** Identifies this derivation as HTTP-driven. */\n source: 'http';\n /**\n * HTTP request configuration for server-driven derivations.\n *\n * The request is sent when dependencies change, with automatic\n * debouncing and cancellation of in-flight requests.\n *\n * Configure debounce via the `trigger: 'debounced'` + `debounceMs` mechanism.\n *\n * @example\n * ```typescript\n * {\n * key: 'exchangeRate',\n * logic: [{\n * type: 'derivation',\n * source: 'http',\n * http: {\n * url: '/api/exchange-rate',\n * method: 'GET',\n * queryParams: {\n * from: 'formValue.sourceCurrency',\n * to: 'formValue.targetCurrency',\n * },\n * },\n * responseExpression: 'response.rate',\n * dependsOn: ['sourceCurrency', 'targetCurrency'],\n * }]\n * }\n * ```\n */\n http: HttpRequestConfig;\n /**\n * Explicit field dependencies. Required for HTTP derivations to prevent\n * wildcard triggering on every keystroke.\n */\n dependsOn: string[];\n /**\n * Expression to extract the derived value from the HTTP response.\n *\n * Evaluated via `ExpressionParser` with `{ response }` as the evaluation scope.\n *\n * @example\n * ```typescript\n * responseExpression: 'response.rate'\n * responseExpression: 'response.data.suggestedPrice'\n * ```\n */\n responseExpression: string;\n // Mutual exclusivity: other sources are not allowed\n value?: never;\n expression?: never;\n functionName?: never;\n asyncFunctionName?: never;\n}\n\n// ============================================================================\n// Async function derivation mode (source: 'asyncFunction' — required; dependsOn — required)\n// ============================================================================\n\n/**\n * Base for async function derivations. `source: 'asyncFunction'` is required.\n * TypeScript enforces `dependsOn` at the type level.\n *\n * @internal\n */\ninterface AsyncFunctionDerivationBase extends SharedDerivationFields {\n /** Identifies this derivation as async-function-driven. */\n source: 'asyncFunction';\n /**\n * Name of a registered async derivation function.\n *\n * The function receives the evaluation context and returns a Promise or Observable\n * of the derived value. Register functions in `customFnConfig.asyncDerivations`.\n *\n * @example\n * ```typescript\n * {\n * key: 'suggestedPrice',\n * logic: [{\n * type: 'derivation',\n * source: 'asyncFunction',\n * asyncFunctionName: 'fetchSuggestedPrice',\n * dependsOn: ['productId', 'quantity'],\n * }]\n * }\n * ```\n */\n asyncFunctionName: string;\n /**\n * Explicit field dependencies. Required for async derivations to prevent\n * wildcard triggering on every form change.\n */\n dependsOn: string[];\n // Mutual exclusivity: other sources are not allowed\n value?: never;\n expression?: never;\n functionName?: never;\n http?: never;\n responseExpression?: never;\n}\n\n// ============================================================================\n// Sync derivation modes\n// ============================================================================\n\n/**\n * Base for expression derivations.\n *\n * @internal\n */\ninterface ExpressionDerivationBase extends SharedDerivationFields {\n source?: never;\n /**\n * JavaScript expression to evaluate for the derived value.\n *\n * Has access to `formValue` object containing all form values.\n * For array fields, `formValue` is scoped to the current array item.\n * Uses the same secure AST-based parser as other expressions.\n *\n * @example\n * ```typescript\n * expression: 'formValue.quantity * formValue.unitPrice'\n * expression: 'formValue.firstName + \" \" + formValue.lastName'\n * expression: 'formValue.price * (1 - formValue.discount / 100)'\n * ```\n */\n expression: string;\n /**\n * Explicit field dependencies for expressions.\n *\n * For `expression`, dependencies are automatically extracted from the expression.\n * Provide `dependsOn` to override automatic detection for complex expressions.\n *\n * @example\n * ```typescript\n * // Override automatic detection for complex expressions\n * {\n * key: 'total',\n * logic: [{\n * type: 'derivation',\n * expression: 'calculateTotal(formValue)',\n * dependsOn: ['quantity', 'unitPrice', 'discount']\n * }]\n * }\n * ```\n */\n dependsOn?: string[];\n // Mutual exclusivity: other mode payload fields are not allowed\n value?: never;\n functionName?: never;\n http?: never;\n asyncFunctionName?: never;\n responseExpression?: never;\n}\n\n/**\n * Base for value derivations.\n *\n * @internal\n */\ninterface ValueDerivationBase extends SharedDerivationFields {\n source?: never;\n /**\n * Static value to set on this field.\n *\n * Use when the derived value is a constant.\n *\n * @example\n * ```typescript\n * value: '+1' // String\n * value: 100 // Number\n * value: true // Boolean\n * value: { code: 'US' } // Object\n * ```\n */\n value: unknown;\n /**\n * Explicit field dependencies for value derivations.\n *\n * For `value` (static), no dependencies are needed.\n * Provide `dependsOn` to conditionally re-evaluate when specific fields change.\n */\n dependsOn?: string[];\n // Mutual exclusivity: other mode payload fields are not allowed\n expression?: never;\n functionName?: never;\n http?: never;\n asyncFunctionName?: never;\n responseExpression?: never;\n}\n\n/**\n * Base for custom sync function derivations.\n *\n * @internal\n */\ninterface FunctionDerivationBase extends SharedDerivationFields {\n source?: never;\n /**\n * Name of a registered custom derivation function.\n *\n * The function receives the evaluation context and returns the derived value.\n * Register functions in `customFnConfig.derivations`.\n *\n * @example\n * ```typescript\n * functionName: 'getCurrencyForCountry'\n * functionName: 'calculateTax'\n * functionName: 'formatPhoneNumber'\n * ```\n */\n functionName: string;\n /**\n * Explicit field dependencies for function derivations.\n *\n * If not provided, defaults to all fields ('*').\n * Specify `dependsOn` for better performance when the function only\n * depends on a subset of fields.\n *\n * @example\n * ```typescript\n * // Only re-evaluate when country changes\n * {\n * key: 'currency',\n * logic: [{\n * type: 'derivation',\n * functionName: 'getCurrencyForCountry',\n * dependsOn: ['country']\n * }]\n * }\n * ```\n */\n dependsOn?: string[];\n // Mutual exclusivity: other mode payload fields are not allowed\n value?: never;\n expression?: never;\n http?: never;\n asyncFunctionName?: never;\n responseExpression?: never;\n}\n\n/**\n * HTTP derivation that evaluates immediately on change (default).\n * @internal\n */\ntype OnChangeHttpDerivationLogicConfig = HttpDerivationBase & ImmediateDerivationTrigger;\n\n/**\n * HTTP derivation that evaluates after a debounce period.\n * @internal\n */\ntype DebouncedHttpDerivationLogicConfig = HttpDerivationBase & DebouncedDerivationTrigger;\n\n/**\n * Async function derivation that evaluates immediately on change (default).\n * @internal\n */\ntype OnChangeAsyncFunctionDerivationLogicConfig = AsyncFunctionDerivationBase & ImmediateDerivationTrigger;\n\n/**\n * Async function derivation that evaluates after a debounce period.\n * @internal\n */\ntype DebouncedAsyncFunctionDerivationLogicConfig = AsyncFunctionDerivationBase & DebouncedDerivationTrigger;\n\n/**\n * Expression derivation that evaluates immediately on change (default).\n * @internal\n */\ntype OnChangeExpressionDerivationLogicConfig = ExpressionDerivationBase & ImmediateDerivationTrigger;\n\n/**\n * Expression derivation that evaluates after a debounce period.\n * @internal\n */\ntype DebouncedExpressionDerivationLogicConfig = ExpressionDerivationBase & DebouncedDerivationTrigger;\n\n/**\n * Value derivation that evaluates immediately on change (default).\n * @internal\n */\ntype OnChangeValueDerivationLogicConfig = ValueDerivationBase & ImmediateDerivationTrigger;\n\n/**\n * Value derivation that evaluates after a debounce period.\n * @internal\n */\ntype DebouncedValueDerivationLogicConfig = ValueDerivationBase & DebouncedDerivationTrigger;\n\n/**\n * Function derivation that evaluates immediately on change (default).\n * @internal\n */\ntype OnChangeFunctionDerivationLogicConfig = FunctionDerivationBase & ImmediateDerivationTrigger;\n\n/**\n * Function derivation that evaluates after a debounce period.\n * @internal\n */\ntype DebouncedFunctionDerivationLogicConfig = FunctionDerivationBase & DebouncedDerivationTrigger;\n\n/**\n * Configuration for value derivation logic.\n *\n * Enables programmatic value derivation based on conditions.\n * Derivations are self-targeting: the logic is placed on the field\n * that should receive the computed value.\n *\n * @example\n * ```typescript\n * // Set phone prefix based on country selection\n * {\n * key: 'phonePrefix',\n * logic: [{\n * type: 'derivation',\n * value: '+1',\n * condition: {\n * type: 'fieldValue',\n * fieldPath: 'country',\n * operator: 'equals',\n * value: 'USA'\n * }\n * }]\n * }\n *\n * // Compute total from quantity and price\n * {\n * key: 'total',\n * derivation: 'formValue.quantity * formValue.unitPrice'\n * }\n *\n * // Use custom function for complex logic\n * {\n * key: 'currency',\n * logic: [{\n * type: 'derivation',\n * functionName: 'getCurrencyForCountry'\n * }]\n * }\n *\n * // Self-transform with debounced trigger\n * // (applies after user stops typing)\n * {\n * key: 'email',\n * logic: [{\n * type: 'derivation',\n * expression: 'formValue.email.toLowerCase()',\n * trigger: 'debounced',\n * debounceMs: 500\n * }]\n * }\n *\n * // Array item derivation (formValue is scoped to current item)\n * {\n * key: 'lineTotal', // Inside array field\n * derivation: 'formValue.quantity * formValue.unitPrice'\n * }\n * ```\n *\n * @public\n */\nexport type DerivationLogicConfig =\n | OnChangeHttpDerivationLogicConfig\n | DebouncedHttpDerivationLogicConfig\n | OnChangeAsyncFunctionDerivationLogicConfig\n | DebouncedAsyncFunctionDerivationLogicConfig\n | OnChangeExpressionDerivationLogicConfig\n | DebouncedExpressionDerivationLogicConfig\n | OnChangeValueDerivationLogicConfig\n | DebouncedValueDerivationLogicConfig\n | OnChangeFunctionDerivationLogicConfig\n | DebouncedFunctionDerivationLogicConfig;\n\n/**\n * Union type for all logic configurations.\n *\n * - `StateLogicConfig`: For field state changes (hidden, readonly, disabled, required)\n * - `DerivationLogicConfig`: For value derivation (including property derivation via `targetProperty`)\n *\n * @public\n */\nexport type LogicConfig = StateLogicConfig | DerivationLogicConfig;\n\n/**\n * Log level for derivation debug output.\n *\n * - 'none': No debug logging\n * - 'summary': Log cycle completion with counts (default in dev mode)\n * - 'verbose': Log individual derivation evaluations with details\n *\n * @public\n */\nexport type DerivationLogLevel = 'none' | 'summary' | 'verbose';\n\n/**\n * Configuration for derivation debug logging.\n *\n * @public\n */\nexport interface DerivationLogConfig {\n /** Log level for derivation debugging. Defaults to 'none'. */\n level: DerivationLogLevel;\n}\n\n/**\n * Creates the default derivation log configuration.\n *\n * Defaults to 'none' (silent). Users can enable logging via `withLoggerConfig`.\n *\n * @returns Default DerivationLogConfig\n *\n * @public\n */\nexport function createDefaultDerivationLogConfig(): DerivationLogConfig {\n return {\n level: 'none',\n };\n}\n\n/**\n * Checks if logging should occur at the specified level.\n *\n * @param config - Current log configuration\n * @param minLevel - Minimum level required for logging\n * @returns True if logging should occur\n *\n * @public\n */\nexport function shouldLog(config: DerivationLogConfig, minLevel: 'summary' | 'verbose'): boolean {\n if (config.level === 'none') return false;\n if (minLevel === 'summary') return config.level === 'summary' || config.level === 'verbose';\n return config.level === 'verbose';\n}\n\n/**\n * Type guard to check if a condition is a FormStateCondition.\n *\n * @param condition - The condition to check\n * @returns true if the condition is a FormStateCondition\n *\n * @public\n */\nexport function isFormStateCondition(\n condition: StateLogicConfig['condition'] | DerivationLogicConfig['condition'],\n): condition is FormStateCondition {\n return typeof condition === 'string' && ['formInvalid', 'formSubmitting', 'pageInvalid'].includes(condition);\n}\n\n/**\n * Type guard to check if a logic config is a StateLogicConfig.\n *\n * @param config - The logic config to check\n * @returns true if the config is for field state logic\n *\n * @public\n */\nexport function isStateLogicConfig(config: LogicConfig): config is StateLogicConfig {\n return config.type === 'hidden' || config.type === 'readonly' || config.type === 'disabled' || config.type === 'required';\n}\n\n/**\n * Type guard to check if a logic config is a DerivationLogicConfig.\n *\n * @param config - The logic config to check\n * @returns true if the config is for value derivation\n *\n * @public\n */\nexport function isDerivationLogicConfig(config: LogicConfig): config is DerivationLogicConfig {\n return config.type === 'derivation';\n}\n\n/**\n * Type guard to check if a derivation config targets a property rather than the field value.\n *\n * When `targetProperty` is present on a `type: 'derivation'` config, it is routed\n * to the property derivation pipeline instead of the value derivation pipeline.\n *\n * @param config - The derivation logic config to check\n * @returns true if the config has a targetProperty (property derivation)\n *\n * @public\n */\nexport function hasTargetProperty(config: DerivationLogicConfig): config is DerivationLogicConfig & { targetProperty: string } {\n return 'targetProperty' in config && typeof config.targetProperty === 'string' && config.targetProperty.length > 0;\n}\n","import { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { FormStateCondition, isFormStateCondition, StateLogicConfig } from '../../models/logic/logic-config';\nimport { CustomValidatorConfig, ValidatorConfig } from '../../models/validation/validator-config';\nimport { SchemaApplicationConfig } from '../../models/schemas/schema-definition';\nimport { CustomFunctionScope } from '../expressions/custom-function-types';\n\n/**\n * Regular expression to detect formValue property access in expressions.\n * Matches patterns like: formValue.fieldName, formValue['fieldName'], formValue[\"fieldName\"]\n */\nconst FORM_VALUE_ACCESS_PATTERN = /\\bformValue\\s*(?:\\.|\\[)/;\n\n/**\n * Regular expressions to extract field paths from formValue expressions.\n *\n * Enhanced to capture full nested paths including dot notation chains:\n * - formValue.fieldName → captures 'fieldName'\n * - formValue.parent.child.grandchild → captures 'parent.child.grandchild'\n * - formValue['field-name'] → captures 'field-name'\n * - formValue[\"field.with.dots\"] → captures 'field.with.dots'\n *\n * Note: Computed property access (formValue[variableName]) is NOT supported\n * and must use explicit dependsOn configuration.\n */\nconst FORM_VALUE_DOT_PATTERN = /\\bformValue\\.([\\w.]+)/g;\nconst FORM_VALUE_BRACKET_SINGLE_PATTERN = /\\bformValue\\s*\\[\\s*'([\\w.-]+)'\\s*\\]/g;\nconst FORM_VALUE_BRACKET_DOUBLE_PATTERN = /\\bformValue\\s*\\[\\s*\"([\\w.-]+)\"\\s*\\]/g;\n\n/**\n * Context for cross-field detection, providing access to function scope information.\n */\nexport interface CrossFieldDetectionContext {\n /**\n * Lookup function to get the scope of a registered custom function.\n *\n * @param functionName The name of the custom function\n * @returns The function's scope, or undefined if not registered\n */\n getFunctionScope?: (functionName: string) => CustomFunctionScope | undefined;\n}\n\n/**\n * Detects if a ConditionalExpression references other fields (cross-field).\n *\n * This is the core detection function that handles ALL expression types:\n * - `fieldValue` with `fieldPath` → Always cross-field\n * - `formValue` → Always cross-field\n * - `javascript` with `formValue.*` in expression → Cross-field\n * - `custom` → Checks registered function scope, defaults to cross-field if unknown\n * - `and`/`or` → Recursively check nested conditions\n *\n * @param expr The conditional expression to analyze\n * @param context Optional context providing function scope lookup\n * @returns true if the expression references other fields\n */\nexport function isCrossFieldExpression(\n expr: ConditionalExpression | boolean | FormStateCondition | undefined,\n context?: CrossFieldDetectionContext,\n): boolean {\n // Boolean, undefined, or FormStateCondition (form-level state checks) are not cross-field\n if (expr === undefined || typeof expr === 'boolean' || isFormStateCondition(expr)) {\n return false;\n }\n\n switch (expr.type) {\n case 'fieldValue':\n // fieldPath means it references another field's value\n return !!expr.fieldPath;\n\n case 'javascript':\n // Check for formValue.* patterns in the expression string\n return FORM_VALUE_ACCESS_PATTERN.test(expr.expression || '');\n\n case 'custom': {\n // For custom functions, determine scope from registry or default to cross-field.\n // Look up function scope from registry if context is provided\n const functionName = expr.functionName;\n if (context?.getFunctionScope && functionName) {\n const scope = context.getFunctionScope(functionName);\n if (scope === 'field') {\n // Function is explicitly marked as field-scoped (no cross-field deps)\n return false;\n }\n // 'form' scope or undefined → treat as cross-field\n }\n\n // Default: conservative approach - assume cross-field\n return true;\n }\n\n case 'async':\n // Async conditions create their own toObservable → toSignal pipeline\n // and manage reactivity independently — not cross-field in the sync graph\n return false;\n\n case 'and':\n case 'or':\n // Recursively check nested conditions, passing context through\n return (expr.conditions || []).some((c) => isCrossFieldExpression(c, context));\n\n default:\n return false;\n }\n}\n\n/**\n * Extracts field dependencies from a ConditionalExpression.\n *\n * Returns an array of field keys that the expression depends on.\n * For `formValue` type without specific field, returns ['*'] to indicate\n * dependency on the entire form.\n *\n * @param expr The conditional expression to analyze\n * @returns Array of field keys that this expression depends on\n */\nexport function extractExpressionDependencies(expr: ConditionalExpression | boolean | undefined): string[] {\n if (expr === undefined || typeof expr === 'boolean') {\n return [];\n }\n\n const deps = new Set<string>();\n\n switch (expr.type) {\n case 'fieldValue':\n if (expr.fieldPath) {\n // Extract root field name (before any dots for nested paths)\n deps.add(expr.fieldPath.split('.')[0]);\n }\n break;\n\n case 'javascript':\n // Extract from formValue.* patterns in expression\n extractFromExpressionString(expr.expression || '', deps);\n break;\n\n case 'custom':\n // Custom functions have full form access - conservative approach\n deps.add('*');\n break;\n\n case 'async':\n // Async conditions manage their own reactivity — no auto-extractable dependencies\n break;\n\n case 'and':\n case 'or':\n // Recursively extract from nested conditions\n for (const condition of expr.conditions || []) {\n extractExpressionDependencies(condition).forEach((d) => deps.add(d));\n }\n break;\n }\n\n return Array.from(deps);\n}\n\n/**\n * Extracts field names from a JavaScript expression string.\n * Handles both dot notation (formValue.field) and bracket notation (formValue['field']).\n */\nexport function extractStringDependencies(expression: string): string[] {\n const deps = new Set<string>();\n extractFromExpressionString(expression, deps);\n return Array.from(deps);\n}\n\n/**\n * Internal helper that populates a Set with dependencies from an expression string.\n *\n * Extracts both root fields and full nested paths for precise dependency tracking:\n * - 'formValue.parent.child' → adds 'parent' (root) and 'parent.child' (full path)\n * - 'formValue.simple' → adds 'simple'\n */\nfunction extractFromExpressionString(expression: string, deps: Set<string>): void {\n // Extract from dot notation: formValue.fieldName or formValue.parent.child.grandchild\n const dotMatches = expression.matchAll(FORM_VALUE_DOT_PATTERN);\n for (const match of dotMatches) {\n const fullPath = match[1];\n // Always add the root field (first segment) as the primary dependency\n const rootField = fullPath.split('.')[0];\n deps.add(rootField);\n // Also add the full path for more precise dependency tracking if nested\n if (fullPath.includes('.')) {\n deps.add(fullPath);\n }\n }\n\n // Extract from bracket notation with single quotes: formValue['fieldName']\n const bracketSingleMatches = expression.matchAll(FORM_VALUE_BRACKET_SINGLE_PATTERN);\n for (const match of bracketSingleMatches) {\n const fullPath = match[1];\n const rootField = fullPath.split('.')[0];\n deps.add(rootField);\n if (fullPath.includes('.')) {\n deps.add(fullPath);\n }\n }\n\n // Extract from bracket notation with double quotes: formValue[\"fieldName\"]\n const bracketDoubleMatches = expression.matchAll(FORM_VALUE_BRACKET_DOUBLE_PATTERN);\n for (const match of bracketDoubleMatches) {\n const fullPath = match[1];\n const rootField = fullPath.split('.')[0];\n deps.add(rootField);\n if (fullPath.includes('.')) {\n deps.add(fullPath);\n }\n }\n}\n\n// ============================================================================\n// Validator Detection\n// ============================================================================\n\n/**\n * Detects if a custom validator configuration references formValue (cross-field validation).\n *\n * @param config The custom validator configuration to check\n * @returns true if the validator references formValue\n */\nexport function isCrossFieldValidator(config: CustomValidatorConfig): boolean {\n if (!config.expression) {\n return false;\n }\n return FORM_VALUE_ACCESS_PATTERN.test(config.expression);\n}\n\n/**\n * Detects if a built-in validator has a dynamic expression that references formValue.\n *\n * Built-in validators (min, max, pattern, etc.) can have dynamic expressions\n * like `{ type: 'min', expression: 'formValue.minAge' }`.\n *\n * @param config The validator configuration to check\n * @returns true if the validator has a cross-field dynamic expression\n */\nexport function isCrossFieldBuiltInValidator(config: ValidatorConfig): boolean {\n if (config.type === 'custom') {\n return false; // Custom validators handled separately\n }\n\n // Check if expression property references formValue\n if ('expression' in config && typeof config.expression === 'string') {\n return FORM_VALUE_ACCESS_PATTERN.test(config.expression);\n }\n\n return false;\n}\n\n/**\n * Checks if a validator uses Angular's resource API (validateHttp / validateAsync).\n *\n * Resource-based validators handle cross-field when-conditions internally\n * via their request/params callbacks returning `undefined`. They must NOT\n * be skipped by the cross-field early-return guard in `applyValidator`,\n * because they require field-level registration.\n */\nexport function isResourceBasedValidator(config: ValidatorConfig): boolean {\n return config.type === 'async' || config.type === 'http';\n}\n\n/**\n * Detects if a validator's `when` condition is cross-field.\n *\n * @param config The validator configuration to check\n * @param context Optional context providing function scope lookup\n * @returns true if the when condition references other fields\n */\nexport function hasCrossFieldWhenCondition(config: ValidatorConfig, context?: CrossFieldDetectionContext): boolean {\n if (!('when' in config) || !config.when) {\n return false;\n }\n return isCrossFieldExpression(config.when as ConditionalExpression, context);\n}\n\n// ============================================================================\n// Logic Detection\n// ============================================================================\n\n/**\n * Detects if a StateLogicConfig has a cross-field condition.\n *\n * Note: This function only handles state logic (hidden, readonly, disabled, required).\n * Derivation logic is handled separately by the derivation system.\n *\n * @param config The state logic configuration to check\n * @param context Optional context providing function scope lookup\n * @returns true if the logic condition references other fields\n */\nexport function isCrossFieldStateLogic(config: StateLogicConfig, context?: CrossFieldDetectionContext): boolean {\n return isCrossFieldExpression(config.condition, context);\n}\n\n// ============================================================================\n// Schema Detection\n// ============================================================================\n\n/**\n * Detects if a SchemaApplicationConfig has a cross-field condition.\n *\n * @param config The schema application configuration to check\n * @param context Optional context providing function scope lookup\n * @returns true if the schema condition references other fields\n */\nexport function isCrossFieldSchema(config: SchemaApplicationConfig, context?: CrossFieldDetectionContext): boolean {\n if (config.type !== 'applyWhen' || !config.condition) {\n return false;\n }\n return isCrossFieldExpression(config.condition, context);\n}\n","import { DerivationEntry } from './derivation-types';\n\n/**\n * Sorts derivation entries in topological order based on their dependencies.\n *\n * This ensures that derivations are processed in the correct order:\n * if derivation B depends on field A, and derivation A->A' modifies A,\n * then A->A' is processed before B.\n *\n * Uses Kahn's algorithm for topological sorting, which also provides\n * natural handling of entries with no dependencies (they come first).\n *\n * @param entries - The derivation entries to sort\n * @returns A new array of entries in topological order\n *\n * @example\n * ```typescript\n * // Given derivations:\n * // 1. quantity -> lineTotal (depends on quantity, unitPrice)\n * // 2. unitPrice -> lineTotal (depends on quantity, unitPrice)\n * // 3. lineTotal -> grandTotal (depends on lineTotal)\n * //\n * // Topological sort ensures lineTotal is computed before grandTotal\n * const sorted = topologicalSort(entries);\n * // Result: [1, 2, 3] - derivations that produce lineTotal come before\n * // those that consume it\n * ```\n *\n * @public\n */\nexport function topologicalSort(entries: DerivationEntry[]): DerivationEntry[] {\n if (entries.length <= 1) {\n return [...entries];\n }\n\n // Build adjacency list and in-degree count\n // An edge A -> B exists if B depends on the target of A\n const graph = new Map<DerivationEntry, Set<DerivationEntry>>();\n const inDegree = new Map<DerivationEntry, number>();\n\n // Initialize\n for (const entry of entries) {\n graph.set(entry, new Set());\n inDegree.set(entry, 0);\n }\n\n // Pre-build index: field key -> entries that produce/target it\n // This enables O(1) lookup instead of O(n) scanning\n const derivationsByField = new Map<string, DerivationEntry[]>();\n for (const entry of entries) {\n // Index by exact field key\n const fieldEntries = derivationsByField.get(entry.fieldKey) ?? [];\n fieldEntries.push(entry);\n derivationsByField.set(entry.fieldKey, fieldEntries);\n\n // Also index array field relative paths for array derivations\n // If entry targets 'items.$.lineTotal', index under 'lineTotal' too\n if (entry.fieldKey.includes('.$.')) {\n const relativePath = entry.fieldKey.split('.$.')[1];\n if (relativePath) {\n const relativeEntries = derivationsByField.get(relativePath) ?? [];\n relativeEntries.push(entry);\n derivationsByField.set(relativePath, relativeEntries);\n }\n }\n }\n\n // Collect entries with wildcard dependencies (need special handling)\n const wildcardDependents: DerivationEntry[] = [];\n for (const entry of entries) {\n if (entry.dependsOn.includes('*')) {\n wildcardDependents.push(entry);\n }\n }\n\n // Build edges using pre-computed index\n // For each entry B, find all entries A whose field is in B's dependencies\n // If B depends on field X, and A produces X, then A must run before B\n for (const entryB of entries) {\n for (const dep of entryB.dependsOn) {\n // Skip wildcards here - handled separately below\n if (dep === '*') continue;\n\n // O(1) lookup: find all derivations that produce this dependency\n const producers = derivationsByField.get(dep);\n if (producers) {\n for (const entryA of producers) {\n const entryAEdges = graph.get(entryA);\n if (entryA !== entryB && entryAEdges && !entryAEdges.has(entryB)) {\n entryAEdges.add(entryB);\n inDegree.set(entryB, (inDegree.get(entryB) ?? 0) + 1);\n }\n }\n }\n }\n }\n\n // Handle wildcard dependencies: they depend on ALL producers\n for (const entryB of wildcardDependents) {\n for (const entryA of entries) {\n const entryAEdges = graph.get(entryA);\n if (entryA !== entryB && entryAEdges && !entryAEdges.has(entryB)) {\n entryAEdges.add(entryB);\n inDegree.set(entryB, (inDegree.get(entryB) ?? 0) + 1);\n }\n }\n }\n\n // Kahn's algorithm: process nodes with in-degree 0\n const queue: DerivationEntry[] = [];\n const sorted: DerivationEntry[] = [];\n\n // Start with entries that have no dependencies on other derivation outputs\n for (const entry of entries) {\n if (inDegree.get(entry) === 0) {\n queue.push(entry);\n }\n }\n\n while (queue.length > 0) {\n const current = queue.shift();\n if (!current) break; // TypeScript guard (shouldn't happen due to while condition)\n sorted.push(current);\n\n // Reduce in-degree for all neighbors\n const neighbors = graph.get(current) ?? new Set<DerivationEntry>();\n for (const neighbor of neighbors) {\n const newDegree = (inDegree.get(neighbor) ?? 0) - 1;\n inDegree.set(neighbor, newDegree);\n\n if (newDegree === 0) {\n queue.push(neighbor);\n }\n }\n }\n\n // If we couldn't sort all entries, there's a cycle\n // (but cycles should be caught by cycle-detector, so this is defensive)\n if (sorted.length !== entries.length) {\n // Return original order for entries in cycles\n const sortedSet = new Set(sorted);\n for (const entry of entries) {\n if (!sortedSet.has(entry)) {\n sorted.push(entry);\n }\n }\n }\n\n return sorted;\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { FieldWithValidation } from '../../definitions/base/field-with-validation';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\nimport { DerivationLogicConfig, hasTargetProperty, isDerivationLogicConfig } from '../../models/logic/logic-config';\nimport { hasChildFields } from '../../models/types/type-guards';\nimport { normalizeFieldsArray } from '../../utils/object-utils';\nimport { extractExpressionDependencies, extractStringDependencies } from '../cross-field/cross-field-detector';\nimport { topologicalSort } from './derivation-sorter';\nimport { DerivationCollection, DerivationEntry } from './derivation-types';\n\n/**\n * Context for collecting derivations, tracking the current array path for relative references.\n *\n * @internal\n */\ninterface CollectionContext {\n /**\n * Current array path for resolving relative field references.\n *\n * When inside an array field, this contains the path to the array item\n * (e.g., 'items[0]' or 'orders[1].lineItems[2]').\n */\n arrayPath?: string;\n}\n\n/**\n * Collects all derivation entries from field definitions.\n *\n * This function traverses the field definition tree and extracts:\n * - Shorthand `derivation` properties on fields\n * - Full `logic` array entries with `type: 'derivation'`\n *\n * The collected entries include dependency information for cycle detection\n * and reactive evaluation. Entries are sorted topologically so derivations\n * are processed in dependency order.\n *\n * Lookup maps (byTarget, byDependency, etc.) are NOT built here to\n * reduce the size of the returned collection.\n *\n * @param fields - Array of field definitions to traverse\n * @returns Collection containing sorted derivation entries\n *\n * @example\n * ```typescript\n * const fields = [\n * { key: 'quantity', type: 'number' },\n * { key: 'unitPrice', type: 'number' },\n * {\n * key: 'total',\n * type: 'number',\n * derivation: 'formValue.quantity * formValue.unitPrice',\n * },\n * ];\n *\n * const collection = collectDerivations(fields);\n * // collection.entries has 1 entry for the 'total' field derivation\n * ```\n *\n * @public\n */\nexport function collectDerivations(fields: FieldDef<unknown>[]): DerivationCollection {\n const entries: DerivationEntry[] = [];\n const context: CollectionContext = {};\n\n traverseFields(fields, entries, context);\n\n // Sort entries in topological order for efficient processing.\n // This ensures derivations are processed in dependency order,\n // reducing the number of iterations needed in the applicator.\n const sortedEntries = topologicalSort(entries);\n\n return { entries: sortedEntries };\n}\n\n/**\n * Recursively traverses field definitions to collect derivations.\n *\n * @internal\n */\nfunction traverseFields(fields: FieldDef<unknown>[], entries: DerivationEntry[], context: CollectionContext): void {\n for (const field of fields) {\n collectFromField(field, entries, context);\n\n // Recursively process container fields (page, row, group, array)\n if (hasChildFields(field)) {\n const childContext = { ...context };\n\n // Update array path context if this is an array field\n if (field.type === 'array') {\n childContext.arrayPath = field.key;\n\n // Array fields have items that can be either FieldDef (primitive) or FieldDef[] (object).\n // Normalize all items to arrays and flatten for traversal.\n const arrayItems = normalizeFieldsArray(field.fields) as (FieldDef<unknown> | FieldDef<unknown>[])[];\n const normalizedChildren: FieldDef<unknown>[] = [];\n\n for (const item of arrayItems) {\n if (Array.isArray(item)) {\n // Object item: FieldDef[] - add each field\n normalizedChildren.push(...item);\n } else {\n // Primitive item: single FieldDef - add directly\n normalizedChildren.push(item);\n }\n }\n\n traverseFields(normalizedChildren, entries, childContext);\n } else {\n traverseFields(normalizeFieldsArray(field.fields) as FieldDef<unknown>[], entries, childContext);\n }\n }\n }\n}\n\n/**\n * Collects derivation entries from a single field.\n *\n * @internal\n */\nfunction collectFromField(field: FieldDef<unknown>, entries: DerivationEntry[], context: CollectionContext): void {\n const fieldKey = field.key;\n if (!fieldKey) return;\n\n const validationField = field as FieldDef<unknown> & FieldWithValidation;\n\n // Collect shorthand derivation property\n if (validationField.derivation) {\n const entry = createShorthandEntry(fieldKey, validationField.derivation, context);\n entries.push(entry);\n }\n\n // Collect logic array derivations\n if (validationField.logic) {\n for (const logicConfig of validationField.logic) {\n if (isDerivationLogicConfig(logicConfig)) {\n if (hasTargetProperty(logicConfig)) continue;\n const entry = createLogicEntry(fieldKey, logicConfig, context);\n entries.push(entry);\n }\n }\n }\n}\n\n/**\n * Creates a derivation entry from the shorthand `derivation` property.\n *\n * Shorthand derivations:\n * - Target the same field they're defined on (self-targeting)\n * - Always apply (condition defaults to true)\n * - Always trigger on change\n *\n * @internal\n */\nfunction createShorthandEntry(fieldKey: string, expression: string, context: CollectionContext): DerivationEntry {\n // Build the effective field key, including array path if in array context\n const effectiveFieldKey = context.arrayPath ? `${context.arrayPath}.$.${fieldKey}` : fieldKey;\n\n return {\n fieldKey: effectiveFieldKey,\n dependsOn: extractStringDependencies(expression),\n condition: true,\n expression,\n trigger: 'onChange',\n isShorthand: true,\n };\n}\n\n/**\n * Creates a derivation entry from a full `DerivationLogicConfig`.\n *\n * All derivations are self-targeting: the derivation is defined on and targets\n * the same field (fieldKey). For array fields, the context is used to build\n * the array placeholder path.\n *\n * Handles:\n * - Condition extraction and dependency analysis\n * - Array field context for placeholder paths\n * - Multiple value source types (static, expression, function)\n * - Trigger and debounce configuration\n *\n * @internal\n */\nfunction createLogicEntry(fieldKey: string, config: DerivationLogicConfig, context: CollectionContext): DerivationEntry {\n // Build the effective field key, including array path if in array context\n const effectiveFieldKey = context.arrayPath ? `${context.arrayPath}.$.${fieldKey}` : fieldKey;\n\n // Runtime guards for HTTP and async derivations.\n // Mutual exclusivity and required fields are now enforced by TypeScript (via `source` discriminant).\n // The wildcard and empty-array checks below are not expressible in the type system.\n if (config.source === 'http') {\n if (config.dependsOn.length === 0) {\n throw new DynamicFormError(\n `HTTP derivation for '${effectiveFieldKey}' requires explicit 'dependsOn'. ` +\n `Wildcard dependencies would trigger HTTP requests on every form change.`,\n );\n }\n if (config.dependsOn.includes('*')) {\n throw new DynamicFormError(\n `HTTP derivation for '${effectiveFieldKey}' cannot use wildcard ('*') in 'dependsOn'. ` +\n `Wildcards would trigger HTTP requests on every form change. Specify explicit field dependencies instead.`,\n );\n }\n }\n\n if (config.source === 'asyncFunction') {\n if (config.dependsOn.length === 0) {\n throw new DynamicFormError(\n `Async derivation for '${effectiveFieldKey}' requires explicit 'dependsOn'. ` +\n `Wildcard dependencies would trigger async functions on every form change.`,\n );\n }\n if (config.dependsOn.includes('*')) {\n throw new DynamicFormError(\n `Async derivation for '${effectiveFieldKey}' cannot use wildcard ('*') in 'dependsOn'. ` +\n `Wildcards would trigger async functions on every form change. Specify explicit field dependencies instead.`,\n );\n }\n }\n\n const dependsOn = extractDependencies(config);\n const condition = config.condition ?? true;\n const trigger = config.trigger ?? 'onChange';\n\n // Extract debounceMs from debounced configs\n // The type system ensures debounceMs is only present when trigger is 'debounced'\n const debounceMs = trigger === 'debounced' ? (config as { debounceMs?: number }).debounceMs : undefined;\n\n return {\n fieldKey: effectiveFieldKey,\n dependsOn,\n condition,\n value: config.value,\n expression: config.expression,\n functionName: config.functionName,\n http: config.http,\n responseExpression: config.responseExpression,\n asyncFunctionName: config.asyncFunctionName,\n trigger,\n debounceMs,\n isShorthand: false,\n originalConfig: config,\n debugName: config.debugName,\n stopOnUserOverride: config.stopOnUserOverride,\n reEngageOnDependencyChange: config.reEngageOnDependencyChange,\n };\n}\n\n/**\n * Extracts all field dependencies from a derivation config.\n *\n * Combines dependencies from:\n * - Explicit `dependsOn` array (if provided, takes precedence)\n * - Condition expression\n * - Value expression\n * - Function name (defaults to '*' if no explicit dependsOn)\n *\n * @internal\n */\nfunction extractDependencies(config: DerivationLogicConfig): string[] {\n const deps = new Set<string>();\n\n // If explicit dependsOn is provided, use it as the primary source\n // This allows users to override automatic detection and control\n // when derivations are triggered\n if (config.dependsOn && config.dependsOn.length > 0) {\n config.dependsOn.forEach((dep) => deps.add(dep));\n } else {\n // Extract from expression (automatic dependency detection)\n if (config.expression) {\n const exprDeps = extractStringDependencies(config.expression);\n exprDeps.forEach((dep) => deps.add(dep));\n }\n\n // Custom functions assume full form access if no explicit dependsOn\n if (config.functionName) {\n deps.add('*');\n }\n }\n\n // Always extract from condition (these are additional runtime guards)\n if (config.condition && config.condition !== true) {\n const conditionDeps = extractExpressionDependencies(config.condition);\n conditionDeps.forEach((dep) => deps.add(dep));\n }\n\n return Array.from(deps);\n}\n","import { isDevMode } from '@angular/core';\nimport { CycleDetectionResult, DerivationCollection } from './derivation-types';\nimport { Logger } from '../../providers/features/logger/logger.interface';\n\n/**\n * Node in the derivation dependency graph.\n *\n * @internal\n */\ninterface GraphNode {\n /** Field key this node represents */\n fieldKey: string;\n\n /** Set of field keys this node depends on (edges to other nodes) */\n dependsOn: Set<string>;\n\n /** Set of field keys that depend on this node (reverse edges) */\n dependedOnBy: Set<string>;\n}\n\n/**\n * State for topological sort cycle detection.\n *\n * @internal\n */\nconst enum VisitState {\n /** Node has not been visited */\n Unvisited = 0,\n /** Node is currently being processed (in the stack) */\n InProgress = 1,\n /** Node has been fully processed */\n Completed = 2,\n}\n\n/**\n * Detects cycles in the derivation dependency graph.\n *\n * Uses Kahn's algorithm variant with DFS to detect cycles.\n * Bidirectional sync patterns (A→B→A) are allowed because they stabilize\n * via the equality check at runtime.\n *\n * @param collection - The collected derivation entries\n * @returns Result indicating whether a cycle exists and details if found\n *\n * @example\n * ```typescript\n * const collection = collectDerivations(fields);\n * const result = detectCycles(collection);\n *\n * if (result.hasCycle) {\n * console.error(`Cycle detected: ${result.cyclePath?.join(' -> ')}`);\n * throw new Error(result.errorMessage);\n * }\n * ```\n *\n * @public\n */\nexport function detectCycles(collection: DerivationCollection): CycleDetectionResult {\n // Build directed graph from derivation entries\n const graph = buildDependencyGraph(collection);\n\n // No entries means no cycles\n if (graph.size === 0) {\n return { hasCycle: false };\n }\n\n // Build bidirectional pairs set for cycle exemption\n const bidirectionalPairs = detectBidirectionalPairs(collection);\n\n // Run DFS to detect cycles\n const result = detectCyclesWithDFS(graph, bidirectionalPairs);\n\n // Include bidirectional pairs in result for warnings\n if (bidirectionalPairs.size > 0) {\n result.bidirectionalPairs = Array.from(bidirectionalPairs);\n }\n\n return result;\n}\n\n/**\n * Detects bidirectional derivation pairs (A↔B patterns).\n *\n * These patterns are allowed because they stabilize via equality checks.\n * Example: USD/EUR conversion where both fields derive from each other.\n *\n * A bidirectional pair exists when:\n * - Field A derives its value from field B (A depends on B)\n * - Field B derives its value from field A (B depends on A)\n *\n * ## Floating-Point Precision Note\n *\n * Bidirectional derivations stabilize via equality checks using exact IEEE 754\n * comparison with no tolerance. This means:\n *\n * - **Integer math**: Safe (e.g., `A = B * 2`, `B = A / 2` where A is even)\n * - **Floating-point math**: May oscillate due to rounding errors\n *\n * For currency conversions or other floating-point operations, consider:\n * 1. Rounding values in your expression (e.g., `Math.round(value * 100) / 100`)\n * 2. Using integer cents instead of decimal dollars\n * 3. Using one-way derivation instead of bidirectional\n *\n * @example\n * ```typescript\n * // Bidirectional currency conversion\n * { key: 'amountUSD', derivation: 'formValue.amountEUR * 1.1' }\n * { key: 'amountEUR', derivation: 'formValue.amountUSD / 1.1' }\n * ```\n *\n * @internal\n */\nfunction detectBidirectionalPairs(collection: DerivationCollection): Set<string> {\n const pairs = new Set<string>();\n\n // Build a map of fieldKey -> dependencies (other fields this derivation reads from)\n const dependencyMap = new Map<string, Set<string>>();\n for (const entry of collection.entries) {\n const deps = dependencyMap.get(entry.fieldKey) ?? new Set<string>();\n for (const dep of entry.dependsOn) {\n if (dep !== '*' && dep !== entry.fieldKey) {\n deps.add(dep);\n }\n }\n dependencyMap.set(entry.fieldKey, deps);\n }\n\n // Find bidirectional pairs: A depends on B AND B depends on A\n for (const [fieldA, depsA] of dependencyMap) {\n for (const fieldB of depsA) {\n const depsB = dependencyMap.get(fieldB);\n if (depsB?.has(fieldA)) {\n // Normalize pair key (alphabetically sorted)\n const pairKey = fieldA < fieldB ? `${fieldA}↔${fieldB}` : `${fieldB}↔${fieldA}`;\n pairs.add(pairKey);\n }\n }\n }\n\n return pairs;\n}\n\n/**\n * Checks if a cycle path represents a bidirectional pair.\n *\n * @internal\n */\nfunction isBidirectionalCycle(cyclePath: string[], bidirectionalPairs: Set<string>): boolean {\n // Bidirectional cycles are exactly: [A, B, A] (length 3 with first=last)\n if (cyclePath.length !== 3) {\n return false;\n }\n\n const [first, second, third] = cyclePath;\n if (first !== third) {\n return false;\n }\n\n // Check if this pair is in our bidirectional set\n const pairKey = first < second ? `${first}↔${second}` : `${second}↔${first}`;\n return bidirectionalPairs.has(pairKey);\n}\n\n/**\n * Builds a dependency graph from derivation entries.\n *\n * Creates nodes for each field involved in derivations and\n * edges representing the derivation dependencies.\n *\n * Edge direction is based on dependencies:\n * - If field A's derivation depends on field B, then B -> A (changing B triggers A)\n * - A cycle exists if: A -> B -> C -> A (circular dependency chain)\n *\n * @internal\n */\nfunction buildDependencyGraph(collection: DerivationCollection): Map<string, GraphNode> {\n const graph = new Map<string, GraphNode>();\n\n // Helper to ensure a node exists\n const ensureNode = (fieldKey: string): GraphNode => {\n let node = graph.get(fieldKey);\n if (!node) {\n node = {\n fieldKey,\n dependsOn: new Set(),\n dependedOnBy: new Set(),\n };\n graph.set(fieldKey, node);\n }\n return node;\n };\n\n for (const entry of collection.entries) {\n const fieldNode = ensureNode(entry.fieldKey);\n\n // Track dependencies from the derivation expression/condition.\n // For cycle detection, edges go from dependency -> field:\n // If field A depends on field B, then when B changes, A gets updated.\n // A cycle exists when there's a circular chain of such dependencies.\n for (const dep of entry.dependsOn) {\n // Skip wildcard dependencies and self-references\n if (dep !== '*' && dep !== entry.fieldKey) {\n const depNode = ensureNode(dep);\n // The field depends on 'dep'\n fieldNode.dependsOn.add(dep);\n // 'dep' is depended on by the field\n depNode.dependedOnBy.add(entry.fieldKey);\n }\n }\n }\n\n return graph;\n}\n\n/**\n * Detects cycles using depth-first search.\n *\n * Uses three-color marking:\n * - Unvisited (white): Not yet processed\n * - InProgress (gray): Currently in the DFS stack\n * - Completed (black): Fully processed\n *\n * A cycle is detected when we visit a node that's InProgress,\n * unless it's a bidirectional sync pattern (allowed).\n *\n * @internal\n */\nfunction detectCyclesWithDFS(graph: Map<string, GraphNode>, bidirectionalPairs: Set<string>): CycleDetectionResult {\n const visitState = new Map<string, VisitState>();\n const parent = new Map<string, string | null>();\n\n // Initialize all nodes as unvisited\n for (const fieldKey of graph.keys()) {\n visitState.set(fieldKey, VisitState.Unvisited);\n }\n\n // Process each unvisited node\n for (const fieldKey of graph.keys()) {\n if (visitState.get(fieldKey) === VisitState.Unvisited) {\n const cycleResult = dfsVisit(fieldKey, graph, visitState, parent, [], bidirectionalPairs);\n if (cycleResult) {\n return cycleResult;\n }\n }\n }\n\n return { hasCycle: false };\n}\n\n/**\n * DFS visit function that detects back edges (cycles).\n *\n * @internal\n */\nfunction dfsVisit(\n fieldKey: string,\n graph: Map<string, GraphNode>,\n visitState: Map<string, VisitState>,\n parent: Map<string, string | null>,\n path: string[],\n bidirectionalPairs: Set<string>,\n): CycleDetectionResult | null {\n visitState.set(fieldKey, VisitState.InProgress);\n path.push(fieldKey);\n\n const node = graph.get(fieldKey);\n if (!node) {\n visitState.set(fieldKey, VisitState.Completed);\n path.pop();\n return null;\n }\n\n // Check all nodes that this field's changes would trigger\n for (const targetFieldKey of node.dependedOnBy) {\n const targetState = visitState.get(targetFieldKey);\n\n if (targetState === VisitState.InProgress) {\n // Back edge found - potential cycle\n const cyclePath = extractCyclePath(path, targetFieldKey);\n\n // Allow bidirectional sync patterns (A→B→A)\n // These stabilize via equality checks at runtime\n if (isBidirectionalCycle(cyclePath, bidirectionalPairs)) {\n // Continue DFS without reporting this as a cycle\n continue;\n }\n\n return {\n hasCycle: true,\n cyclePath,\n errorMessage: formatCycleError(cyclePath),\n };\n }\n\n if (targetState === VisitState.Unvisited) {\n parent.set(targetFieldKey, fieldKey);\n const result = dfsVisit(targetFieldKey, graph, visitState, parent, path, bidirectionalPairs);\n if (result) {\n return result;\n }\n }\n }\n\n visitState.set(fieldKey, VisitState.Completed);\n path.pop();\n return null;\n}\n\n/**\n * Extracts the cycle path from the DFS path.\n *\n * @internal\n */\nfunction extractCyclePath(path: string[], cycleStart: string): string[] {\n const cycleStartIndex = path.indexOf(cycleStart);\n if (cycleStartIndex === -1) {\n // Shouldn't happen, but handle gracefully\n return [...path, cycleStart];\n }\n\n // Extract from cycle start to current position, then back to start\n const cyclePath = path.slice(cycleStartIndex);\n cyclePath.push(cycleStart); // Close the cycle\n return cyclePath;\n}\n\n/**\n * Formats a human-readable error message for a detected cycle.\n *\n * @internal\n */\nfunction formatCycleError(cyclePath: string[]): string {\n const pathStr = cyclePath.join(' -> ');\n return (\n `Derivation cycle detected: ${pathStr}\\n` +\n `This would cause an infinite loop at runtime. ` +\n `Remove one of the derivations to break the cycle.`\n );\n}\n\n/**\n * Validates a derivation collection and throws if cycles are detected.\n *\n * This is the main entry point for cycle validation during form initialization.\n * Should be called after collecting derivations and before setting up effects.\n *\n * In dev mode, logs a warning when bidirectional derivation pairs are detected.\n * These patterns are allowed but may oscillate with floating-point values.\n *\n * @param collection - The collected derivation entries to validate\n * @param logger - Optional logger for dev-mode warnings\n * @throws Error if a cycle is detected, with details about the cycle\n *\n * @example\n * ```typescript\n * const collection = collectDerivations(fields);\n *\n * // This will throw if cycles exist\n * validateNoCycles(collection, logger);\n *\n * // Safe to set up derivation effects now\n * setupDerivationEffects(collection);\n * ```\n *\n * @public\n */\nexport function validateNoCycles(collection: DerivationCollection, logger?: Logger): void {\n const result = detectCycles(collection);\n\n if (result.hasCycle) {\n throw new Error(result.errorMessage);\n }\n\n // Warn about bidirectional patterns in dev mode\n if (isDevMode() && result.bidirectionalPairs && result.bidirectionalPairs.length > 0 && logger) {\n logger.warn(\n '[Derivation] Bidirectional derivation patterns detected. ' +\n 'These patterns stabilize via equality checks, but may oscillate with floating-point values ' +\n '(e.g., currency conversions with rounding). ' +\n 'Consider adding tolerance-based comparisons for numeric values.',\n result.bidirectionalPairs,\n );\n }\n}\n","import { InjectionToken } from '@angular/core';\n\n/**\n * Tracks fields that have already been warned about to prevent log spam.\n * Scoped to a single form instance via DI.\n *\n * This replaces the module-level Set to avoid SSR/testing issues where\n * warnings from one form instance would suppress warnings for all others.\n *\n * @public\n */\nexport interface DerivationWarningTracker {\n /** Set of field keys we've already warned about */\n warnedFields: Set<string>;\n}\n\n/**\n * Injection token for the derivation warning tracker.\n * Provided at form component level for instance-scoped tracking.\n *\n * @public\n */\nexport const DERIVATION_WARNING_TRACKER = new InjectionToken<DerivationWarningTracker>('DerivationWarningTracker', {\n providedIn: null,\n factory: () => ({ warnedFields: new Set<string>() }),\n});\n\n/**\n * Creates a fresh warning tracker instance.\n *\n * @returns A new DerivationWarningTracker with an empty warnedFields Set\n *\n * @public\n */\nexport function createDerivationWarningTracker(): DerivationWarningTracker {\n return { warnedFields: new Set<string>() };\n}\n","import { HttpRequestConfig } from '../../models/http/http-request-config';\nimport { EvaluationContext } from '../../models/expressions/evaluation-context';\nimport { HttpResourceRequest } from '../validation/validator-types';\nimport { ExpressionParser } from '../expressions/parser/expression-parser';\n\n/**\n * Resolves an `HttpRequestConfig` into an `HttpResourceRequest` by evaluating\n * expression-based query params and (optionally) body values.\n *\n * Returns `null` if any path parameter resolves to `undefined` or `null`,\n * signaling that the request should be suppressed (the URL would be malformed).\n *\n * `debounceMs` is intentionally ignored — it's used by HTTP derivations/conditions (PRs 3-4),\n * not by validators.\n */\nexport function resolveHttpRequest(config: HttpRequestConfig, context: EvaluationContext): HttpResourceRequest | null {\n let url = config.url;\n\n if (config.params) {\n for (const [key, expression] of Object.entries(config.params)) {\n const value = ExpressionParser.evaluate(expression, context);\n if (value == null) {\n context.logger.debug(\n `HTTP request suppressed: path param '${key}' resolved to ${String(value)} ` +\n `(expression: '${expression}'). The request will not be sent.`,\n );\n return null;\n }\n url = url.replace(`:${key}`, encodeURIComponent(String(value)));\n }\n }\n\n if (config.queryParams) {\n const params = new URLSearchParams();\n for (const [key, expression] of Object.entries(config.queryParams)) {\n const value = ExpressionParser.evaluate(expression, context);\n params.set(key, value != null ? String(value) : '');\n }\n const queryString = params.toString();\n if (queryString) {\n url += (url.includes('?') ? '&' : '?') + queryString;\n }\n }\n\n const request: HttpResourceRequest = {\n url,\n method: config.method,\n };\n\n if (config.body) {\n if (config.evaluateBodyExpressions) {\n const resolvedBody: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(config.body)) {\n if (typeof value === 'string') {\n resolvedBody[key] = ExpressionParser.evaluate(value, context);\n } else {\n resolvedBody[key] = value;\n }\n }\n request.body = resolvedBody;\n } else {\n request.body = config.body;\n }\n }\n\n if (config.headers) {\n request.headers = config.headers;\n }\n\n return request;\n}\n","import { HttpClient } from '@angular/common/http';\nimport { Signal, untracked } from '@angular/core';\nimport type { FieldTree } from '@angular/forms/signals';\nimport { EMPTY, Observable, Subject, debounceTime, filter, map, pairwise, startWith, switchMap, take, takeUntil } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\nimport { EvaluationContext } from '../../models/expressions/evaluation-context';\nimport { getChangedKeys, isEqual } from '../../utils/object-utils';\nimport { isArrayPlaceholderPath } from '../../utils/path-utils/path-utils';\nimport { CustomFunction } from '../expressions/custom-function-types';\nimport { evaluateCondition } from '../expressions/condition-evaluator';\nimport { ExpressionParser } from '../expressions/parser/expression-parser';\nimport { getNestedValue } from '../expressions/value-utils';\nimport { resolveHttpRequest } from '../http/http-request-resolver';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport { DerivationEntry } from './derivation-types';\nimport { DerivationLogger } from './derivation-logger.service';\nimport { DerivationWarningTracker } from './derivation-warning-tracker';\nimport { readFieldDirty, resetFieldState, applyValueToForm } from './field-value-utils';\nimport { readFieldStateInfo, createFormFieldStateMap } from './field-state-extractor';\nimport type { FieldTreeRecord } from '../field-tree-utils';\n\n/**\n * Context required for creating HTTP derivation streams.\n *\n * @internal\n */\nexport interface HttpDerivationStreamContext {\n /** Signal containing the current form value */\n formValue: Signal<Record<string, unknown>>;\n\n /** Signal containing the form accessor */\n form: Signal<FieldTree<unknown>>;\n\n /** Angular HttpClient for making requests */\n httpClient: HttpClient;\n\n /** Logger for diagnostic output */\n logger: Logger;\n\n /** Signal containing the derivation logger */\n derivationLogger: Signal<DerivationLogger>;\n\n /** Lazy resolver for custom functions — called per-emission to get fresh values */\n customFunctions?: () => Record<string, CustomFunction> | undefined;\n\n /** Lazy resolver for external data — called per-emission to get fresh values */\n externalData?: () => Record<string, unknown> | undefined;\n\n /** Warning tracker to suppress duplicate missing-field warnings */\n warningTracker?: DerivationWarningTracker;\n\n /**\n * Observable that emits when the current generation of streams should be torn down.\n * Pipe HTTP requests through `takeUntil(context.guard$)` to automatically discard\n * in-flight responses when the config changes.\n */\n guard$: Observable<void>;\n}\n\n/**\n * Creates a staleness guard for HTTP/async derivation streams.\n *\n * - Call `invalidate()` when tearing down the current generation of streams.\n * - Pipe HTTP requests through `takeUntil(guard$)` to automatically discard\n * in-flight responses that arrive after the generation has been invalidated.\n */\nexport function createStreamGuard(): { invalidate: () => void; guard$: Observable<void> } {\n const subject = new Subject<void>();\n return {\n invalidate: () => subject.next(),\n guard$: subject.asObservable().pipe(take(1)),\n };\n}\n\nconst LOG_PREFIX = 'HTTP Derivation -';\nconst DEFAULT_HTTP_DEBOUNCE_MS = 300;\n\n/**\n * Creates an RxJS Observable stream that processes an HTTP derivation entry.\n *\n * Each HTTP derivation gets its own stream with:\n * - `debounceTime` to batch rapid changes\n * - `switchMap` to auto-cancel in-flight requests\n * - `catchError` inside the switchMap projection to prevent stream termination\n *\n * **Note:** The stream uses `startWith(null) → pairwise()` to detect changed fields.\n * This means the first form value emission (initial load) will fire an HTTP request\n * for all `dependsOn` fields, since every field appears \"changed\" relative to `null`.\n * This is intentional — it ensures derived values are populated on initial form load.\n *\n * @param entry - The derivation entry with HTTP configuration\n * @param formValue$ - Observable of form value changes\n * @param context - Context with HttpClient, logger, etc.\n * @returns Observable that applies HTTP-derived values to the form\n *\n * @internal\n */\nexport function createHttpDerivationStream(\n entry: DerivationEntry,\n formValue$: Observable<Record<string, unknown>>,\n context: HttpDerivationStreamContext,\n): Observable<void> {\n // Guard: no array support for HTTP derivations\n if (isArrayPlaceholderPath(entry.fieldKey)) {\n context.logger.warn(\n `${LOG_PREFIX} HTTP derivation for array field '${entry.fieldKey}' is not supported. ` +\n `Array HTTP derivations will be supported in a future release.`,\n );\n return EMPTY;\n }\n\n if (!entry.http || !entry.responseExpression) {\n return EMPTY;\n }\n\n // Capture after the guard — TS narrows this to `string` here\n const responseExpression = entry.responseExpression;\n const debounceMs = entry.debounceMs ?? DEFAULT_HTTP_DEBOUNCE_MS;\n\n return formValue$.pipe(\n startWith(null as Record<string, unknown> | null),\n pairwise(),\n map(([previous, current]) => ({\n current: current!,\n changedFields: getChangedKeys(previous, current!),\n })),\n // Only proceed when a dependency in entry.dependsOn changed\n filter(({ changedFields }) => {\n if (changedFields.size === 0) return false;\n return entry.dependsOn.some((dep) => changedFields.has(dep));\n }),\n debounceTime(debounceMs),\n switchMap(({ current, changedFields }) => {\n return new Observable<void>((subscriber) => {\n const formAccessor = untracked(() => context.form());\n\n // Check stopOnUserOverride — skip if the user has manually edited the target field\n if (entry.stopOnUserOverride) {\n const isDirty = readFieldDirty(formAccessor, entry.fieldKey);\n if (isDirty) {\n // Re-engage: if a dependency changed, clear dirty state so derivation resumes\n if (entry.reEngageOnDependencyChange && changedFields.size > 0) {\n if (entry.dependsOn.some((dep) => changedFields.has(dep))) {\n resetFieldState(formAccessor, entry.fieldKey);\n // Fall through — proceed with the HTTP request\n } else {\n // Dependency didn't change, still skip\n const derivationLogger = untracked(() => context.derivationLogger());\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'user-override',\n });\n subscriber.complete();\n return;\n }\n } else {\n const derivationLogger = untracked(() => context.derivationLogger());\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'user-override',\n });\n subscriber.complete();\n return;\n }\n }\n }\n\n // Resolve lazy context values per-emission\n const customFunctions = context.customFunctions?.();\n const externalData = context.externalData?.();\n\n // Build evaluation context for condition check and request resolution\n const fieldValue = getNestedValue(current, entry.fieldKey);\n const fieldAccessor = (formAccessor as FieldTreeRecord)[entry.fieldKey];\n const fieldState = fieldAccessor ? readFieldStateInfo(fieldAccessor, false) : undefined;\n\n const evalContext: EvaluationContext = {\n fieldValue,\n formValue: current,\n fieldPath: entry.fieldKey,\n customFunctions,\n externalData,\n logger: context.logger,\n fieldState,\n formFieldState: createFormFieldStateMap(formAccessor, false),\n };\n\n // Evaluate condition — skip if false\n if (entry.condition !== true) {\n const conditionMet = typeof entry.condition === 'boolean' ? entry.condition : evaluateCondition(entry.condition, evalContext);\n if (!conditionMet) {\n const derivationLogger = untracked(() => context.derivationLogger());\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'condition-false',\n });\n subscriber.complete();\n return;\n }\n }\n\n // Returns null when a path param is undefined — suppress the request\n const resolvedRequest = resolveHttpRequest(entry.http!, evalContext);\n\n if (!resolvedRequest) {\n const derivationLogger = untracked(() => context.derivationLogger());\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'condition-false',\n });\n subscriber.complete();\n return;\n }\n\n // Make the HTTP request. takeUntil(guard$) automatically discards responses\n // that arrive after the config has changed and the guard has been invalidated.\n const method = (resolvedRequest.method ?? 'GET').toUpperCase();\n const httpSub = context.httpClient\n .request(method, resolvedRequest.url, {\n body: resolvedRequest.body,\n headers: resolvedRequest.headers as Record<string, string>,\n })\n .pipe(takeUntil(context.guard$))\n .subscribe({\n next: (response) => {\n try {\n // Extract value from response using responseExpression\n const newValue = ExpressionParser.evaluate(responseExpression, { response });\n\n // Compare with current value — skip if unchanged\n const currentFormValue = untracked(() => context.formValue());\n const currentValue = getNestedValue(currentFormValue, entry.fieldKey);\n\n if (isEqual(currentValue, newValue)) {\n const derivationLogger = untracked(() => context.derivationLogger());\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'value-unchanged',\n });\n subscriber.complete();\n return;\n }\n\n // Apply the value to the form\n const currentForm = untracked(() => context.form());\n applyValueToForm(entry.fieldKey, newValue, currentForm, context.logger, context.warningTracker);\n\n const derivationLogger = untracked(() => context.derivationLogger());\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'applied',\n previousValue: currentValue,\n newValue,\n });\n subscriber.complete();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n context.logger.warn(`${LOG_PREFIX} Failed to process response for '${entry.fieldKey}': ${message}`);\n subscriber.complete();\n }\n },\n error: (error) => {\n const message = error instanceof Error ? error.message : String(error);\n context.logger.warn(`${LOG_PREFIX} HTTP request failed for '${entry.fieldKey}': ${message}`);\n subscriber.complete();\n },\n });\n\n // Cleanup: RxJS unsubscription cancels the in-flight HTTP request.\n // Angular's HttpClient uses an internal AbortController when operating with\n // the fetch backend, so unsubscribing is sufficient for network cancellation.\n return () => {\n httpSub.unsubscribe();\n };\n });\n }),\n catchError((error) => {\n // Safety net — should not normally be reached since inner errors are caught\n const message = error instanceof Error ? error.message : String(error);\n context.logger.warn(`${LOG_PREFIX} Unexpected stream error for '${entry.fieldKey}': ${message}`);\n return EMPTY;\n }),\n );\n}\n","import { Signal, untracked } from '@angular/core';\nimport type { FieldTree } from '@angular/forms/signals';\nimport { EMPTY, from, Observable, debounceTime, filter, map, pairwise, startWith, switchMap } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\nimport { EvaluationContext } from '../../models/expressions/evaluation-context';\nimport { getChangedKeys, isEqual } from '../../utils/object-utils';\nimport { isArrayPlaceholderPath } from '../../utils/path-utils/path-utils';\nimport { CustomFunction } from '../expressions/custom-function-types';\nimport type { AsyncDerivationFunction } from '../expressions/async-custom-function-types';\nimport { evaluateCondition } from '../expressions/condition-evaluator';\nimport { getNestedValue } from '../expressions/value-utils';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport { DerivationEntry } from './derivation-types';\nimport { DerivationLogger } from './derivation-logger.service';\nimport { DerivationWarningTracker } from './derivation-warning-tracker';\nimport { readFieldDirty, resetFieldState, applyValueToForm } from './field-value-utils';\nimport { readFieldStateInfo, createFormFieldStateMap } from './field-state-extractor';\nimport type { FieldTreeRecord } from '../field-tree-utils';\n\n/**\n * Context required for creating async derivation streams.\n *\n * @internal\n */\nexport interface AsyncDerivationStreamContext {\n /** Signal containing the current form value */\n formValue: Signal<Record<string, unknown>>;\n\n /** Signal containing the form accessor */\n form: Signal<FieldTree<unknown>>;\n\n /** Logger for diagnostic output */\n logger: Logger;\n\n /** Signal containing the derivation logger */\n derivationLogger: Signal<DerivationLogger>;\n\n /** Lazy resolver for custom functions — called per-emission to get fresh values */\n customFunctions?: () => Record<string, CustomFunction> | undefined;\n\n /** Lazy resolver for async derivation functions — called per-emission to get fresh values */\n asyncDerivationFunctions?: () => Record<string, AsyncDerivationFunction> | undefined;\n\n /** Lazy resolver for external data — called per-emission to get fresh values */\n externalData?: () => Record<string, unknown> | undefined;\n\n /** Warning tracker to suppress duplicate missing-field warnings */\n warningTracker?: DerivationWarningTracker;\n}\n\nconst LOG_PREFIX = 'Async Derivation -';\nconst DEFAULT_ASYNC_DEBOUNCE_MS = 300;\n\n/**\n * Creates an RxJS Observable stream that processes an async derivation entry.\n *\n * Each async derivation gets its own stream with:\n * - `debounceTime` to batch rapid changes\n * - `switchMap` to auto-cancel in-flight async operations\n * - `catchError` inside the switchMap projection to prevent stream termination\n *\n * @param entry - The derivation entry with asyncFunctionName\n * @param formValue$ - Observable of form value changes\n * @param context - Context with logger, etc.\n * @returns Observable that applies async-derived values to the form\n *\n * @internal\n */\nexport function createAsyncDerivationStream(\n entry: DerivationEntry,\n formValue$: Observable<Record<string, unknown>>,\n context: AsyncDerivationStreamContext,\n): Observable<void> {\n // Guard: no array support for async derivations\n if (isArrayPlaceholderPath(entry.fieldKey)) {\n context.logger.warn(\n `${LOG_PREFIX} Async derivation for array field '${entry.fieldKey}' is not supported. ` +\n `Array async derivations will be supported in a future release.`,\n );\n return EMPTY;\n }\n\n if (!entry.asyncFunctionName) {\n return EMPTY;\n }\n\n const asyncFunctionName = entry.asyncFunctionName;\n const debounceMs = entry.debounceMs ?? DEFAULT_ASYNC_DEBOUNCE_MS;\n\n // startWith(null) → pairwise() causes all fields to appear \"changed\" on the\n // first emission (null vs actual form value), so every dependsOn field matches.\n // This intentionally fires the async derivation on initial form load — same\n // pattern as http-derivation-stream.ts.\n return formValue$.pipe(\n startWith(null as Record<string, unknown> | null),\n pairwise(),\n map(([previous, current]) => ({\n current: current!,\n changedFields: getChangedKeys(previous, current!),\n })),\n // Only proceed when a dependency in entry.dependsOn changed\n filter(({ changedFields }) => {\n if (changedFields.size === 0) return false;\n return entry.dependsOn.some((dep) => changedFields.has(dep));\n }),\n debounceTime(debounceMs),\n switchMap(({ current, changedFields }) => {\n return new Observable<void>((subscriber) => {\n const formAccessor = untracked(() => context.form());\n\n // Check stopOnUserOverride — skip if the user has manually edited the target field\n if (entry.stopOnUserOverride) {\n const isDirty = readFieldDirty(formAccessor, entry.fieldKey);\n if (isDirty) {\n // Re-engage: the outer filter already guarantees changedFields is non-empty\n // and that a dependsOn field changed, so only check reEngageOnDependencyChange.\n if (entry.reEngageOnDependencyChange) {\n resetFieldState(formAccessor, entry.fieldKey);\n // Fall through — proceed with the async call\n } else {\n const derivationLogger = untracked(() => context.derivationLogger());\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'user-override',\n });\n subscriber.complete();\n return;\n }\n }\n }\n\n // Resolve lazy context values per-emission\n const customFunctions = context.customFunctions?.();\n const asyncDerivationFunctions = context.asyncDerivationFunctions?.();\n const externalData = context.externalData?.();\n\n // Look up the async function\n const asyncFn = asyncDerivationFunctions?.[asyncFunctionName];\n if (!asyncFn) {\n context.logger.warn(\n `${LOG_PREFIX} Async derivation function '${asyncFunctionName}' not found for field '${entry.fieldKey}'. ` +\n `Register it in customFnConfig.asyncDerivations.`,\n );\n subscriber.complete();\n return;\n }\n\n // Build evaluation context for condition check\n const fieldValue = getNestedValue(current, entry.fieldKey);\n const fieldAccessor = (formAccessor as FieldTreeRecord)[entry.fieldKey];\n const fieldState = fieldAccessor ? readFieldStateInfo(fieldAccessor, false) : undefined;\n\n const evalContext: EvaluationContext = {\n fieldValue,\n formValue: current,\n fieldPath: entry.fieldKey,\n customFunctions,\n externalData,\n logger: context.logger,\n fieldState,\n formFieldState: createFormFieldStateMap(formAccessor, false),\n };\n\n // Evaluate condition — skip if false\n if (entry.condition !== true) {\n const conditionMet = typeof entry.condition === 'boolean' ? entry.condition : evaluateCondition(entry.condition, evalContext);\n if (!conditionMet) {\n const derivationLogger = untracked(() => context.derivationLogger());\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'condition-false',\n });\n subscriber.complete();\n return;\n }\n }\n\n // Call the async function (normalize Promise → Observable)\n const result$ = from(asyncFn(evalContext));\n\n const asyncSub = result$.subscribe({\n next: (newValue) => {\n try {\n // Compare with current value — skip if unchanged\n const currentFormValue = untracked(() => context.formValue());\n const currentValue = getNestedValue(currentFormValue, entry.fieldKey);\n\n if (isEqual(currentValue, newValue)) {\n const derivationLogger = untracked(() => context.derivationLogger());\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'skipped',\n skipReason: 'value-unchanged',\n });\n subscriber.complete();\n return;\n }\n\n // Apply the value to the form\n const currentForm = untracked(() => context.form());\n applyValueToForm(entry.fieldKey, newValue, currentForm, context.logger, context.warningTracker);\n\n const derivationLogger = untracked(() => context.derivationLogger());\n derivationLogger.evaluation({\n debugName: entry.debugName,\n fieldKey: entry.fieldKey,\n result: 'applied',\n previousValue: currentValue,\n newValue,\n });\n subscriber.complete();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n context.logger.warn(`${LOG_PREFIX} Failed to process result for '${entry.fieldKey}': ${message}`);\n subscriber.complete();\n }\n },\n error: (error) => {\n const message = error instanceof Error ? error.message : String(error);\n context.logger.warn(`${LOG_PREFIX} Async function failed for '${entry.fieldKey}': ${message}`);\n subscriber.complete();\n },\n complete: () => {\n // Handles Observables that complete without emitting (e.g. EMPTY),\n // preventing the inner Observable from staying open indefinitely.\n subscriber.complete();\n },\n });\n\n // Cleanup subscription on unsubscribe (switchMap cancellation)\n return () => {\n asyncSub.unsubscribe();\n };\n });\n }),\n catchError((error) => {\n // Safety net — should not normally be reached since inner errors are caught\n const message = error instanceof Error ? error.message : String(error);\n context.logger.warn(`${LOG_PREFIX} Unexpected stream error for '${entry.fieldKey}': ${message}`);\n return EMPTY;\n }),\n );\n}\n","import { HttpClient } from '@angular/common/http';\nimport { computed, DestroyRef, inject, InjectionToken, Injector, isDevMode, isSignal, Signal, untracked } from '@angular/core';\nimport { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';\nimport { FieldTree } from '@angular/forms/signals';\nimport {\n auditTime,\n combineLatestWith,\n debounceTime,\n exhaustMap,\n filter,\n map,\n merge,\n of,\n pairwise,\n queueScheduler,\n scheduled,\n startWith,\n Subscription,\n switchMap,\n timer,\n} from 'rxjs';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { FORM_OPTIONS } from '../../models/field-signal-context.token';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { DEFAULT_DEBOUNCE_MS } from '../../utils/debounce/debounce';\nimport { getChangedKeys } from '../../utils/object-utils';\nimport { FunctionRegistryService } from '../registry';\nimport { applyDerivationsForTrigger } from './derivation-applicator';\nimport { collectDerivations } from './derivation-collector';\nimport { validateNoCycles } from './cycle-detector';\nimport { DerivationCollection, DerivationEntry } from './derivation-types';\nimport { DerivationLogger } from './derivation-logger.service';\nimport { DERIVATION_WARNING_TRACKER } from './derivation-warning-tracker';\nimport { createHttpDerivationStream, createStreamGuard, HttpDerivationStreamContext } from './http-derivation-stream';\nimport { createAsyncDerivationStream } from './async-derivation-stream';\n\n/**\n * Minimal configuration for creating a DerivationOrchestrator.\n * Only includes form-specific signals that cannot be injected.\n *\n * @internal\n */\nexport interface DerivationOrchestratorConfig {\n /** Signal containing the flattened schema fields */\n schemaFields: Signal<FieldDef<unknown>[] | undefined>;\n\n /** Signal containing the current form value */\n formValue: Signal<Record<string, unknown>>;\n\n /** Signal containing the form accessor */\n form: Signal<FieldTree<unknown>>;\n\n /** Signal containing the derivation logger */\n derivationLogger: Signal<DerivationLogger>;\n\n /** Signal containing external data signals for expression evaluation */\n externalData?: Signal<Record<string, Signal<unknown>> | undefined>;\n}\n\n/**\n * Orchestrates derivation processing for a dynamic form.\n *\n * Uses RxJS streams for reactive derivation processing:\n * - `exhaustMap` prevents re-entry during onChange derivation application\n * - `pairwise` tracks value changes without mutable state\n * - `takeUntilDestroyed` handles automatic cleanup\n *\n * Injects common services directly, requiring only form-specific signals in config.\n *\n * @public\n */\nexport class DerivationOrchestrator {\n private readonly config: DerivationOrchestratorConfig;\n private readonly injector = inject(Injector);\n private readonly destroyRef = inject(DestroyRef);\n private readonly logger = inject(DynamicFormLogger);\n private readonly warningTracker = inject(DERIVATION_WARNING_TRACKER);\n private readonly functionRegistry = inject(FunctionRegistryService);\n private readonly formOptions = inject(FORM_OPTIONS);\n private readonly httpClient = inject(HttpClient, { optional: true });\n\n /** Active HTTP derivation stream subscriptions */\n private httpSubscriptions: Subscription[] = [];\n\n /** Identity keys of current HTTP entries for smart teardown comparison */\n private lastHttpEntryKeys: Set<string> | null = null;\n\n /** Active async function derivation stream subscriptions */\n private asyncFunctionSubscriptions: Subscription[] = [];\n\n /** Identity keys of current async entries for smart teardown comparison */\n private lastAsyncEntryKeys: Set<string> | null = null;\n\n /**\n * Guard for detecting stale HTTP responses. Call `invalidate()` on teardown to cancel\n * in-flight requests from the previous generation. Each HTTP stream subscribes via\n * `takeUntil(guard$)` — when `invalidate()` fires, all in-flight requests are discarded.\n */\n private readonly streamGuard = createStreamGuard();\n\n /**\n * Computed signal containing the collected and validated derivations.\n * Returns null if no derivations are defined.\n */\n readonly derivationCollection: Signal<DerivationCollection | null>;\n\n constructor(config: DerivationOrchestratorConfig) {\n this.config = config;\n\n this.derivationCollection = computed<DerivationCollection | null>(() => {\n const fields = config.schemaFields();\n\n if (!fields || fields.length === 0) {\n return null;\n }\n\n const collection = collectDerivations(fields);\n\n if (collection.entries.length === 0) {\n return null;\n }\n\n validateNoCycles(collection, this.logger);\n this.warnAboutWildcardDependencies(collection.entries, fields.length);\n this.warnAboutMisconfiguredReEngagement(collection.entries);\n\n return collection;\n });\n\n this.setupOnChangeStream();\n this.setupDebouncedStream();\n this.setupHttpStreams();\n this.setupAsyncFunctionStreams();\n }\n\n private setupOnChangeStream(): void {\n const collection$ = toObservable(this.derivationCollection, { injector: this.injector });\n const formValue$ = toObservable(this.config.formValue, { injector: this.injector });\n const form$ = toObservable(this.config.form, { injector: this.injector });\n\n collection$\n .pipe(\n filter((collection): collection is DerivationCollection => collection !== null),\n combineLatestWith(formValue$, form$),\n\n // auditTime(0): Batch synchronous emissions from Angular's change detection.\n // When a single user action triggers multiple signal updates, this ensures\n // we only process derivations once after all updates complete (microtask timing).\n auditTime(0),\n\n // startWith + pairwise: Track previous and current values to detect changed fields.\n // This enables reEngageOnDependencyChange for onChange derivations.\n startWith(null as [DerivationCollection, Record<string, unknown>, FieldTree<unknown>] | null),\n pairwise(),\n filter((pair): pair is [(typeof pair)[0], [DerivationCollection, Record<string, unknown>, FieldTree<unknown>]] => pair[1] !== null),\n map(([previous, current]) => ({\n collection: current[0],\n formAccessor: current[2],\n changedFields: getChangedKeys(previous?.[1] ?? null, current[1]),\n })),\n\n // exhaustMap: Prevents re-entry while processing derivations.\n // If form value changes DURING derivation processing (from our own setValue calls),\n // we ignore those emissions and complete the current cycle first.\n // switchMap would cancel mid-processing, causing incomplete derivation chains.\n exhaustMap(({ collection, formAccessor, changedFields }) => {\n this.applyOnChangeDerivations(collection, formAccessor, changedFields);\n\n // scheduled with queueScheduler: Ensures the observable completes\n // in the next microtask, allowing exhaustMap to accept new emissions.\n // Without this, exhaustMap would block indefinitely.\n return scheduled([null], queueScheduler);\n }),\n\n takeUntilDestroyed(this.destroyRef),\n )\n .subscribe({\n error: (err) => this.logger.error('Derivation onChange stream error', err),\n });\n }\n\n private setupDebouncedStream(): void {\n toObservable(this.config.formValue, { injector: this.injector })\n .pipe(\n // debounceTime: Wait for value to stabilize before detecting changes.\n // Uses DEFAULT_DEBOUNCE_MS as the minimum debounce period.\n debounceTime(DEFAULT_DEBOUNCE_MS),\n\n // startWith + pairwise: Track previous and current values to detect changes.\n // startWith(null) ensures pairwise has an initial value to pair with.\n startWith(null as Record<string, unknown> | null),\n pairwise(),\n filter((pair): pair is [Record<string, unknown> | null, Record<string, unknown>] => pair[1] !== null),\n map(([previous, current]) => ({\n current,\n changedFields: getChangedKeys(previous, current),\n })),\n filter(({ changedFields }) => changedFields.size > 0),\n\n // switchMap: For debounced derivations, it's OK to cancel pending work\n // if new changes come in - we want the latest debounced values.\n // (Unlike onChange which uses exhaustMap to prevent cancellation)\n switchMap(({ changedFields }) => {\n const collection = untracked(() => this.derivationCollection());\n const formAccessor = untracked(() => this.config.form());\n\n if (!collection || !formAccessor) return of(null);\n\n // Get unique debounce periods from entries with trigger 'debounced'\n const debouncePeriods = this.getDebouncePeriods(collection.entries);\n if (debouncePeriods.length === 0) return of(null);\n\n // merge: Process multiple debounce periods concurrently.\n // Each period stream handles its own timing independently.\n const periodStreams = debouncePeriods.map((debounceMs) =>\n this.createPeriodStream(debounceMs, collection, formAccessor, changedFields),\n );\n\n return merge(...periodStreams);\n }),\n\n takeUntilDestroyed(this.destroyRef),\n )\n .subscribe({\n error: (err) => this.logger.error('Derivation debounced stream error', err),\n });\n }\n\n private createPeriodStream(\n debounceMs: number,\n collection: DerivationCollection,\n formAccessor: FieldTree<unknown>,\n changedFields: Set<string>,\n ) {\n const additionalWait = Math.max(0, debounceMs - DEFAULT_DEBOUNCE_MS);\n\n if (additionalWait === 0) {\n return of(null).pipe(\n map(() => {\n this.applyDebouncedEntriesForPeriod(debounceMs, collection, formAccessor, changedFields);\n }),\n );\n }\n\n return timer(additionalWait).pipe(\n map(() => {\n const currentCollection = untracked(() => this.derivationCollection());\n const currentFormAccessor = untracked(() => this.config.form());\n if (currentCollection && currentFormAccessor) {\n this.applyDebouncedEntriesForPeriod(debounceMs, currentCollection, currentFormAccessor, changedFields);\n }\n }),\n );\n }\n\n private applyOnChangeDerivations(collection: DerivationCollection, formAccessor: FieldTree<unknown>, changedFields?: Set<string>): void {\n const applicatorContext = {\n formValue: this.config.formValue,\n rootForm: formAccessor,\n derivationFunctions: this.functionRegistry.getDerivationFunctions(),\n customFunctions: this.functionRegistry.getCustomFunctions(),\n externalData: this.resolveExternalData(),\n logger: this.logger,\n warningTracker: this.warningTracker,\n derivationLogger: untracked(() => this.config.derivationLogger()),\n maxIterations: untracked(() => this.formOptions()?.maxDerivationIterations),\n };\n\n const result = applyDerivationsForTrigger(collection, 'onChange', applicatorContext, changedFields);\n\n if (result.maxIterationsReached) {\n this.logger.warn(\n `Derivation processing reached max iterations. ` +\n `This may indicate a loop in derivation logic that wasn't caught at build time. ` +\n `Applied: ${result.appliedCount}, Skipped: ${result.skippedCount}, Errors: ${result.errorCount}`,\n );\n }\n }\n\n private applyDebouncedEntriesForPeriod(\n debounceMs: number,\n collection: DerivationCollection,\n formAccessor: FieldTree<unknown>,\n changedFields?: Set<string>,\n ): void {\n // Filter entries to just those with the specific debounce period\n const debouncedEntries = collection.entries.filter(\n (entry) => entry.trigger === 'debounced' && (entry.debounceMs ?? DEFAULT_DEBOUNCE_MS) === debounceMs,\n );\n\n if (debouncedEntries.length === 0) {\n return;\n }\n\n // Create a minimal collection with filtered entries\n const filteredCollection: DerivationCollection = {\n entries: debouncedEntries,\n };\n\n const applicatorContext = {\n formValue: this.config.formValue,\n rootForm: formAccessor,\n derivationFunctions: this.functionRegistry.getDerivationFunctions(),\n customFunctions: this.functionRegistry.getCustomFunctions(),\n externalData: this.resolveExternalData(),\n logger: this.logger,\n warningTracker: this.warningTracker,\n derivationLogger: untracked(() => this.config.derivationLogger()),\n maxIterations: untracked(() => this.formOptions()?.maxDerivationIterations),\n };\n\n const result = applyDerivationsForTrigger(filteredCollection, 'debounced', applicatorContext, changedFields);\n\n if (result.maxIterationsReached) {\n this.logger.warn(\n `Debounced derivation processing reached max iterations (${debounceMs}ms). ` +\n `Applied: ${result.appliedCount}, Skipped: ${result.skippedCount}, Errors: ${result.errorCount}`,\n );\n }\n }\n\n /**\n * Sets up reactive HTTP derivation streams that react to collection changes.\n *\n * Subscribes to derivationCollection changes and creates per-entry HTTP streams.\n * Uses smart teardown: only recreates streams when HTTP entries actually change.\n */\n private setupHttpStreams(): void {\n toObservable(this.derivationCollection, { injector: this.injector })\n .pipe(takeUntilDestroyed(this.destroyRef))\n .subscribe((collection) => {\n const httpEntries = collection?.entries.filter((entry) => entry.http) ?? [];\n\n if (httpEntries.length === 0) {\n this.teardownHttpStreams();\n this.lastHttpEntryKeys = null;\n return;\n }\n\n // Smart teardown: compare entry identity keys to avoid redundant stream recreation\n const newKeys = this.computeHttpEntryKeys(httpEntries);\n if (this.lastHttpEntryKeys && this.setsEqual(this.lastHttpEntryKeys, newKeys)) {\n return; // No change in HTTP entries — keep existing streams\n }\n\n // Validate HttpClient availability\n if (!this.httpClient) {\n this.logger.error(\n 'HTTP Derivation - HttpClient is not available. ' + 'Ensure provideHttpClient() is included in your application providers.',\n );\n return;\n }\n\n // Tear down previous streams and create new ones\n this.teardownHttpStreams();\n this.lastHttpEntryKeys = newKeys;\n\n const formValue$ = toObservable(this.config.formValue, { injector: this.injector });\n\n for (const entry of httpEntries) {\n const context: HttpDerivationStreamContext = {\n formValue: this.config.formValue,\n form: this.config.form,\n httpClient: this.httpClient,\n logger: this.logger,\n derivationLogger: this.config.derivationLogger,\n customFunctions: () => this.functionRegistry.getCustomFunctions(),\n externalData: () => this.resolveExternalData(),\n warningTracker: this.warningTracker,\n guard$: this.streamGuard.guard$,\n };\n\n const stream = createHttpDerivationStream(entry, formValue$, context).pipe(takeUntilDestroyed(this.destroyRef));\n\n this.httpSubscriptions.push(\n stream.subscribe({\n error: (err) => this.logger.error(`HTTP Derivation - Stream error for '${entry.fieldKey}'`, err),\n }),\n );\n }\n });\n }\n\n /**\n * Tears down all active HTTP derivation streams. Invalidating the stream guard\n * cancels any in-flight HTTP responses from the old generation via `takeUntil`.\n */\n private teardownHttpStreams(): void {\n this.streamGuard.invalidate();\n for (const sub of this.httpSubscriptions) {\n sub.unsubscribe();\n }\n this.httpSubscriptions = [];\n }\n\n /**\n * Computes a set of identity keys for HTTP entries.\n * Used for smart teardown comparison.\n */\n private computeHttpEntryKeys(entries: DerivationEntry[]): Set<string> {\n return new Set(entries.map((entry) => `${entry.fieldKey}:${JSON.stringify(entry.http, Object.keys(entry.http ?? {}).sort())}`));\n }\n\n /**\n * Compares two sets for equality.\n */\n private setsEqual(a: Set<string>, b: Set<string>): boolean {\n if (a.size !== b.size) return false;\n for (const item of a) {\n if (!b.has(item)) return false;\n }\n return true;\n }\n\n /**\n * Sets up reactive async function derivation streams that react to collection changes.\n *\n * Subscribes to derivationCollection changes and creates per-entry async streams.\n * Uses smart teardown: only recreates streams when async entries actually change.\n */\n private setupAsyncFunctionStreams(): void {\n toObservable(this.derivationCollection, { injector: this.injector })\n .pipe(takeUntilDestroyed(this.destroyRef))\n .subscribe((collection) => {\n const asyncEntries = collection?.entries.filter((entry) => entry.asyncFunctionName) ?? [];\n\n if (asyncEntries.length === 0) {\n this.teardownAsyncFunctionStreams();\n this.lastAsyncEntryKeys = null;\n return;\n }\n\n // Smart teardown: compare entry identity keys to avoid redundant stream recreation\n const newKeys = this.computeAsyncEntryKeys(asyncEntries);\n if (this.lastAsyncEntryKeys && this.setsEqual(this.lastAsyncEntryKeys, newKeys)) {\n return; // No change in async entries — keep existing streams\n }\n\n // Tear down previous streams and create new ones\n this.teardownAsyncFunctionStreams();\n this.lastAsyncEntryKeys = newKeys;\n\n const formValue$ = toObservable(this.config.formValue, { injector: this.injector });\n\n for (const entry of asyncEntries) {\n const context = {\n formValue: this.config.formValue,\n form: this.config.form,\n logger: this.logger,\n derivationLogger: this.config.derivationLogger,\n customFunctions: () => this.functionRegistry.getCustomFunctions(),\n asyncDerivationFunctions: () => this.functionRegistry.getAsyncDerivationFunctions(),\n externalData: () => this.resolveExternalData(),\n warningTracker: this.warningTracker,\n };\n\n const stream = createAsyncDerivationStream(entry, formValue$, context).pipe(takeUntilDestroyed(this.destroyRef));\n\n this.asyncFunctionSubscriptions.push(\n stream.subscribe({\n error: (err) => this.logger.error(`Async Derivation - Stream error for '${entry.fieldKey}'`, err),\n }),\n );\n }\n });\n }\n\n /**\n * Tears down all active async function derivation streams.\n */\n private teardownAsyncFunctionStreams(): void {\n for (const sub of this.asyncFunctionSubscriptions) {\n sub.unsubscribe();\n }\n this.asyncFunctionSubscriptions = [];\n }\n\n /**\n * Computes a set of identity keys for async entries.\n * Used for smart teardown comparison.\n */\n private computeAsyncEntryKeys(entries: DerivationEntry[]): Set<string> {\n return new Set(\n entries.map((entry) => {\n const config = {\n asyncFunctionName: entry.asyncFunctionName,\n dependsOn: entry.dependsOn,\n debounceMs: entry.debounceMs,\n stopOnUserOverride: entry.stopOnUserOverride,\n reEngageOnDependencyChange: entry.reEngageOnDependencyChange,\n };\n return `${entry.fieldKey}:${JSON.stringify(config, Object.keys(config).sort())}`;\n }),\n );\n }\n\n /**\n * Gets all unique debounce periods from entries with trigger 'debounced'.\n */\n private getDebouncePeriods(entries: DerivationEntry[]): number[] {\n const periods = new Set<number>();\n for (const entry of entries) {\n if (entry.trigger === 'debounced') {\n periods.add(entry.debounceMs ?? DEFAULT_DEBOUNCE_MS);\n }\n }\n return Array.from(periods);\n }\n\n private warnAboutWildcardDependencies(entries: DerivationEntry[], fieldCount: number): void {\n if (!isDevMode()) return;\n\n // Find entries with wildcard dependency\n const wildcardEntries = entries.filter((entry) => entry.dependsOn.includes('*'));\n if (wildcardEntries.length === 0) return;\n\n // Find implicit wildcards (custom functions without explicit dependsOn)\n // HTTP and async entries are excluded because they require explicit dependsOn (validated at collection time)\n const implicitWildcards = wildcardEntries.filter(\n (entry) =>\n !entry.http &&\n !entry.asyncFunctionName &&\n entry.functionName &&\n (!entry.originalConfig?.dependsOn || entry.originalConfig.dependsOn.length === 0),\n );\n\n if (implicitWildcards.length > 0) {\n const derivationDescs = implicitWildcards.map((e) => `${e.fieldKey} (${e.functionName})`);\n\n this.logger.warn(\n '[Derivation] Derivations using custom functions without explicit dependsOn detected. ' +\n `These run on EVERY form change, which may impact performance (form has ${fieldCount} fields). ` +\n 'Consider specifying explicit dependsOn arrays for better performance.',\n derivationDescs,\n );\n }\n }\n\n /**\n * Warns about derivations with `reEngageOnDependencyChange: true` but without\n * `stopOnUserOverride: true`. The re-engagement flag only has an effect when\n * `stopOnUserOverride` is enabled — without it, `reEngageOnDependencyChange` is a no-op.\n */\n private warnAboutMisconfiguredReEngagement(entries: DerivationEntry[]): void {\n if (!isDevMode()) return;\n\n const misconfigured = entries.filter((entry) => entry.reEngageOnDependencyChange && !entry.stopOnUserOverride);\n if (misconfigured.length === 0) return;\n\n const fieldKeys = misconfigured.map((e) => e.debugName ?? e.fieldKey);\n this.logger.warn(\n '[Derivation] Derivations with reEngageOnDependencyChange but without stopOnUserOverride detected. ' +\n 'reEngageOnDependencyChange only takes effect when stopOnUserOverride is true. ' +\n 'Either add stopOnUserOverride: true or remove reEngageOnDependencyChange.',\n fieldKeys,\n );\n }\n\n /**\n * Resolves external data signals to their current values without creating dependencies.\n *\n * Uses `untracked()` to read signals without establishing reactive dependencies,\n * which is important for derivations that shouldn't re-trigger on every external data change.\n *\n * @returns Record of resolved external data values, or undefined if no external data.\n */\n private resolveExternalData(): Record<string, unknown> | undefined {\n const externalDataRecord = untracked(() => this.config.externalData?.());\n\n if (!externalDataRecord) {\n return undefined;\n }\n\n const resolved: Record<string, unknown> = {};\n for (const [key, signal] of Object.entries(externalDataRecord)) {\n if (isSignal(signal)) {\n resolved[key] = untracked(() => signal());\n } else {\n resolved[key] = signal;\n }\n }\n\n return resolved;\n }\n}\n\n/**\n * Creates a DerivationOrchestrator for a dynamic form.\n * Must be called within an injection context.\n *\n * @param config - Form-specific signals configuration\n * @returns The created DerivationOrchestrator\n *\n * @public\n */\nexport function createDerivationOrchestrator(config: DerivationOrchestratorConfig): DerivationOrchestrator {\n return new DerivationOrchestrator(config);\n}\n\n/**\n * Injection token for the DerivationOrchestrator.\n *\n * @public\n */\nexport const DERIVATION_ORCHESTRATOR = new InjectionToken<DerivationOrchestrator>('DERIVATION_ORCHESTRATOR');\n\n/**\n * Injects the DerivationOrchestrator from the current injection context.\n *\n * @returns The DerivationOrchestrator instance\n * @throws Error if called outside of an injection context or if orchestrator is not provided\n *\n * @public\n */\nexport function injectDerivationOrchestrator(): DerivationOrchestrator {\n return inject(DERIVATION_ORCHESTRATOR);\n}\n","import { Signal, untracked } from '@angular/core';\nimport { EvaluationContext } from '../../models/expressions/evaluation-context';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\n\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\nimport { parseArrayPath, resolveArrayPath, isArrayPlaceholderPath } from '../../utils/path-utils/path-utils';\nimport { CustomFunction } from '../expressions/custom-function-types';\nimport { evaluateCondition } from '../expressions/condition-evaluator';\nimport { ExpressionParser } from '../expressions/parser/expression-parser';\nimport { getNestedValue } from '../expressions/value-utils';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport { DerivationWarningTracker } from '../derivation/derivation-warning-tracker';\nimport { PropertyDerivationCollection, PropertyDerivationEntry } from './property-derivation-types';\nimport { PropertyOverrideStore } from './property-override-store';\n\n/**\n * Context required for applying property derivations.\n *\n * @public\n */\nexport interface PropertyDerivationApplicatorContext {\n /** The current form value (signal) */\n formValue: Signal<Record<string, unknown>>;\n\n /** The property override store to write to */\n store: PropertyOverrideStore;\n\n /** Registered derivation functions (used for property derivations with `functionName`) */\n derivationFunctions?: Record<string, CustomFunction>;\n\n /** Custom functions for expression evaluation */\n customFunctions?: Record<string, CustomFunction>;\n\n /** External data resolved from form config signals */\n externalData?: Record<string, unknown>;\n\n /** Logger for diagnostic output */\n logger: Logger;\n\n /** Warning tracker to prevent log spam */\n warningTracker?: DerivationWarningTracker;\n}\n\n/**\n * Result of property derivation processing.\n *\n * @public\n */\nexport interface PropertyDerivationProcessingResult {\n /** Number of property derivations successfully applied */\n appliedCount: number;\n /** Number of property derivations skipped */\n skippedCount: number;\n /** Number of property derivations that failed */\n errorCount: number;\n}\n\n/** @internal */\nconst ERROR_PREFIX = '[PropertyDerivation]';\n\n/**\n * Applies all property derivation entries from a collection.\n *\n * Single-pass processing — property derivations read formValue and write to the\n * property override store. No iterative refinement needed because property\n * derivations don't chain among themselves.\n *\n * @param collection - The collected property derivation entries\n * @param context - Context for applying property derivations\n * @param changedFields - Optional set of changed field keys for filtering\n * @returns Result of the processing\n *\n * @public\n */\nexport function applyPropertyDerivations(\n collection: PropertyDerivationCollection,\n context: PropertyDerivationApplicatorContext,\n changedFields?: Set<string>,\n): PropertyDerivationProcessingResult {\n let appliedCount = 0;\n let skippedCount = 0;\n let errorCount = 0;\n\n const entriesToProcess = changedFields ? getEntriesForChangedFields(collection.entries, changedFields) : collection.entries;\n\n for (const entry of entriesToProcess) {\n try {\n const applied = tryApplyPropertyDerivation(entry, context);\n if (applied) {\n appliedCount++;\n } else {\n skippedCount++;\n }\n } catch (error) {\n errorCount++;\n const errorMessage = error instanceof Error ? error.message : String(error);\n context.logger.error(\n `${ERROR_PREFIX} Failed to process property derivation (field: ${entry.fieldKey}, property: ${entry.targetProperty}): ${errorMessage}`,\n );\n }\n }\n\n return { appliedCount, skippedCount, errorCount };\n}\n\n/**\n * Applies property derivations filtered by trigger type.\n *\n * @param collection - The collected property derivation entries\n * @param trigger - The trigger type to filter by\n * @param context - Context for applying property derivations\n * @param changedFields - Optional set of changed field keys for filtering\n * @returns Result of the processing\n *\n * @public\n */\nexport function applyPropertyDerivationsForTrigger(\n collection: PropertyDerivationCollection,\n trigger: 'onChange' | 'debounced',\n context: PropertyDerivationApplicatorContext,\n changedFields?: Set<string>,\n): PropertyDerivationProcessingResult {\n const filteredEntries = collection.entries.filter((entry) => {\n if (trigger === 'onChange') {\n return !entry.trigger || entry.trigger === 'onChange';\n }\n return entry.trigger === trigger;\n });\n\n const filteredCollection: PropertyDerivationCollection = { entries: filteredEntries };\n return applyPropertyDerivations(filteredCollection, context, changedFields);\n}\n\n/**\n * Filters entries based on changed fields.\n *\n * @internal\n */\nfunction getEntriesForChangedFields(entries: PropertyDerivationEntry[], changedFields: Set<string>): PropertyDerivationEntry[] {\n return entries.filter((entry) => {\n if (entry.dependsOn.includes('*')) return true;\n return entry.dependsOn.some((dep) => changedFields.has(dep));\n });\n}\n\n/**\n * Attempts to apply a single property derivation entry.\n *\n * @returns true if the override was applied, false if skipped\n *\n * @internal\n */\nfunction tryApplyPropertyDerivation(entry: PropertyDerivationEntry, context: PropertyDerivationApplicatorContext): boolean {\n // Handle array field derivations\n if (isArrayPlaceholderPath(entry.fieldKey)) {\n return tryApplyArrayPropertyDerivation(entry, context);\n }\n\n const formValue = untracked(() => context.formValue());\n const evalContext = createEvaluationContext(entry, formValue, context);\n\n // Evaluate condition\n if (!evaluatePropertyCondition(entry.condition, evalContext)) {\n return false;\n }\n\n // Compute the derived property value\n const newValue = computePropertyValue(entry, evalContext, context);\n\n // Write to the store\n context.store.setOverride(entry.fieldKey, entry.targetProperty, newValue);\n return true;\n}\n\n/**\n * Handles array field property derivations with '$' placeholder.\n *\n * @internal\n */\nfunction tryApplyArrayPropertyDerivation(entry: PropertyDerivationEntry, context: PropertyDerivationApplicatorContext): boolean {\n const formValue = untracked(() => context.formValue());\n\n const pathInfo = parseArrayPath(entry.fieldKey);\n if (!pathInfo.isArrayPath) {\n return false;\n }\n\n const { arrayPath } = pathInfo;\n const arrayValue = getNestedValue(formValue, arrayPath);\n if (!Array.isArray(arrayValue)) {\n return false;\n }\n\n let appliedAny = false;\n\n for (let i = 0; i < arrayValue.length; i++) {\n const resolvedPath = resolveArrayPath(entry.fieldKey, i);\n const arrayItem = arrayValue[i] as Record<string, unknown>;\n const evalContext = createArrayItemEvaluationContext(entry, arrayItem, formValue, i, arrayPath, context);\n\n if (!evaluatePropertyCondition(entry.condition, evalContext)) {\n continue;\n }\n\n try {\n const newValue = computePropertyValue(entry, evalContext, context);\n context.store.setOverride(resolvedPath, entry.targetProperty, newValue);\n appliedAny = true;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n context.logger.error(\n `${ERROR_PREFIX} Failed to compute property derivation (field: ${entry.fieldKey}, property: ${entry.targetProperty}, index: ${i}): ${errorMessage}`,\n );\n }\n }\n\n return appliedAny;\n}\n\n/**\n * Creates an evaluation context for property derivation processing.\n *\n * @internal\n */\nfunction createEvaluationContext(\n entry: PropertyDerivationEntry,\n formValue: Record<string, unknown>,\n context: PropertyDerivationApplicatorContext,\n): EvaluationContext {\n const fieldValue = getNestedValue(formValue, entry.fieldKey);\n\n return {\n fieldValue,\n formValue,\n fieldPath: entry.fieldKey,\n customFunctions: context.customFunctions,\n externalData: context.externalData,\n logger: context.logger,\n };\n}\n\n/**\n * Creates an evaluation context scoped to a specific array item.\n *\n * @internal\n */\nfunction createArrayItemEvaluationContext(\n entry: PropertyDerivationEntry,\n arrayItem: Record<string, unknown>,\n rootFormValue: Record<string, unknown>,\n itemIndex: number,\n arrayPath: string,\n context: PropertyDerivationApplicatorContext,\n): EvaluationContext {\n return {\n fieldValue: arrayItem,\n formValue: arrayItem,\n fieldPath: `${arrayPath}.${itemIndex}`,\n customFunctions: context.customFunctions,\n externalData: context.externalData,\n logger: context.logger,\n rootFormValue,\n arrayIndex: itemIndex,\n arrayPath,\n };\n}\n\n/**\n * Evaluates the property derivation condition.\n *\n * @internal\n */\nfunction evaluatePropertyCondition(condition: ConditionalExpression | boolean, context: EvaluationContext): boolean {\n if (typeof condition === 'boolean') {\n return condition;\n }\n return evaluateCondition(condition, context);\n}\n\n/**\n * Computes the derived property value based on the entry configuration.\n *\n * @internal\n */\nfunction computePropertyValue(\n entry: PropertyDerivationEntry,\n evalContext: EvaluationContext,\n applicatorContext: PropertyDerivationApplicatorContext,\n): unknown {\n // Static value\n if (entry.value !== undefined) {\n return entry.value;\n }\n\n // Expression\n if (entry.expression) {\n return ExpressionParser.evaluate(entry.expression, evalContext);\n }\n\n // Custom function\n if (entry.functionName) {\n const fn = applicatorContext.derivationFunctions?.[entry.functionName];\n if (!fn) {\n throw new DynamicFormError(`Property derivation function '${entry.functionName}' not found in customFnConfig.derivations`);\n }\n return fn(evalContext);\n }\n\n throw new DynamicFormError(\n `Property derivation for ${entry.fieldKey}.${entry.targetProperty} has no value source. ` +\n `Specify 'value', 'expression', or 'functionName'.`,\n );\n}\n","/**\n * Sentinel value for the `$` placeholder index used in registration keys.\n *\n * The property derivation system uses two key formats for array fields:\n * - **Placeholder format** (`items.$.email`) — used by the collector/orchestrator to register\n * derivations and by the fast-path `hasField()` check. The `$` acts as a wildcard\n * representing \"any index\".\n * - **Concrete format** (`items.0.email`) — used at render time to look up overrides\n * for a specific array item.\n *\n * Pass `PLACEHOLDER_INDEX` as the `index` parameter to produce the placeholder format.\n *\n * @public\n */\nexport const PLACEHOLDER_INDEX = '$' as const;\n\n/**\n * Builds a property override store key for a field.\n *\n * For non-array fields, the key is just the field's key.\n * For array item fields, the key includes the array path and either a concrete\n * index (e.g., `contacts.0.email`) or the `$` placeholder (e.g., `contacts.$.email`).\n *\n * @param arrayKey - The array field key (e.g., 'contacts'), or undefined for non-array fields\n * @param index - The array item index, `PLACEHOLDER_INDEX` for the wildcard format, or undefined for non-array fields\n * @param fieldKey - The leaf field key (e.g., 'email')\n * @returns The store key (e.g., 'email', 'contacts.0.email', or 'contacts.$.email')\n *\n * @public\n */\nexport function buildPropertyOverrideKey(\n arrayKey: string | undefined,\n index: number | typeof PLACEHOLDER_INDEX | undefined,\n fieldKey: string,\n): string {\n if (arrayKey != null && index != null) {\n return `${arrayKey}.${index}.${fieldKey}`;\n }\n return fieldKey;\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { FieldWithValidation } from '../../definitions/base/field-with-validation';\nimport { DerivationLogicConfig, isDerivationLogicConfig, hasTargetProperty } from '../../models/logic/logic-config';\nimport { hasChildFields } from '../../models/types/type-guards';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport { DeprecationWarningTracker } from '../../utils/deprecation-warning-tracker';\nimport { normalizeFieldsArray } from '../../utils/object-utils';\nimport { extractExpressionDependencies, extractStringDependencies } from '../cross-field/cross-field-detector';\nimport { buildPropertyOverrideKey, PLACEHOLDER_INDEX } from './property-override-key';\nimport { PropertyDerivationCollection, PropertyDerivationEntry } from './property-derivation-types';\n\n/**\n * Context for collecting property derivations, tracking array path for relative references.\n *\n * @internal\n */\ninterface CollectionContext {\n /** Current array path for resolving relative field references. */\n arrayPath?: string;\n logger: Logger;\n tracker: DeprecationWarningTracker;\n}\n\n/**\n * Collects all property derivation entries from field definitions.\n *\n * Traverses the field definition tree and extracts `type: 'derivation'` with `targetProperty`\n * entries from each field's `logic` array.\n *\n * No topological sort is needed because property derivations don't chain —\n * they read formValue and write to the property override store.\n *\n * @param fields - Array of field definitions to traverse\n * @returns Collection containing property derivation entries\n *\n * @public\n */\nexport function collectPropertyDerivations(\n fields: FieldDef<unknown>[],\n logger: Logger,\n tracker: DeprecationWarningTracker,\n): PropertyDerivationCollection {\n const entries: PropertyDerivationEntry[] = [];\n const context: CollectionContext = { logger, tracker };\n\n traverseFields(fields, entries, context);\n\n return { entries };\n}\n\n/**\n * Recursively traverses field definitions to collect property derivations.\n *\n * @internal\n */\nfunction traverseFields(fields: FieldDef<unknown>[], entries: PropertyDerivationEntry[], context: CollectionContext): void {\n for (const field of fields) {\n collectFromField(field, entries, context);\n\n // Recursively process container fields (page, row, group, array)\n if (hasChildFields(field)) {\n const childContext = { ...context };\n\n if (field.type === 'array') {\n childContext.arrayPath = field.key;\n\n const arrayItems = normalizeFieldsArray(field.fields) as (FieldDef<unknown> | FieldDef<unknown>[])[];\n const normalizedChildren: FieldDef<unknown>[] = [];\n\n for (const item of arrayItems) {\n if (Array.isArray(item)) {\n normalizedChildren.push(...item);\n } else {\n normalizedChildren.push(item);\n }\n }\n\n traverseFields(normalizedChildren, entries, childContext);\n } else {\n traverseFields(normalizeFieldsArray(field.fields) as FieldDef<unknown>[], entries, childContext);\n }\n }\n }\n}\n\n/**\n * Collects property derivation entries from a single field.\n *\n * @internal\n */\nfunction collectFromField(field: FieldDef<unknown>, entries: PropertyDerivationEntry[], context: CollectionContext): void {\n const fieldKey = field.key;\n if (!fieldKey) return;\n\n const validationField = field as FieldDef<unknown> & FieldWithValidation;\n\n if (validationField.logic) {\n for (const logicConfig of validationField.logic) {\n if (isDerivationLogicConfig(logicConfig) && hasTargetProperty(logicConfig)) {\n const entry = createPropertyDerivationEntryFromDerivation(fieldKey, logicConfig, context);\n entries.push(entry);\n }\n }\n }\n}\n\n/**\n * Creates a property derivation entry from a `DerivationLogicConfig` that has `targetProperty`.\n *\n * This handles the new unified path where `type: 'derivation'` configs with `targetProperty`\n * are routed to the property derivation pipeline.\n *\n * @internal\n */\nfunction createPropertyDerivationEntryFromDerivation(\n fieldKey: string,\n config: DerivationLogicConfig & { targetProperty: string },\n context: CollectionContext,\n): PropertyDerivationEntry {\n const effectiveFieldKey = buildPropertyOverrideKey(context.arrayPath, context.arrayPath ? PLACEHOLDER_INDEX : undefined, fieldKey);\n const dependsOn = extractDependencies(config);\n const condition = config.condition ?? true;\n const trigger = config.trigger ?? 'onChange';\n const debounceMs = trigger === 'debounced' ? (config as { debounceMs?: number }).debounceMs : undefined;\n\n return {\n fieldKey: effectiveFieldKey,\n targetProperty: config.targetProperty,\n dependsOn,\n condition,\n value: config.value,\n expression: config.expression,\n functionName: config.functionName,\n trigger,\n debounceMs,\n debugName: config.debugName,\n originalConfig: config,\n };\n}\n\n/**\n * Extracts all field dependencies from a property derivation config.\n *\n * @internal\n */\nfunction extractDependencies(config: DerivationLogicConfig): string[] {\n const deps = new Set<string>();\n\n if (config.dependsOn && config.dependsOn.length > 0) {\n config.dependsOn.forEach((dep) => deps.add(dep));\n } else {\n if (config.expression) {\n const exprDeps = extractStringDependencies(config.expression);\n exprDeps.forEach((dep) => deps.add(dep));\n }\n\n if (config.functionName) {\n deps.add('*');\n }\n }\n\n // Always extract from condition\n if (config.condition && config.condition !== true) {\n const conditionDeps = extractExpressionDependencies(config.condition);\n conditionDeps.forEach((dep) => deps.add(dep));\n }\n\n return Array.from(deps);\n}\n","import { computed, DestroyRef, inject, InjectionToken, Injector, isDevMode, isSignal, Signal, untracked } from '@angular/core';\nimport { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport {\n auditTime,\n combineLatestWith,\n debounceTime,\n exhaustMap,\n filter,\n map,\n merge,\n of,\n pairwise,\n queueScheduler,\n scheduled,\n startWith,\n switchMap,\n timer,\n} from 'rxjs';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { FORM_OPTIONS } from '../../models/field-signal-context.token';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { DEFAULT_DEBOUNCE_MS } from '../../utils/debounce/debounce';\nimport { getChangedKeys } from '../../utils/object-utils';\nimport { FunctionRegistryService } from '../registry';\nimport { DERIVATION_WARNING_TRACKER } from '../derivation/derivation-warning-tracker';\nimport { DEPRECATION_WARNING_TRACKER } from '../../utils/deprecation-warning-tracker';\nimport { applyPropertyDerivationsForTrigger } from './property-derivation-applicator';\nimport { collectPropertyDerivations } from './property-derivation-collector';\nimport { PropertyDerivationCollection, PropertyDerivationEntry } from './property-derivation-types';\nimport { PropertyOverrideStore } from './property-override-store';\n\n/**\n * Configuration for creating a PropertyDerivationOrchestrator.\n *\n * @internal\n */\nexport interface PropertyDerivationOrchestratorConfig {\n /** Signal from stateManager.formSetup()?.schemaFields */\n schemaFields: Signal<FieldDef<unknown>[] | undefined>;\n\n /** Signal from stateManager.formValue */\n formValue: Signal<Record<string, unknown>>;\n\n /** The property override store instance */\n store: PropertyOverrideStore;\n\n /** Signal from stateManager.activeConfig()?.externalData */\n externalData?: Signal<Record<string, Signal<unknown>> | undefined>;\n}\n\n/**\n * Orchestrates property derivation processing for a dynamic form.\n *\n * Uses the same reactive stream pattern as DerivationOrchestrator:\n * - `exhaustMap` prevents re-entry during onChange processing\n * - `pairwise` tracks value changes without mutable state\n * - `takeUntilDestroyed` handles automatic cleanup\n *\n * @public\n */\nexport class PropertyDerivationOrchestrator {\n private readonly config: PropertyDerivationOrchestratorConfig;\n private readonly injector = inject(Injector);\n private readonly destroyRef = inject(DestroyRef);\n private readonly logger = inject(DynamicFormLogger);\n private readonly warningTracker = inject(DERIVATION_WARNING_TRACKER);\n private readonly deprecationTracker = inject(DEPRECATION_WARNING_TRACKER);\n private readonly functionRegistry = inject(FunctionRegistryService);\n private readonly formOptions = inject(FORM_OPTIONS);\n\n /**\n * Computed signal containing the collected property derivations.\n * Returns null if no property derivations are defined.\n */\n readonly propertyDerivationCollection: Signal<PropertyDerivationCollection | null>;\n\n constructor(config: PropertyDerivationOrchestratorConfig) {\n this.config = config;\n\n // Pure computed — no side effects. Just derives the collection from schema fields.\n this.propertyDerivationCollection = computed<PropertyDerivationCollection | null>(() => {\n const fields = config.schemaFields();\n\n if (!fields || fields.length === 0) {\n return null;\n }\n\n const collection = collectPropertyDerivations(fields, this.logger, this.deprecationTracker);\n\n if (collection.entries.length === 0) {\n return null;\n }\n\n return collection;\n });\n\n // Side effects react to collection changes: clear the store, register fields, warn.\n // schemaFields is included in the dependency array to ensure the field count is always\n // in sync with the collection (avoids reading a stale value via untracked).\n explicitEffect([this.propertyDerivationCollection, this.config.schemaFields], ([collection, fields]) => {\n config.store.clear();\n\n if (!collection) return;\n\n for (const entry of collection.entries) {\n config.store.registerField(entry.fieldKey);\n }\n\n this.warnAboutWildcardDependencies(collection.entries, fields?.length ?? 0);\n });\n\n this.setupOnChangeStream();\n this.setupDebouncedStream();\n }\n\n private setupOnChangeStream(): void {\n const collection$ = toObservable(this.propertyDerivationCollection, { injector: this.injector });\n const formValue$ = toObservable(this.config.formValue, { injector: this.injector });\n\n collection$\n .pipe(\n filter((collection): collection is PropertyDerivationCollection => collection !== null),\n combineLatestWith(formValue$),\n auditTime(0),\n exhaustMap(([collection]) => {\n this.applyOnChangePropertyDerivations(collection);\n return scheduled([null], queueScheduler);\n }),\n takeUntilDestroyed(this.destroyRef),\n )\n .subscribe({\n error: (err) => this.logger.error('Property derivation onChange stream error', err),\n });\n }\n\n private setupDebouncedStream(): void {\n toObservable(this.config.formValue, { injector: this.injector })\n .pipe(\n debounceTime(DEFAULT_DEBOUNCE_MS),\n startWith(null as Record<string, unknown> | null),\n pairwise(),\n filter((pair): pair is [Record<string, unknown> | null, Record<string, unknown>] => pair[1] !== null),\n map(([previous, current]) => ({\n current,\n changedFields: getChangedKeys(previous, current),\n })),\n filter(({ changedFields }) => changedFields.size > 0),\n switchMap(({ changedFields }) => {\n const collection = untracked(() => this.propertyDerivationCollection());\n if (!collection) return of(null);\n\n const debouncePeriods = this.getDebouncePeriods(collection.entries);\n if (debouncePeriods.length === 0) return of(null);\n\n const periodStreams = debouncePeriods.map((debounceMs) => this.createPeriodStream(debounceMs, collection, changedFields));\n\n return merge(...periodStreams);\n }),\n takeUntilDestroyed(this.destroyRef),\n )\n .subscribe({\n error: (err) => this.logger.error('Property derivation debounced stream error', err),\n });\n }\n\n private createPeriodStream(debounceMs: number, collection: PropertyDerivationCollection, changedFields: Set<string>) {\n const additionalWait = Math.max(0, debounceMs - DEFAULT_DEBOUNCE_MS);\n\n return timer(additionalWait).pipe(\n map(() => {\n // For periods beyond DEFAULT_DEBOUNCE_MS, re-read collection as it may have changed during the wait.\n // For zero-wait periods, use the original collection directly since no time has elapsed.\n const currentCollection = additionalWait > 0 ? (untracked(() => this.propertyDerivationCollection()) ?? collection) : collection;\n this.applyDebouncedEntriesForPeriod(debounceMs, currentCollection, changedFields);\n }),\n );\n }\n\n private applyOnChangePropertyDerivations(collection: PropertyDerivationCollection): void {\n const applicatorContext = {\n formValue: this.config.formValue,\n store: this.config.store,\n derivationFunctions: this.functionRegistry.getDerivationFunctions(),\n customFunctions: this.functionRegistry.getCustomFunctions(),\n externalData: this.resolveExternalData(),\n logger: this.logger,\n warningTracker: this.warningTracker,\n };\n\n applyPropertyDerivationsForTrigger(collection, 'onChange', applicatorContext);\n }\n\n private applyDebouncedEntriesForPeriod(debounceMs: number, collection: PropertyDerivationCollection, changedFields?: Set<string>): void {\n const debouncedEntries = collection.entries.filter(\n (entry) => entry.trigger === 'debounced' && (entry.debounceMs ?? DEFAULT_DEBOUNCE_MS) === debounceMs,\n );\n\n if (debouncedEntries.length === 0) return;\n\n const filteredCollection: PropertyDerivationCollection = { entries: debouncedEntries };\n\n const applicatorContext = {\n formValue: this.config.formValue,\n store: this.config.store,\n derivationFunctions: this.functionRegistry.getDerivationFunctions(),\n customFunctions: this.functionRegistry.getCustomFunctions(),\n externalData: this.resolveExternalData(),\n logger: this.logger,\n warningTracker: this.warningTracker,\n };\n\n applyPropertyDerivationsForTrigger(filteredCollection, 'debounced', applicatorContext, changedFields);\n }\n\n private getDebouncePeriods(entries: PropertyDerivationEntry[]): number[] {\n const periods = new Set<number>();\n for (const entry of entries) {\n if (entry.trigger === 'debounced') {\n periods.add(entry.debounceMs ?? DEFAULT_DEBOUNCE_MS);\n }\n }\n return Array.from(periods);\n }\n\n private warnAboutWildcardDependencies(entries: PropertyDerivationEntry[], fieldCount: number): void {\n if (!isDevMode()) return;\n\n const implicitWildcards = entries.filter(\n (entry) =>\n entry.dependsOn.includes('*') &&\n entry.functionName &&\n (!entry.originalConfig?.dependsOn || entry.originalConfig.dependsOn.length === 0),\n );\n\n if (implicitWildcards.length > 0) {\n const derivationDescs = implicitWildcards.map((e) => `${e.fieldKey}.${e.targetProperty} (${e.functionName})`);\n\n this.logger.warn(\n '[PropertyDerivation] Property derivations using custom functions without explicit dependsOn detected. ' +\n `These run on EVERY form change, which may impact performance (form has ${fieldCount} fields). ` +\n 'Consider specifying explicit dependsOn arrays for better performance.',\n derivationDescs,\n );\n }\n }\n\n /**\n * Resolves external data signals to their current values.\n *\n * Called on every onChange and debounced application. Each call iterates all\n * external data entries and resolves signals via untracked(). For forms with\n * many external data entries, this could be optimized by caching the resolved\n * record and only invalidating when external data signal values change.\n * In practice, external data entries are few, so the linear scan is acceptable.\n */\n private resolveExternalData(): Record<string, unknown> | undefined {\n const externalDataRecord = untracked(() => this.config.externalData?.());\n\n if (!externalDataRecord) return undefined;\n\n const resolved: Record<string, unknown> = {};\n for (const [key, signalValue] of Object.entries(externalDataRecord)) {\n if (isSignal(signalValue)) {\n resolved[key] = untracked(() => signalValue());\n } else {\n resolved[key] = signalValue;\n }\n }\n\n return resolved;\n }\n}\n\n/**\n * Creates a PropertyDerivationOrchestrator for a dynamic form.\n * Must be called within an injection context.\n *\n * @param config - Form-specific signals configuration\n * @returns The created PropertyDerivationOrchestrator\n *\n * @public\n */\nexport function createPropertyDerivationOrchestrator(config: PropertyDerivationOrchestratorConfig): PropertyDerivationOrchestrator {\n return new PropertyDerivationOrchestrator(config);\n}\n\n/**\n * Injection token for the PropertyDerivationOrchestrator.\n *\n * @public\n */\nexport const PROPERTY_DERIVATION_ORCHESTRATOR = new InjectionToken<PropertyDerivationOrchestrator>('PROPERTY_DERIVATION_ORCHESTRATOR');\n","import { FormEvent } from '../interfaces/form-event';\n\nexport class NextPageEvent implements FormEvent {\n readonly type = 'next-page' as const;\n}\n","import { FormEvent } from '../interfaces/form-event';\n\nexport class PageChangeEvent implements FormEvent {\n readonly type = 'page-change' as const;\n\n constructor(\n /** The current page index (0-based) */\n public readonly currentPageIndex: number,\n /** Total number of pages */\n public readonly totalPages: number,\n /** Previous page index (0-based), undefined if first navigation */\n public readonly previousPageIndex?: number,\n ) {}\n}\n","import { FormEvent } from '../interfaces/form-event';\n\nexport class PreviousPageEvent implements FormEvent {\n readonly type = 'previous-page' as const;\n}\n","import { FormEvent } from '../interfaces/form-event';\n\n/**\n * Event dispatched when the form should be reset to its default values.\n *\n * This event instructs the dynamic form component to restore all field values\n * to their initial default values as defined in the form configuration.\n *\n * @example\n * ```typescript\n * // Dispatch from a button component\n * eventBus.dispatch(FormResetEvent);\n * ```\n *\n * @example\n * ```typescript\n * // Listen for reset events\n * eventBus.on<FormResetEvent>('form-reset').subscribe(() => {\n * console.log('Form was reset to defaults');\n * });\n * ```\n */\nexport class FormResetEvent implements FormEvent {\n readonly type = 'form-reset' as const;\n}\n","import { FormEvent } from '../interfaces/form-event';\n\n/**\n * Event dispatched when the form should be cleared.\n *\n * This event instructs the dynamic form component to clear all field values,\n * resetting them to empty/undefined state regardless of their default values.\n *\n * @example\n * ```typescript\n * // Dispatch from a button component\n * eventBus.dispatch(FormClearEvent);\n * ```\n *\n * @example\n * ```typescript\n * // Listen for clear events\n * eventBus.on<FormClearEvent>('form-clear').subscribe(() => {\n * console.log('Form was cleared');\n * });\n * ```\n */\nexport class FormClearEvent implements FormEvent {\n readonly type = 'form-clear' as const;\n}\n","import { FormEvent } from '../interfaces/form-event';\nimport { ArrayItemDefinition, ArrayItemTemplate } from '../../definitions/default/array-field';\n\n/**\n * Template type for array items used in events.\n * Canonical definition lives in {@link ArrayItemDefinition} — this alias\n * preserves the events-specific naming convention.\n */\nexport type ArrayItemDefinitionTemplate = ArrayItemDefinition;\n\n// Re-export the canonical ArrayItemTemplate for backwards-compatible event API surface\nexport type { ArrayItemTemplate };\n\n/**\n * Event dispatched to append a new item at the END of an array field.\n *\n * This is the most common array operation - adding items to the end.\n * For other positions, use {@link PrependArrayItemEvent} or {@link InsertArrayItemEvent}.\n *\n * @example\n * ```typescript\n * // Object item: append { name, email } object\n * eventBus.dispatch(arrayEvent('contacts').append([\n * { key: 'name', type: 'input', label: 'Name' },\n * { key: 'email', type: 'input', label: 'Email' }\n * ]));\n *\n * // Primitive item: append single value\n * eventBus.dispatch(arrayEvent('tags').append(\n * { key: 'tag', type: 'input', label: 'Tag' }\n * ));\n * ```\n *\n * @typeParam TTemplate - The type of the template (single field or array of fields)\n */\nexport class AppendArrayItemEvent<TTemplate extends ArrayItemDefinitionTemplate = ArrayItemDefinitionTemplate> implements FormEvent {\n readonly type = 'append-array-item' as const;\n\n constructor(\n /** The key of the array field to append an item to */\n public readonly arrayKey: string,\n /**\n * Template for the new array item. REQUIRED.\n * - Single field (FieldDef): Creates a primitive item (field's value is extracted directly)\n * - Array of fields (FieldDef[]): Creates an object item (fields merged into object)\n */\n public readonly template: TTemplate,\n ) {}\n}\n","import { FormEvent } from '../interfaces/form-event';\nimport { ArrayItemDefinitionTemplate } from './append-array-item.event';\n\n/**\n * Event dispatched to prepend a new item at the BEGINNING of an array field.\n *\n * Use this when new items should appear at the start of the list.\n * For appending to the end, use {@link AppendArrayItemEvent}.\n *\n * @example\n * ```typescript\n * // Object item: prepend { name } object\n * eventBus.dispatch(arrayEvent('contacts').prepend([\n * { key: 'name', type: 'input', label: 'Name' }\n * ]));\n *\n * // Primitive item: prepend single value\n * eventBus.dispatch(arrayEvent('tags').prepend(\n * { key: 'tag', type: 'input', label: 'Tag' }\n * ));\n * ```\n *\n * @typeParam TTemplate - The type of the template (single field or array of fields)\n */\nexport class PrependArrayItemEvent<TTemplate extends ArrayItemDefinitionTemplate = ArrayItemDefinitionTemplate> implements FormEvent {\n readonly type = 'prepend-array-item' as const;\n\n constructor(\n /** The key of the array field to prepend an item to */\n public readonly arrayKey: string,\n /**\n * Template for the new array item. REQUIRED.\n * - Single field (FieldDef): Creates a primitive item (field's value is extracted directly)\n * - Array of fields (FieldDef[]): Creates an object item (fields merged into object)\n */\n public readonly template: TTemplate,\n ) {}\n}\n","import { FormEvent } from '../interfaces/form-event';\nimport { ArrayItemDefinitionTemplate } from './append-array-item.event';\n\n/**\n * Event dispatched to insert a new item at a SPECIFIC INDEX in an array field.\n *\n * Use this when you need precise control over where the new item appears.\n * For simpler operations, use {@link AppendArrayItemEvent} or {@link PrependArrayItemEvent}.\n *\n * @example\n * ```typescript\n * // Object item: insert { name } object at index 2\n * eventBus.dispatch(arrayEvent('contacts').insertAt(2, [\n * { key: 'name', type: 'input', label: 'Name' }\n * ]));\n *\n * // Primitive item: insert single value at index 2\n * eventBus.dispatch(arrayEvent('tags').insertAt(2,\n * { key: 'tag', type: 'input', label: 'Tag' }\n * ));\n * ```\n *\n * @typeParam TTemplate - The type of the template (single field or array of fields)\n */\nexport class InsertArrayItemEvent<TTemplate extends ArrayItemDefinitionTemplate = ArrayItemDefinitionTemplate> implements FormEvent {\n readonly type = 'insert-array-item' as const;\n\n constructor(\n /** The key of the array field to insert an item into */\n public readonly arrayKey: string,\n /** The index at which to insert the new item */\n public readonly index: number,\n /**\n * Template for the new array item. REQUIRED.\n * - Single field (FieldDef): Creates a primitive item (field's value is extracted directly)\n * - Array of fields (FieldDef[]): Creates an object item (fields merged into object)\n */\n public readonly template: TTemplate,\n ) {}\n}\n","import { FormEvent } from '../interfaces/form-event';\n\n/**\n * Event dispatched to remove the LAST item from an array field.\n *\n * Equivalent to JavaScript's `Array.pop()` - removes from the end.\n * For removing from the beginning, use {@link ShiftArrayItemEvent}.\n * For removing at a specific index, use {@link RemoveAtIndexEvent}.\n *\n * @example\n * ```typescript\n * // Use the builder API (recommended)\n * eventBus.dispatch(arrayEvent('contacts').pop());\n *\n * // Or instantiate directly\n * eventBus.dispatch(new PopArrayItemEvent('contacts'));\n * ```\n */\nexport class PopArrayItemEvent implements FormEvent {\n readonly type = 'pop-array-item' as const;\n\n constructor(\n /** The key of the array field to remove the last item from */\n public readonly arrayKey: string,\n ) {}\n}\n","import { FormEvent } from '../interfaces/form-event';\n\n/**\n * Event dispatched to remove the FIRST item from an array field.\n *\n * Equivalent to JavaScript's `Array.shift()` - removes from the beginning.\n * For removing from the end, use {@link PopArrayItemEvent}.\n * For removing at a specific index, use {@link RemoveAtIndexEvent}.\n *\n * @example\n * ```typescript\n * // Use the builder API (recommended)\n * eventBus.dispatch(arrayEvent('contacts').shift());\n *\n * // Or instantiate directly\n * eventBus.dispatch(new ShiftArrayItemEvent('contacts'));\n * ```\n */\nexport class ShiftArrayItemEvent implements FormEvent {\n readonly type = 'shift-array-item' as const;\n\n constructor(\n /** The key of the array field to remove the first item from */\n public readonly arrayKey: string,\n ) {}\n}\n","import { FormEvent } from '../interfaces/form-event';\n\n/**\n * Event dispatched to move an existing item from one index to another within an array field.\n *\n * This is an atomic reorder operation — the item at `fromIndex` is removed and\n * reinserted at `toIndex`. No template is required because the existing item\n * (resolved component, form value, and stored template) is preserved.\n *\n * @example\n * ```typescript\n * // Use the builder API (recommended)\n * eventBus.dispatch(arrayEvent('contacts').move(0, 2));\n *\n * // Or instantiate directly\n * eventBus.dispatch(new MoveArrayItemEvent('contacts', 0, 2));\n * ```\n */\nexport class MoveArrayItemEvent implements FormEvent {\n readonly type = 'move-array-item' as const;\n\n constructor(\n /** The key of the array field containing the item to move */\n public readonly arrayKey: string,\n /** The current index of the item to move */\n public readonly fromIndex: number,\n /** The target index to move the item to */\n public readonly toIndex: number,\n ) {}\n}\n","import { FormEvent } from '../interfaces/form-event';\n\n/**\n * Event dispatched to remove an item at a SPECIFIC INDEX from an array field.\n *\n * Use this when you need precise control over which item to remove.\n * For simpler operations, use {@link PopArrayItemEvent} or {@link ShiftArrayItemEvent}.\n *\n * @example\n * ```typescript\n * // Use the builder API (recommended)\n * eventBus.dispatch(arrayEvent('contacts').removeAt(2));\n *\n * // Or instantiate directly\n * eventBus.dispatch(new RemoveAtIndexEvent('contacts', 2));\n * ```\n */\nexport class RemoveAtIndexEvent implements FormEvent {\n readonly type = 'remove-at-index' as const;\n\n constructor(\n /** The key of the array field to remove an item from */\n public readonly arrayKey: string,\n /** The index of the item to remove */\n public readonly index: number,\n ) {}\n}\n","import { FormEvent } from '../interfaces/form-event';\nimport { PageOrchestratorState } from '../../core/page-orchestrator/page-orchestrator.interfaces';\n\nexport class PageNavigationStateChangeEvent implements FormEvent {\n type = 'page-navigation-state-change' as const;\n\n constructor(public state: PageOrchestratorState) {}\n}\n","import { ChangeDetectionStrategy, Component, computed, inject, input, linkedSignal } from '@angular/core';\nimport { takeUntilDestroyed } from '@angular/core/rxjs-interop';\nimport { EventBus } from '../../events/event.bus';\nimport { NextPageEvent, PageChangeEvent, PreviousPageEvent } from '../../events/constants';\nimport { NavigationResult, PageOrchestratorState } from './page-orchestrator.interfaces';\nimport { PageField } from '../../definitions/default/page-field';\nimport { ContainerLogicConfig } from '../../definitions/base/container-logic-config';\nimport { FieldSignalContext } from '../../mappers/types';\nimport PageFieldComponent from '../../fields/page/page-field.component';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { PageNavigationStateChangeEvent } from '../../events/constants/page-navigation-state-change.event';\nimport { FieldTree } from '@angular/forms/signals';\nimport { FIELD_SIGNAL_CONTEXT, FORM_OPTIONS } from '../../models/field-signal-context.token';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { evaluateCondition } from '../expressions/condition-evaluator';\nimport { FunctionRegistryService } from '../registry/function-registry.service';\nimport { FieldContextRegistryService } from '../registry/field-context-registry.service';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { isRowField } from '../../definitions/default/row-field';\n\n/**\n * PageOrchestrator manages page navigation and visibility for paged forms.\n * It acts as an intermediary between the DynamicForm component and PageField components,\n * handling page state management and navigation events without interfering with form data.\n *\n * This component uses declarative rendering with @defer blocks for optimal performance,\n * ensuring that non-visible pages are lazily loaded only when needed.\n *\n * Key responsibilities:\n * - Manage current page index state\n * - Handle navigation events (next/previous)\n * - Declaratively render pages with deferred loading\n * - Emit page change events\n * - Validate navigation boundaries\n *\n * @example\n * ```html\n * <div page-orchestrator\n * [pageFields]=\"pageFields\"\n * [form]=\"form\"\n * [fieldSignalContext]=\"fieldSignalContext\"\n * [config]=\"orchestratorConfig\"\n * (pageChanged)=\"onPageChanged($event)\"\n * (navigationStateChanged)=\"onNavigationStateChanged($event)\">\n * </div>\n * ```\n */\n@Component({\n selector: 'div[page-orchestrator]',\n imports: [PageFieldComponent],\n template: `\n @for (pageField of pageFields(); track pageField.key; let i = $index) {\n @if (i === state().currentPageIndex || i === state().currentPageIndex + 1 || i === state().currentPageIndex - 1) {\n <!-- Current and adjacent pages (±1): render immediately for flicker-free navigation -->\n @defer (on immediate) {\n <section\n page-field\n [field]=\"pageField\"\n [key]=\"pageField.key\"\n [pageIndex]=\"i\"\n [isVisible]=\"i === state().currentPageIndex\"\n ></section>\n } @placeholder {\n <div class=\"df-page-placeholder\" [attr.data-page-index]=\"i\" [attr.data-page-key]=\"pageField.key\"></div>\n }\n } @else {\n <!-- Distant pages: defer until browser is idle for memory savings -->\n @defer (on idle) {\n <section page-field [field]=\"pageField\" [key]=\"pageField.key\" [pageIndex]=\"i\" [isVisible]=\"false\"></section>\n } @placeholder {\n <div class=\"df-page-placeholder\" [attr.data-page-index]=\"i\" [attr.data-page-key]=\"pageField.key\"></div>\n }\n }\n }\n `,\n styleUrl: './page-orchestrator.component.scss',\n host: {\n class: 'df-page-orchestrator',\n '[attr.data-current-page]': 'state().currentPageIndex',\n '[attr.data-total-pages]': 'state().totalPages',\n },\n providers: [\n {\n provide: FIELD_SIGNAL_CONTEXT,\n useFactory: (orchestrator: PageOrchestratorComponent) => orchestrator.extendedFieldSignalContext(),\n deps: [PageOrchestratorComponent],\n },\n ],\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport class PageOrchestratorComponent {\n private readonly eventBus = inject(EventBus);\n private readonly fieldContextRegistry = inject(FieldContextRegistryService);\n private readonly functionRegistry = inject(FunctionRegistryService);\n private readonly formOptions = inject(FORM_OPTIONS, { optional: true });\n\n /**\n * Array of page field definitions to render\n */\n pageFields = input.required<PageField[]>();\n\n /**\n * Root form instance from parent DynamicForm.\n * Uses FieldTree<unknown> to accept any form type.\n */\n form = input.required<FieldTree<unknown>>();\n\n /**\n * Field signal context for child fields\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- FieldSignalContext is contravariant in TModel, using any allows accepting any form type\n fieldSignalContext = input.required<FieldSignalContext<any>>();\n\n /**\n * Computed signal that tracks which pages are hidden.\n * Returns an array of booleans where true means the page is hidden.\n * This signal is reactive and will re-evaluate when form values change.\n */\n readonly pageHiddenStates = computed(() => {\n const pages = this.pageFields();\n\n return pages.map((page) => this.evaluatePageHidden(page));\n });\n\n /**\n * Computed signal that returns indices of visible (non-hidden) pages.\n * This is used for navigation to skip hidden pages.\n */\n readonly visiblePageIndices = computed(() => {\n const hiddenStates = this.pageHiddenStates();\n return hiddenStates\n .map((hidden, index) => ({ index, hidden }))\n .filter((item) => !item.hidden)\n .map((item) => item.index);\n });\n\n /**\n * Internal signal for current page index that tracks with page fields.\n * This tracks the actual page index, not the visible page index.\n *\n * Note: We only track pageFields().length to handle page additions/removals.\n * The hidden state changes should NOT reset the current page index -\n * that would cause unwanted navigation when form values change.\n */\n private readonly currentPageIndex = linkedSignal(() => {\n const totalPages = this.pageFields().length;\n\n if (totalPages === 0) return 0;\n\n // Start on page 0 (will be adjusted if page 0 is hidden by initial navigation)\n return 0;\n });\n\n /**\n * Computed state for the orchestrator\n */\n readonly state = computed<PageOrchestratorState>(() => {\n const currentIndex = this.currentPageIndex();\n const totalPages = this.pageFields().length;\n const visibleIndices = this.visiblePageIndices();\n\n // Find where the current index is in the visible pages list\n const currentVisiblePosition = visibleIndices.indexOf(currentIndex);\n const isFirstVisiblePage = currentVisiblePosition === 0 || currentVisiblePosition === -1;\n const isLastVisiblePage = currentVisiblePosition >= visibleIndices.length - 1;\n\n return {\n currentPageIndex: currentIndex,\n totalPages,\n isFirstPage: isFirstVisiblePage,\n isLastPage: isLastVisiblePage,\n navigationDisabled: false,\n };\n });\n\n /**\n * Signal indicating whether all fields on the current page are valid.\n *\n * This is used by next page buttons to determine their disabled state.\n * Returns `true` if all fields on the current page pass validation,\n * `false` otherwise.\n *\n * @returns `true` if current page is valid, `false` otherwise\n */\n readonly currentPageValid = computed(() => {\n const currentIndex = this.currentPageIndex();\n const pages = this.pageFields();\n const form = this.form();\n\n // No pages or invalid index\n if (pages.length === 0 || currentIndex >= pages.length) {\n return true;\n }\n\n const currentPage = pages[currentIndex];\n const pageFields = currentPage.fields || [];\n\n // Collect all leaf field keys, recursively traversing group/row containers\n const leafKeys = collectLeafFieldKeys(pageFields);\n\n // Check validity of each leaf field on the current page\n // Fields are stored at root level in the form (pages don't add nesting)\n for (const fieldKey of leafKeys) {\n const field = (form as Record<string, unknown>)[fieldKey];\n if (field && typeof field === 'function') {\n const fieldState = (field as () => { valid: () => boolean })();\n if (fieldState && typeof fieldState.valid === 'function' && !fieldState.valid()) {\n return false;\n }\n }\n }\n\n return true;\n });\n\n /**\n * Extended field signal context that includes currentPageValid.\n *\n * This extends the parent context from DynamicForm with page-specific\n * information needed by button mappers (e.g., next button needs to know\n * if the current page is valid).\n */\n readonly extendedFieldSignalContext = computed(() => ({\n ...this.fieldSignalContext(),\n currentPageValid: this.currentPageValid,\n }));\n\n constructor() {\n // Setup event listeners for navigation\n this.setupEventListeners();\n\n // B15: Auto-navigate away when current page becomes hidden\n explicitEffect([this.state, this.visiblePageIndices], ([state, visibleIndices]) => {\n const currentVisiblePosition = visibleIndices.indexOf(state.currentPageIndex);\n if (currentVisiblePosition === -1 && visibleIndices.length > 0) {\n // Current page is hidden — navigate to the nearest visible page\n const nearest = this.findNearestVisiblePage(state.currentPageIndex, visibleIndices);\n if (nearest !== -1) {\n this.navigateToPage(nearest);\n }\n }\n });\n }\n\n /**\n * Navigate to the next visible page, skipping hidden pages.\n * @returns Navigation result\n */\n navigateToNextPage(): NavigationResult {\n // Guard: do not advance if current page has invalid fields.\n // Respects disableWhenPageInvalid option (defaults to true).\n const disableWhenPageInvalid = this.formOptions?.()?.nextButton?.disableWhenPageInvalid ?? true;\n if (disableWhenPageInvalid && !this.currentPageValid()) {\n return {\n success: false,\n newPageIndex: this.state().currentPageIndex,\n error: 'Current page has invalid fields',\n };\n }\n\n const currentState = this.state();\n const visibleIndices = this.visiblePageIndices();\n\n if (currentState.isLastPage) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: 'Already on the last visible page',\n };\n }\n\n if (currentState.navigationDisabled) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: 'Navigation is currently disabled',\n };\n }\n\n // Find the next visible page after the current index\n const currentVisiblePosition = visibleIndices.indexOf(currentState.currentPageIndex);\n if (currentVisiblePosition === -1 || currentVisiblePosition >= visibleIndices.length - 1) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: 'No next visible page available',\n };\n }\n\n const nextVisiblePageIndex = visibleIndices[currentVisiblePosition + 1];\n return this.navigateToPage(nextVisiblePageIndex);\n }\n\n /**\n * Navigate to the previous visible page, skipping hidden pages.\n * @returns Navigation result\n */\n navigateToPreviousPage(): NavigationResult {\n const currentState = this.state();\n const visibleIndices = this.visiblePageIndices();\n\n if (currentState.isFirstPage) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: 'Already on the first visible page',\n };\n }\n\n if (currentState.navigationDisabled) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: 'Navigation is currently disabled',\n };\n }\n\n // Find the previous visible page before the current index\n const currentVisiblePosition = visibleIndices.indexOf(currentState.currentPageIndex);\n if (currentVisiblePosition <= 0) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: 'No previous visible page available',\n };\n }\n\n const prevVisiblePageIndex = visibleIndices[currentVisiblePosition - 1];\n return this.navigateToPage(prevVisiblePageIndex);\n }\n\n /**\n * Navigate to a specific page index\n * @param pageIndex The target page index (0-based)\n * @returns Navigation result\n */\n navigateToPage(pageIndex: number): NavigationResult {\n const currentState = this.state();\n const totalPages = currentState.totalPages;\n\n // Validate page index bounds\n if (pageIndex < 0 || pageIndex >= totalPages) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: `Invalid page index: ${pageIndex}. Valid range is 0 to ${totalPages - 1}`,\n };\n }\n\n // Validate target page is visible\n const visibleIndices = this.visiblePageIndices();\n if (!visibleIndices.includes(pageIndex)) {\n return {\n success: false,\n newPageIndex: currentState.currentPageIndex,\n error: `Cannot navigate to hidden page at index ${pageIndex}. Visible pages: [${visibleIndices.join(', ')}]`,\n };\n }\n\n // Check if already on target page\n if (pageIndex === currentState.currentPageIndex) {\n return {\n success: true,\n newPageIndex: pageIndex,\n };\n }\n\n // Perform navigation\n const previousIndex = currentState.currentPageIndex;\n this.currentPageIndex.set(pageIndex);\n\n // Emit page change event\n this.eventBus.dispatch(PageChangeEvent, pageIndex, totalPages, previousIndex);\n\n return {\n success: true,\n newPageIndex: pageIndex,\n };\n }\n\n /**\n * Finds the nearest visible page index to the given index.\n * Prefers the forward (higher index) page when equidistant.\n */\n private findNearestVisiblePage(currentIndex: number, visibleIndices: number[]): number {\n let nearest = -1;\n let minDistance = Infinity;\n\n for (const idx of visibleIndices) {\n const distance = Math.abs(idx - currentIndex);\n // Prefer forward (higher index) when tied\n if (distance < minDistance || (distance === minDistance && idx > nearest)) {\n minDistance = distance;\n nearest = idx;\n }\n }\n\n return nearest;\n }\n\n /**\n * Set up event listeners for navigation events\n */\n private setupEventListeners(): void {\n // Listen for next page events\n this.eventBus\n .on<NextPageEvent>('next-page')\n .pipe(takeUntilDestroyed())\n .subscribe(() => {\n this.navigateToNextPage();\n });\n\n // Listen for previous page events\n this.eventBus\n .on<PreviousPageEvent>('previous-page')\n .pipe(takeUntilDestroyed())\n .subscribe(() => {\n this.navigateToPreviousPage();\n });\n\n explicitEffect([this.state], ([state]) => this.eventBus.dispatch(PageNavigationStateChangeEvent, state));\n }\n\n /**\n * Evaluates whether a page should be hidden based on its logic configuration.\n * A page is hidden if ANY of its hidden logic conditions evaluate to true.\n *\n * @param page The page field to evaluate\n * @returns true if the page should be hidden, false otherwise\n */\n private evaluatePageHidden(page: PageField): boolean {\n // If no logic defined, page is visible\n if (!page.logic || page.logic.length === 0) {\n return false;\n }\n\n // Filter to only hidden logic (pages only support hidden type)\n const hiddenLogic = page.logic.filter((l): l is ContainerLogicConfig => l.type === 'hidden');\n\n // If no hidden logic, page is visible\n if (hiddenLogic.length === 0) {\n return false;\n }\n\n // Check each hidden logic - if ANY condition is true, the page is hidden\n for (const logic of hiddenLogic) {\n // Handle static boolean conditions (fast path)\n if (typeof logic.condition === 'boolean') {\n if (logic.condition) {\n return true;\n }\n continue;\n }\n\n // Evaluate conditional expression using centralized context creation\n const condition = logic.condition as ConditionalExpression;\n const context = this.fieldContextRegistry.createDisplayOnlyContext(page.key || '', this.functionRegistry.getCustomFunctions());\n\n if (evaluateCondition(condition, context)) {\n return true;\n }\n }\n\n return false;\n }\n}\n\n/**\n * Recursively collects form-tree keys for all value-bearing nodes on a page.\n *\n * Row fields are layout-only containers whose children are flattened to the\n * parent level in the form tree, so we recurse through them transparently.\n *\n * Group fields create a nested sub-tree in the form (form['address']['street']).\n * Their group-level FieldTree node aggregates child validity, so we use the\n * group's own key — not the individual child keys — to check validity.\n *\n * Array fields are also accessed by their own key; the ArrayFieldTree node\n * covers minLength/maxLength and any item-level validators.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any field shape for recursive traversal\nfunction collectLeafFieldKeys(fields: readonly FieldDef<any>[]): string[] {\n const keys: string[] = [];\n\n for (const field of fields) {\n if (isRowField(field)) {\n // Row children are at the same form-tree level as the row itself\n keys.push(...collectLeafFieldKeys(field.fields));\n } else if (field.key) {\n keys.push(field.key);\n }\n }\n\n return keys;\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { ArrayAllowedChildren } from '../../models/types/nesting-constraints';\n\n/**\n * Metadata attached to normalized array fields during simplified array expansion.\n *\n * Stored via a well-known Symbol property on the field object. This survives\n * object spreading (`{ ...field }`) since Symbol-keyed properties are copied\n * by the spread operator, while remaining invisible to `JSON.stringify`,\n * `Object.keys`, and `for...in` loops.\n */\nexport interface NormalizedArrayMetadata {\n /**\n * Remove button FieldDef for primitive simplified arrays.\n * The array component renders this alongside each item without\n * wrapping in a row, preserving flat primitive form values.\n */\n readonly autoRemoveButton?: FieldDef<unknown>;\n /**\n * For primitive simplified arrays, the key of the value field template (e.g., 'value').\n * Stored during normalization so the array component doesn't need dynamic discovery.\n */\n readonly primitiveFieldKey?: string;\n /**\n * Copied from `SimplifiedArrayField.template` during normalization. Used as the\n * fallback template for any array item present in the form value that was not\n * added through the event handlers and is not covered by a positional entry in\n * `fields` — e.g., items introduced by external form-value updates.\n */\n readonly template?: ArrayAllowedChildren | readonly ArrayAllowedChildren[];\n}\n\n/**\n * Symbol key for storing normalization metadata on array field objects.\n * Using a Symbol ensures no collision with user-defined properties and\n * the property is excluded from JSON serialization and enumeration.\n */\nexport const NORMALIZED_ARRAY_METADATA = Symbol('normalizedArrayMetadata');\n\n/**\n * Associates normalization metadata with an array field object.\n * Called during simplified array expansion.\n */\nexport function setNormalizedArrayMetadata(arrayField: Record<string | symbol, unknown>, metadata: NormalizedArrayMetadata): void {\n arrayField[NORMALIZED_ARRAY_METADATA] = metadata;\n}\n\n/**\n * Retrieves normalization metadata for an array field, if any.\n * Returns undefined for full-API arrays that were not normalized from a simplified definition.\n */\nexport function getNormalizedArrayMetadata(arrayField: object): NormalizedArrayMetadata | undefined {\n return (arrayField as Record<symbol, unknown>)[NORMALIZED_ARRAY_METADATA] as NormalizedArrayMetadata | undefined;\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport {\n isSimplifiedArrayField,\n SimplifiedArrayField,\n ArrayButtonConfig,\n ArrayField,\n isArrayField,\n} from '../../definitions/default/array-field';\nimport { isContainerField, hasChildFields } from '../../models/types/type-guards';\nimport { ArrayAllowedChildren } from '../../models/types/nesting-constraints';\nimport { ArrayItemDefinition } from '../../definitions/default/array-field';\nimport { setNormalizedArrayMetadata } from './normalized-array-metadata';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\n\n/**\n * Normalizes simplified array fields into full array field definitions.\n *\n * Walks the field tree and expands any `SimplifiedArrayField` (those with a `template` property)\n * into a standard `ArrayField` with proper item definitions and add/remove button fields.\n *\n * This is a pure function with no DI dependencies. It is idempotent — calling it on\n * already-normalized output produces the same result.\n */\nexport function normalizeSimplifiedArrays(fields: FieldDef<unknown>[]): FieldDef<unknown>[] {\n return fields.flatMap((field): FieldDef<unknown>[] => {\n // Recurse into non-array containers (page, group, row) that have child fields\n if (isContainerField(field) && !isArrayField(field) && hasChildFields(field)) {\n return [{ ...field, fields: normalizeSimplifiedArrays(field.fields as FieldDef<unknown>[]) } as FieldDef<unknown>];\n }\n\n // Full-API arrays may have simplified arrays nested inside their item templates\n if (isArrayField(field) && !isSimplifiedArrayField(field)) {\n const normalizedItems = field.fields.map((item: ArrayItemDefinition) =>\n Array.isArray(item) ? normalizeSimplifiedArrays(item as FieldDef<unknown>[]) : item,\n );\n return [{ ...field, fields: normalizedItems } as ArrayField as FieldDef<unknown>];\n }\n\n // Expand simplified array fields\n if (isSimplifiedArrayField(field)) {\n const { arrayField, addButton } = expandSimplifiedArray(field);\n return addButton ? [arrayField, addButton] : [arrayField];\n }\n\n // Pass through all other fields unchanged\n return [field];\n });\n}\n\ninterface ExpandedArray {\n arrayField: FieldDef<unknown>;\n addButton?: FieldDef<unknown>;\n}\n\n/**\n * Invalid field types that are not allowed as array children.\n * TypeScript enforces this via ArrayAllowedChildren at compile time,\n * but runtime validation is needed for JavaScript users and dynamic configs.\n */\nconst INVALID_ARRAY_CHILD_TYPES = new Set(['page', 'array']);\n\n/**\n * Validates a simplified array field's template configuration.\n * Throws DynamicFormError for invalid configurations that would silently produce broken output.\n */\nfunction validateSimplifiedTemplate(field: SimplifiedArrayField): void {\n const { template, key } = field;\n const isObjectTemplate = Array.isArray(template);\n\n if (isObjectTemplate) {\n const templateFields = template as readonly ArrayAllowedChildren[];\n for (const tmpl of templateFields) {\n // Cast to FieldDef for runtime check — TypeScript prevents this statically,\n // but dynamic configs (e.g., from JSON) may violate the constraint.\n if (INVALID_ARRAY_CHILD_TYPES.has((tmpl as FieldDef<unknown>).type)) {\n throw new DynamicFormError(\n `Simplified array \"${key}\" template contains a '${tmpl.type}' field (key: '${tmpl.key}'). ` +\n `Only leaf fields, rows, and groups are allowed as array children.`,\n );\n }\n }\n } else {\n const singleTemplate = template as FieldDef<unknown>;\n if (INVALID_ARRAY_CHILD_TYPES.has(singleTemplate.type)) {\n throw new DynamicFormError(\n `Simplified array \"${key}\" template has type '${singleTemplate.type}'. ` +\n `Only leaf fields, rows, and groups are allowed as array children.`,\n );\n }\n }\n}\n\n/**\n * Expands a simplified array field into a full ArrayField + optional add button.\n */\nfunction expandSimplifiedArray(field: SimplifiedArrayField): ExpandedArray {\n const {\n template,\n value = [],\n addButton,\n removeButton,\n key,\n logic,\n minLength,\n maxLength,\n wrappers,\n skipAutoWrappers,\n skipDefaultWrappers,\n } = field;\n const isObjectTemplate = Array.isArray(template);\n const values = value as unknown[];\n\n // Validate template before expansion\n validateSimplifiedTemplate(field);\n\n // Build items from values\n const items: ArrayItemDefinition[] = values.map((v) => {\n if (isObjectTemplate) {\n return buildObjectItem(template as readonly ArrayAllowedChildren[], v as Record<string, unknown>, removeButton);\n }\n return buildPrimitiveItem(template as ArrayAllowedChildren, v);\n });\n\n // Build the add button template (item structure without values)\n // For primitive arrays, the add template is a single field (not wrapped in array)\n // so that handleAddFromEvent treats it as a primitive item\n const addTemplate: ArrayAllowedChildren | readonly ArrayAllowedChildren[] = isObjectTemplate\n ? buildObjectItemTemplate(template as readonly ArrayAllowedChildren[], removeButton)\n : (template as ArrayAllowedChildren);\n\n // For primitive arrays with remove buttons, store the remove button config\n // via Symbol metadata. The array component renders remove buttons alongside\n // each item without wrapping in a row, preserving flat primitive form values.\n const hasAutoRemove = !isObjectTemplate && removeButton !== false;\n\n // Construct the full ArrayField\n const arrayFieldObj: Record<string, unknown> = {\n key,\n type: 'array' as const,\n fields: items,\n };\n if (logic) {\n arrayFieldObj['logic'] = logic;\n }\n if (minLength !== undefined) {\n arrayFieldObj['minLength'] = minLength;\n }\n if (maxLength !== undefined) {\n arrayFieldObj['maxLength'] = maxLength;\n }\n if (wrappers !== undefined) {\n arrayFieldObj['wrappers'] = wrappers;\n }\n if (skipAutoWrappers !== undefined) {\n arrayFieldObj['skipAutoWrappers'] = skipAutoWrappers;\n }\n if (skipDefaultWrappers !== undefined) {\n arrayFieldObj['skipDefaultWrappers'] = skipDefaultWrappers;\n }\n\n // Safe cast: we're constructing a valid ArrayField shape with key, type, and fields\n const arrayField = arrayFieldObj as unknown as FieldDef<unknown>;\n\n // Store normalization metadata via Symbol property instead of a runtime property.\n // `template` always gets populated so the array component can resolve untracked\n // items (e.g., from external form-value updates).\n //\n // For object templates, we must include the auto-generated remove button in the stored\n // template because object arrays embed the button inside each item's fields (via\n // buildObjectItem) rather than via the `autoRemoveButton` metadata. Without this,\n // items resolved from metadata would render without the remove button that\n // originally-declared items have. Primitive templates keep the button as separate\n // metadata and pass the raw template through — withAutoRemove() appends the button\n // at resolution time from autoRemoveButton.\n const primitiveFieldKey = !isObjectTemplate ? (template as ArrayAllowedChildren).key : undefined;\n const metadataTemplate = isObjectTemplate ? buildObjectItemTemplate(template as readonly ArrayAllowedChildren[], removeButton) : template;\n\n setNormalizedArrayMetadata(arrayFieldObj, {\n ...(hasAutoRemove && { autoRemoveButton: buildRemoveButton(removeButton) }),\n ...(primitiveFieldKey && { primitiveFieldKey }),\n template: metadataTemplate,\n });\n\n // Construct the add button (sibling, placed after the array)\n let addButtonField: FieldDef<unknown> | undefined;\n if (addButton !== false) {\n const buttonConfig = (typeof addButton === 'object' ? addButton : {}) as ArrayButtonConfig;\n // Safe cast: we're constructing a valid addArrayItem field shape\n addButtonField = {\n key: `${key}__add`,\n type: 'addArrayItem',\n label: buttonConfig.label ?? 'Add',\n arrayKey: key,\n template: addTemplate,\n ...(buttonConfig.props && { props: buttonConfig.props }),\n // Logic is intentionally shared with the array field so the add button\n // hides/shows together with the array (e.g., when a hidden condition applies).\n ...(logic && { logic }),\n } as unknown as FieldDef<unknown>;\n }\n\n return { arrayField, addButton: addButtonField };\n}\n\n/**\n * Builds a primitive array item as a single FieldDef (not wrapped in array).\n *\n * This ensures the form schema creates FormControls (not FormGroups) for each item,\n * producing flat primitive values like `['angular', 'typescript']` instead of\n * `[{ value: 'angular' }, { value: 'typescript' }]`.\n *\n * Remove buttons are handled separately via Symbol metadata on the array field,\n * which the array component renders alongside each item without affecting form values.\n */\nfunction buildPrimitiveItem(template: ArrayAllowedChildren, value: unknown): ArrayItemDefinition {\n return { ...template, value } as ArrayAllowedChildren;\n}\n\n/**\n * Builds an object array item: template fields with values merged + optional remove button.\n */\nfunction buildObjectItem(\n template: readonly ArrayAllowedChildren[],\n valueObj: Record<string, unknown>,\n removeButton: ArrayButtonConfig | false | undefined,\n): ArrayItemDefinition {\n const fieldsWithValues = template.map(\n (templateField) =>\n ({\n ...templateField,\n ...(Object.hasOwn(valueObj, templateField.key) && { value: valueObj[templateField.key] }),\n }) as ArrayAllowedChildren,\n );\n\n if (removeButton === false) {\n return fieldsWithValues;\n }\n\n return [...fieldsWithValues, buildRemoveButton(removeButton)];\n}\n\n/**\n * Builds the add button template for object items (template fields without values + remove button).\n */\nfunction buildObjectItemTemplate(\n template: readonly ArrayAllowedChildren[],\n removeButton: ArrayButtonConfig | false | undefined,\n): readonly ArrayAllowedChildren[] {\n if (removeButton === false) {\n return template;\n }\n\n return [...template, buildRemoveButton(removeButton)];\n}\n\n/**\n * Builds a remove button field definition.\n */\nfunction buildRemoveButton(config: ArrayButtonConfig | undefined): ArrayAllowedChildren {\n const buttonConfig = (typeof config === 'object' ? config : {}) as ArrayButtonConfig;\n // Safe cast: removeArrayItem fields are valid ArrayAllowedChildren but not in the static union\n return {\n key: '__remove',\n type: 'removeArrayItem',\n label: buttonConfig.label ?? 'Remove',\n ...(buttonConfig.props && { props: buttonConfig.props }),\n } as unknown as ArrayAllowedChildren;\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { isPageField } from '../../definitions/default/page-field';\nimport { RegisteredFieldTypes } from '../registry/field-registry';\n\n// Re-export isPageField for external usage\nexport { isPageField };\n\n/**\n * Interface for fields that contain child fields\n */\ninterface ContainerField<T> extends FieldDef<T> {\n fields: FieldDef<unknown>[];\n}\n\n/**\n * Type guard to check if a field is a container with fields\n */\nfunction isContainerWithFields<T>(field: FieldDef<T>): field is FieldDef<T> & ContainerField<T> {\n return (\n (field.type === 'row' || field.type === 'group' || field.type === 'page' || field.type === 'container') &&\n 'fields' in field &&\n Array.isArray((field as ContainerField<T>).fields)\n );\n}\n\n/**\n * Form mode enumeration distinguishing between paged and non-paged forms\n */\nexport type FormMode = 'paged' | 'non-paged';\n\n/**\n * Result of form mode detection with validation details\n */\nexport interface FormModeDetectionResult {\n /** The detected form mode */\n mode: FormMode;\n /** Whether the form configuration is valid for the detected mode */\n isValid: boolean;\n /** Array of validation errors if form is invalid */\n errors: string[];\n}\n\n/**\n * Type guard for paged form configurations\n * A paged form has ALL root-level fields of type 'page'\n */\nexport function isPagedForm<TFields extends RegisteredFieldTypes[]>(fields: TFields): boolean {\n if (!fields || fields.length === 0) {\n return false;\n }\n\n return fields.every((field) => isPageField(field));\n}\n\n/**\n * Type guard for non-paged form configurations\n * A non-paged form has NO page fields at any level\n */\nexport function isNonPagedForm<TFields extends RegisteredFieldTypes[]>(fields: TFields): boolean {\n if (!fields || fields.length === 0) {\n return true; // Empty form is considered non-paged\n }\n\n return !hasAnyPageFields(fields);\n}\n\n/**\n * Detects the form mode and validates the configuration\n * @param fields The form field definitions\n * @returns Detection result with mode and validation status\n */\nexport function detectFormMode<TFields extends RegisteredFieldTypes[]>(fields: TFields): FormModeDetectionResult {\n if (!fields || fields.length === 0) {\n return {\n mode: 'non-paged',\n isValid: true,\n errors: [],\n };\n }\n\n const hasPageFields = fields.some((field) => isPageField(field));\n const allPagesAtRoot = fields.every((field) => isPageField(field));\n const hasNestedPages = hasNestedPageFields(fields);\n\n // Determine mode and validate\n if (hasPageFields) {\n const errors: string[] = [];\n\n // For paged forms, ALL root fields must be pages\n if (!allPagesAtRoot) {\n errors.push('Mixed page and non-page fields at root level. In paged forms, ALL root-level fields must be of type \"page\".');\n }\n\n // Check for nested pages in any page field\n if (hasNestedPages) {\n errors.push('Page fields cannot contain nested page fields at any level.');\n }\n\n return {\n mode: 'paged',\n isValid: errors.length === 0,\n errors,\n };\n } else {\n // Non-paged form\n const errors: string[] = [];\n\n // Non-paged forms cannot have page fields anywhere\n if (hasAnyPageFields(fields)) {\n errors.push('Page fields are not allowed in non-paged forms.');\n }\n\n return {\n mode: 'non-paged',\n isValid: errors.length === 0,\n errors,\n };\n }\n}\n\n/**\n * Recursively checks if any field definition is a page field\n * @param fields Array of field definitions to check\n * @returns true if any page field is found at any level\n */\nfunction hasAnyPageFields(fields: FieldDef<unknown>[]): boolean {\n for (const field of fields) {\n if (isPageField(field)) {\n return true;\n }\n\n // Check nested fields in container types\n if (isContainerWithFields(field) && (field.type === 'row' || field.type === 'group')) {\n if (hasAnyPageFields(field.fields)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Checks if fields contain nested page fields within their children\n * (This is different from hasAnyPageFields as it checks NESTED pages, not root pages)\n * @param fields Array of field definitions to check\n * @returns true if nested page fields found\n */\nfunction hasNestedPageFields(fields: FieldDef<unknown>[]): boolean {\n for (const field of fields) {\n // If this is a page field, check if its children contain pages\n if (isPageField(field) && isContainerWithFields(field)) {\n if (hasAnyPageFields(field.fields)) {\n return true;\n }\n }\n\n // Check other container types for nested pages\n if (isContainerWithFields(field) && (field.type === 'row' || field.type === 'group')) {\n if (hasNestedPageFields(field.fields)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Type predicate for valid paged form configurations\n */\nexport function isValidPagedForm<TFields extends RegisteredFieldTypes[]>(fields: TFields): boolean {\n const result = detectFormMode(fields);\n return result.mode === 'paged' && result.isValid;\n}\n\n/**\n * Type predicate for valid non-paged form configurations\n */\nexport function isValidNonPagedForm<TFields extends RegisteredFieldTypes[]>(fields: TFields): boolean {\n const result = detectFormMode(fields);\n return result.mode === 'non-paged' && result.isValid;\n}\n","import { ConditionalExpression } from '../expressions/conditional-expression';\nimport { HttpRequestConfig } from '../http/http-request-config';\nimport { HttpValidationResponseMapping } from '../http/http-response-mapping';\n\n/**\n * Base configuration shared by all validators\n */\nexport interface BaseValidatorConfig {\n /** Conditional logic for when validator applies */\n when?: ConditionalExpression;\n}\n\n/**\n * Built-in validator configuration (required, email, min, max, etc.)\n */\nexport interface BuiltInValidatorConfig extends BaseValidatorConfig {\n /** Validator type identifier */\n type: 'required' | 'email' | 'min' | 'max' | 'minLength' | 'maxLength' | 'pattern';\n\n /** Static value for the validator (e.g., min value, pattern) */\n value?: number | string | RegExp;\n\n /** Dynamic value expression that evaluates to validator parameter */\n expression?: string;\n}\n\n/**\n * Custom validator configuration using Angular's public FieldContext API\n * Returns ValidationError | ValidationError[] | null synchronously\n *\n * Supports two patterns:\n * 1. Function-based: { type: 'custom', functionName: 'myValidator' }\n * 2. Expression-based: { type: 'custom', expression: 'fieldValue === formValue.password', kind: 'passwordMismatch' }\n */\nexport interface CustomValidatorConfig extends BaseValidatorConfig {\n /** Validator type identifier */\n type: 'custom';\n\n /** Name of registered validator function (function-based pattern) */\n functionName?: string;\n\n /** Optional parameters to pass to validator function */\n params?: Record<string, unknown>;\n\n /** JavaScript expression to evaluate (expression-based pattern) */\n expression?: string;\n\n /** Error kind for expression-based validators - links to validationMessages */\n kind?: string;\n\n /**\n * Parameters to include in error object for message interpolation (expression-based pattern)\n * Map of parameter names to expressions that will be evaluated in the same context as the validation expression\n *\n * @example\n * errorParams: {\n * minValue: 'formValue.minValue',\n * maxValue: 'formValue.maxValue'\n * }\n * // Allows message template: \"Value must be between {{minValue}} and {{maxValue}}\"\n */\n errorParams?: Record<string, string>;\n}\n\n/**\n * Async custom validator configuration using Angular's validateAsync API.\n * Returns Observable<ValidationError | ValidationError[] | null>.\n *\n */\nexport interface AsyncValidatorConfig extends BaseValidatorConfig {\n /** Validator type identifier. */\n type: 'async';\n\n /** Name of registered async validator function */\n functionName: string;\n\n /** Optional parameters to pass to validator function */\n params?: Record<string, unknown>;\n}\n\n/**\n * Function-based HTTP validator configuration — requires a registered function.\n *\n * Uses Angular's `validateHttp` API. The function is registered via\n * `customFnConfig.httpValidators`.\n *\n * Discriminated from `DeclarativeHttpValidatorConfig` by the presence of `functionName`.\n *\n */\nexport interface FunctionHttpValidatorConfig extends BaseValidatorConfig {\n /** Validator type identifier. */\n type: 'http';\n\n /** Name of registered HTTP validator configuration */\n functionName: string;\n\n /** Optional parameters to pass to HTTP validator */\n params?: Record<string, unknown>;\n}\n\n/**\n * Declarative HTTP validator configuration — fully JSON-serializable, no function registration required.\n *\n * Uses `HttpRequestConfig` to define the HTTP request and `HttpValidationResponseMapping`\n * to interpret the response as a validation result. Powered by Angular's `validateHttp` API.\n *\n * Discriminated from `FunctionHttpValidatorConfig` by the presence of `http` + `responseMapping`\n * (and absence of `functionName`).\n */\nexport interface DeclarativeHttpValidatorConfig extends BaseValidatorConfig {\n /** Validator type identifier */\n type: 'http';\n\n /** HTTP request configuration with expression-based query params and body */\n http: HttpRequestConfig;\n\n /** Mapping that interprets the HTTP response as a validation result */\n responseMapping: HttpValidationResponseMapping;\n}\n\n/**\n * Configuration for signal forms validator functions that can be serialized from API.\n * Discriminated union type for type-safe validator configuration.\n *\n * Note: `FunctionHttpValidatorConfig` and `DeclarativeHttpValidatorConfig` both use `type: 'http'`.\n * They are discriminated by property presence: `functionName` → function-based, `http` → declarative.\n * Use `isFunctionHttpValidator()` for type-safe narrowing when `type` alone is insufficient.\n */\nexport type ValidatorConfig =\n | BuiltInValidatorConfig\n | CustomValidatorConfig\n | AsyncValidatorConfig\n | FunctionHttpValidatorConfig\n | DeclarativeHttpValidatorConfig;\n\n/**\n * Type guard to distinguish function-based HTTP validators from declarative ones.\n *\n * Both use `type: 'http'`, so `switch (config.type)` cannot narrow between them.\n * Use this guard when you need type-safe access to `FunctionHttpValidatorConfig` properties.\n */\nexport function isFunctionHttpValidator(\n config: FunctionHttpValidatorConfig | DeclarativeHttpValidatorConfig,\n): config is FunctionHttpValidatorConfig {\n return 'functionName' in config && !!config.functionName;\n}\n","import { ValidationError } from '@angular/forms/signals';\nimport { HttpValidationResponseMapping } from '../../models/http/http-response-mapping';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport { ExpressionParser } from '../expressions/parser/expression-parser';\n\n/**\n * Evaluates an HTTP response against a `HttpValidationResponseMapping` to produce a validation result.\n *\n * - `validWhen` === `true` → `null` (valid, no error)\n * - `validWhen` !== `true` → `{ kind: errorKind, ...evaluatedErrorParams }`\n * - Expression error → logs warning, returns `{ kind: errorKind }` (fail-closed)\n *\n * Expressions are evaluated with scope `{ response }` only.\n */\nexport function evaluateHttpValidationResponse(\n response: unknown,\n mapping: HttpValidationResponseMapping,\n logger: Logger,\n): ValidationError | null {\n const scope = { response };\n\n try {\n const result = ExpressionParser.evaluate(mapping.validWhen, scope);\n\n if (typeof result !== 'boolean') {\n logger.warn(`validWhen expression \"${mapping.validWhen}\" returned non-boolean value:`, result, 'Expected true or false.');\n }\n\n if (result === true) {\n return null;\n }\n\n const error: ValidationError & Record<string, unknown> = { kind: mapping.errorKind };\n\n if (mapping.errorParams) {\n for (const [key, expression] of Object.entries(mapping.errorParams)) {\n try {\n error[key] = ExpressionParser.evaluate(expression, scope);\n } catch (err) {\n logger.warn(`Error evaluating errorParam \"${key}\":`, expression, err);\n }\n }\n }\n\n return error;\n } catch (err) {\n logger.warn('Error evaluating validWhen expression:', mapping.validWhen, err);\n return { kind: mapping.errorKind };\n }\n}\n","/**\n * Serializes a value to a deterministic string for cache key generation.\n * Unlike JSON.stringify, this sorts object keys to ensure consistent output\n * regardless of property insertion order.\n */\nexport function stableStringify(value: unknown): string {\n if (value === null || value === undefined) {\n return String(value);\n }\n\n if (typeof value !== 'object') {\n return JSON.stringify(value);\n }\n\n if (Array.isArray(value)) {\n return '[' + value.map(stableStringify).join(',') + ']';\n }\n\n const obj = value as Record<string, unknown>;\n const sortedKeys = Object.keys(obj).sort();\n const pairs = sortedKeys.map((key) => JSON.stringify(key) + ':' + stableStringify(obj[key]));\n return '{' + pairs.join(',') + '}';\n}\n","import { InjectionToken } from '@angular/core';\n\ninterface CacheEntry {\n value: boolean;\n expiresAt: number;\n}\n\n/**\n * TTL cache for HTTP condition responses with max entries eviction.\n *\n * Keyed by serialized resolved request (the `HttpResourceRequest` after expression evaluation).\n * Two different form states producing the same resolved URL+body hit the same cache entry.\n *\n * When `maxEntries` is exceeded, the oldest entry (by insertion order) is evicted.\n *\n * Provided via DI (scoped to DynamicForm component) for SSR safety.\n */\nexport class HttpConditionCache {\n private readonly cache = new Map<string, CacheEntry>();\n private readonly maxEntries: number;\n\n constructor(maxEntries = 100) {\n this.maxEntries = Math.max(1, maxEntries);\n }\n\n get(key: string): boolean | undefined {\n const entry = this.cache.get(key);\n if (!entry) return undefined;\n\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n return undefined;\n }\n\n return entry.value;\n }\n\n set(key: string, value: boolean, ttlMs: number): void {\n // Evict oldest entries if at capacity (Map preserves insertion order)\n while (this.cache.size >= this.maxEntries && !this.cache.has(key)) {\n const oldestKey = this.cache.keys().next().value;\n if (oldestKey !== undefined) {\n this.cache.delete(oldestKey);\n }\n }\n\n this.cache.set(key, { value, expiresAt: Date.now() + ttlMs });\n }\n\n clear(): void {\n this.cache.clear();\n }\n}\n\n/** @internal */\nexport const HTTP_CONDITION_CACHE = new InjectionToken<HttpConditionCache>('HttpConditionCache');\n","import { LogicFn } from '@angular/forms/signals';\n\n/**\n * DI-scoped cache for HTTP condition logic functions.\n *\n * Replaces module-scoped WeakMaps to ensure SSR safety.\n * Scoped to the DynamicForm component via `provideDynamicFormDI()`.\n *\n * Note: Per-field signal stores are closure-scoped per LogicFn, not shared here,\n * because multiple HTTP conditions on the same field share the same FieldContext\n * reference and would collide in a shared WeakMap.\n */\nexport class HttpConditionFunctionCacheService {\n /** Cache for HTTP condition logic functions, keyed by serialized condition. */\n readonly httpConditionFunctionCache = new Map<string, LogicFn<unknown, boolean>>();\n}\n","import { linkedSignal, Resource, ResourceSnapshot, resourceFromSnapshots } from '@angular/core';\n\n/**\n * Wraps a `Resource` so that the previous resolved value is preserved while the resource\n * is loading or reloading. This prevents UI flicker when params change and a new request\n * is in-flight — the consumer sees the stale value with a `loading`/`reloading` status\n * instead of `undefined`.\n *\n * Uses Angular's `resource.snapshot` + `resourceFromSnapshots` composition pattern.\n *\n * @example\n * ```typescript\n * const user = withPreviousValue(\n * resource({ params: () => userId(), loader: ({ params }) => fetchUser(params) })\n * );\n * // user.value() keeps the old user data during loading transitions\n * ```\n *\n * @experimental Uses Angular's experimental resource composition APIs.\n */\nexport function withPreviousValue<T>(input: Resource<T>): Resource<T> {\n const derived = linkedSignal<ResourceSnapshot<T>, ResourceSnapshot<T>>({\n source: input.snapshot,\n computation: (snapshot, previous) => {\n // During loading/reloading, keep the previous resolved value if available.\n // Don't preserve values from error states — those aren't useful to show.\n if (\n (snapshot.status === 'loading' || snapshot.status === 'reloading') &&\n previous !== undefined &&\n previous.value.status !== 'error'\n ) {\n return { status: snapshot.status, value: previous.value.value } as ResourceSnapshot<T>;\n }\n return snapshot;\n },\n });\n\n return resourceFromSnapshots(derived);\n}\n","import { Injector, isSignal, Signal } from '@angular/core';\nimport { toObservable, toSignal } from '@angular/core/rxjs-interop';\nimport { combineLatest, defer, Observable, OperatorFunction } from 'rxjs';\n\n/**\n * Type guard to check if a value is an array of Signals.\n * @internal\n */\nfunction isSignalArray(value: unknown): value is readonly Signal<unknown>[] {\n return Array.isArray(value) && value.every((item) => isSignal(item));\n}\n\n/**\n * Type guard to check if a value is a record (object) of Signals.\n * @internal\n */\nfunction isSignalRecord(value: unknown): value is Record<string, Signal<unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.values(value).every((item) => isSignal(item));\n}\n\n/**\n * Options for derivedFromDeferred.\n */\nexport interface DerivedFromDeferredOptions<R> {\n initialValue: R;\n injector: Injector;\n}\n\n/**\n * Type helper to extract the value type from a Signal.\n */\ntype SignalValue<T> = T extends Signal<infer V> ? V : never;\n\n/**\n * Type helper to map an array of Signals to an array of their value types.\n */\ntype SignalValues<T extends readonly Signal<unknown>[]> = {\n [K in keyof T]: SignalValue<T[K]>;\n};\n\n/**\n * Type helper to map an object of Signals to an object of their value types.\n */\ntype SignalObjectValues<T extends Record<string, Signal<unknown>>> = {\n [K in keyof T]: SignalValue<T[K]>;\n};\n\n/**\n * Like derivedFrom from ngxtension, but uses defer() to avoid input availability issues.\n * This ensures toObservable is called at subscription time, not at field initialization.\n *\n * Supports three source types:\n * - Single signal: `derivedFromDeferred(signal, operator, options)`\n * - Array of signals: `derivedFromDeferred([signal1, signal2], operator, options)`\n * - Object of signals: `derivedFromDeferred({a: signal1, b: signal2}, operator, options)`\n *\n * @example\n * ```typescript\n * // Single signal\n * const result = derivedFromDeferred(\n * mySignal,\n * pipe(map(v => v * 2)),\n * { initialValue: 0, injector }\n * );\n *\n * // Array of signals\n * const result = derivedFromDeferred(\n * [signalA, signalB],\n * pipe(map(([a, b]) => a + b)),\n * { initialValue: 0, injector }\n * );\n *\n * // Object of signals\n * const result = derivedFromDeferred(\n * { x: signalX, y: signalY },\n * pipe(map(({ x, y }) => x + y)),\n * { initialValue: 0, injector }\n * );\n * ```\n */\n\n// Overload: Single signal\nexport function derivedFromDeferred<T, R>(\n source: Signal<T>,\n operator: OperatorFunction<T, R>,\n options: DerivedFromDeferredOptions<R>,\n): Signal<R>;\n\n// Overload: Array of signals\nexport function derivedFromDeferred<T extends readonly Signal<unknown>[], R>(\n sources: [...T],\n operator: OperatorFunction<SignalValues<T>, R>,\n options: DerivedFromDeferredOptions<R>,\n): Signal<R>;\n\n// Overload: Object of signals\nexport function derivedFromDeferred<T extends Record<string, Signal<unknown>>, R>(\n sources: T,\n operator: OperatorFunction<SignalObjectValues<T>, R>,\n options: DerivedFromDeferredOptions<R>,\n): Signal<R>;\n\n// Implementation\nexport function derivedFromDeferred<T, R>(\n source: Signal<T> | Signal<unknown>[] | Record<string, Signal<unknown>>,\n operator: OperatorFunction<T | unknown[] | Record<string, unknown>, R>,\n options: DerivedFromDeferredOptions<R>,\n): Signal<R> {\n const deferred$: Observable<R> = defer(() => {\n // Handle single signal\n if (isSignal(source)) {\n return toObservable(source, { injector: options.injector });\n }\n\n // Handle array of signals\n if (isSignalArray(source)) {\n const observables = source.map((s) => toObservable(s, { injector: options.injector }));\n return combineLatest(observables);\n }\n\n // Handle object of signals\n if (isSignalRecord(source)) {\n const keys = Object.keys(source);\n const observables = keys.map((key) => toObservable(source[key], { injector: options.injector }));\n\n return combineLatest(observables, (...values) => {\n const result: Record<string, unknown> = {};\n keys.forEach((key, index) => {\n result[key] = values[index];\n });\n return result;\n });\n }\n\n // Fallback - should not happen with proper typing\n throw new Error('Invalid source type. Expected a Signal, array of Signals, or object of Signals.');\n }).pipe(operator);\n\n return toSignal(deferred$, { initialValue: options.initialValue, injector: options.injector });\n}\n","import { HttpClient } from '@angular/common/http';\nimport { inject, Injector, Resource, signal, untracked, WritableSignal } from '@angular/core';\nimport { rxResource } from '@angular/core/rxjs-interop';\nimport { FieldContext, LogicFn } from '@angular/forms/signals';\nimport { catchError, debounceTime, distinctUntilChanged, map, of, pipe, tap } from 'rxjs';\nimport { HttpCondition } from '../../models/expressions/conditional-expression';\nimport { stableStringify } from '../../utils/stable-stringify';\nimport { HttpResourceRequest } from '../validation/validator-types';\nimport { FieldContextRegistryService } from '../registry/field-context-registry.service';\nimport { FunctionRegistryService } from '../registry/function-registry.service';\nimport { HTTP_CONDITION_CACHE } from '../http/http-condition-cache';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport { resolveHttpRequest } from '../http/http-request-resolver';\nimport { ExpressionParser } from './parser/expression-parser';\nimport { HttpConditionFunctionCacheService } from './http-condition-function-cache.service';\nimport { safeReadPathKeys } from '../../utils/safe-read-path-keys';\nimport { withPreviousValue } from '../../utils/resource-composition/with-previous-value';\nimport { derivedFromDeferred } from '../../utils/derived-from-deferred/derived-from-deferred';\n\n/**\n * Extracts a boolean from an HTTP response using an optional expression.\n * When `responseExpression` is provided, evaluates it with `{ response }` scope.\n * Truthy values are treated as `true` — non-boolean results trigger a warning to encourage explicit boolean expressions.\n * Otherwise, coerces the response to boolean.\n */\nfunction extractBoolean(response: unknown, responseExpression: string | undefined, pendingValue: boolean, logger: Logger): boolean {\n if (responseExpression) {\n try {\n const result = ExpressionParser.evaluate(responseExpression, { response });\n if (typeof result !== 'boolean') {\n logger.warn(\n `responseExpression \"${responseExpression}\" returned non-boolean value:`,\n result,\n 'Consider returning a boolean explicitly.',\n );\n }\n return !!result;\n } catch (error) {\n logger.warn(`Failed to evaluate responseExpression '${responseExpression}':`, error);\n return pendingValue;\n }\n }\n return !!response;\n}\n\n/**\n * Creates a logic function for an HTTP condition.\n *\n * Uses Angular's `rxResource()` API with snapshot composition for async resolution:\n * the LogicFn updates a `resolvedRequest` signal, a debounced version feeds into\n * an `rxResource()` that manages the HTTP lifecycle, and `withPreviousValue()` preserves\n * the last resolved boolean during re-fetching to prevent UI flicker.\n *\n * Must be called in injection context (same as `createLogicFunction`).\n */\nexport function createHttpConditionLogicFunction<TValue>(condition: HttpCondition): LogicFn<TValue, boolean> {\n const httpClient = inject(HttpClient, { optional: true });\n if (!httpClient) {\n throw new DynamicFormError('HttpClient is required for HTTP conditions. Add provideHttpClient() to your providers.');\n }\n const fieldContextRegistry = inject(FieldContextRegistryService);\n const functionRegistry = inject(FunctionRegistryService);\n const injector = inject(Injector);\n const cache = inject(HTTP_CONDITION_CACHE);\n const logger = inject(DynamicFormLogger) as Logger;\n const cacheService = inject(HttpConditionFunctionCacheService);\n\n const pendingValue = condition.pendingValue ?? false;\n const cacheDurationMs = condition.cacheDurationMs ?? 30000;\n const debounceMs = condition.debounceMs ?? 300;\n\n // Check function cache\n const cacheKey = stableStringify(condition);\n\n const cached = cacheService.httpConditionFunctionCache.get(cacheKey);\n if (cached) {\n return cached as LogicFn<TValue, boolean>;\n }\n\n // Each condition needs its own per-field signal store. A shared store would collide\n // when multiple HTTP conditions exist on the same field (same FieldContext / path).\n const perFunctionSignalStore = new Map<\n string,\n { resolvedRequest: WritableSignal<HttpResourceRequest | undefined>; resultResource: Resource<boolean> }\n >();\n\n const fn: LogicFn<TValue, boolean> = (ctx: FieldContext<TValue>) => {\n const contextKey = safeReadPathKeys(ctx as FieldContext<unknown>).join('.');\n let signalPair = perFunctionSignalStore.get(contextKey);\n\n if (!signalPair) {\n const resolvedRequest = signal<HttpResourceRequest | undefined>(undefined);\n\n // Wrap in untracked() to avoid NG0602: resource() internally creates effects,\n // which cannot be created inside a reactive context (computed). The LogicFn runs\n // inside Angular Signal Forms' BooleanOrLogic.compute (a computed), so we must\n // clear the active reactive consumer before creating the resource pipeline.\n const resultResource = untracked(() => {\n // Create a debounced, stabilized version of the request signal.\n // This prevents rapid re-fetches when form values change quickly.\n const debouncedRequest = derivedFromDeferred(\n resolvedRequest,\n pipe(\n debounceTime(debounceMs),\n distinctUntilChanged((prev, curr) => stableStringify(prev) === stableStringify(curr)),\n ),\n { initialValue: undefined as HttpResourceRequest | undefined, injector },\n );\n\n // rxResource() manages the HTTP lifecycle natively with Observables:\n // auto-cancellation via unsubscription, loading/resolved/error status tracking,\n // and signal-based reactivity.\n const httpResource = rxResource({\n params: () => debouncedRequest() ?? undefined,\n // When params() returns undefined, rxResource() enters idle state and skips the stream.\n stream: ({ params: request }) => {\n const method = request.method ?? 'GET';\n const options: Record<string, unknown> = {};\n if (request.body) options['body'] = request.body;\n if (request.headers) options['headers'] = request.headers;\n\n return httpClient.request(method, request.url, options).pipe(\n map((response) => extractBoolean(response, condition.responseExpression, pendingValue, logger)),\n tap((value) => {\n const requestKey = stableStringify(request);\n cache.set(requestKey, value, cacheDurationMs);\n }),\n catchError((error) => {\n logger.warn('HTTP condition request failed:', error);\n return of(pendingValue);\n }),\n );\n },\n defaultValue: pendingValue,\n injector,\n });\n\n // Snapshot composition: preserve the previous boolean result during re-fetching.\n // Without this, the condition would briefly flash to pendingValue when params change,\n // causing visible UI flicker (e.g., a conditionally visible field briefly disappearing).\n return withPreviousValue(httpResource);\n });\n\n signalPair = { resolvedRequest, resultResource };\n perFunctionSignalStore.set(contextKey, signalPair);\n }\n\n // Build reactive evaluation context (creates signal dependencies on form values)\n const evaluationContext = fieldContextRegistry.createReactiveEvaluationContext(ctx, functionRegistry.getCustomFunctions());\n\n // Returns null when a path param is undefined — skip the request and return pending value\n const resolved = resolveHttpRequest(condition.http, evaluationContext);\n if (!resolved) {\n return signalPair.resultResource.value();\n }\n const requestKey = stableStringify(resolved);\n\n // Check response cache first\n const cachedResult = cache.get(requestKey);\n if (cachedResult !== undefined) {\n return cachedResult;\n }\n\n // Update the resolved request signal (triggers resource if request changed)\n const { resolvedRequest, resultResource } = signalPair;\n untracked(() => {\n const current = resolvedRequest();\n if (stableStringify(current) !== requestKey) {\n resolvedRequest.set(resolved);\n }\n });\n\n return resultResource.value();\n };\n\n cacheService.httpConditionFunctionCache.set(cacheKey, fn as LogicFn<unknown, boolean>);\n return fn;\n}\n","import { LogicFn } from '@angular/forms/signals';\n\n/**\n * DI-scoped cache for async condition logic functions.\n *\n * Replaces module-scoped WeakMaps to ensure SSR safety.\n * Scoped to the DynamicForm component via `provideDynamicFormDI()`.\n *\n * Note: Per-field signal stores are closure-scoped per LogicFn, not shared here,\n * because multiple async conditions on the same field share the same FieldContext\n * reference and would collide in a shared WeakMap.\n */\nexport class AsyncConditionFunctionCacheService {\n /** Cache for async condition logic functions, keyed by serialized condition. */\n readonly asyncConditionFunctionCache = new Map<string, LogicFn<unknown, boolean>>();\n}\n","import { inject, Injector, Resource, signal, untracked, WritableSignal } from '@angular/core';\nimport { rxResource } from '@angular/core/rxjs-interop';\nimport { FieldContext, LogicFn } from '@angular/forms/signals';\nimport { catchError, debounceTime, distinctUntilChanged, from, map, of, pipe } from 'rxjs';\nimport { AsyncCondition } from '../../models/expressions/conditional-expression';\nimport { stableStringify } from '../../utils/stable-stringify';\nimport { FieldContextRegistryService } from '../registry/field-context-registry.service';\nimport { FunctionRegistryService } from '../registry/function-registry.service';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { Logger } from '../../providers/features/logger/logger.interface';\nimport { AsyncConditionFunctionCacheService } from './async-condition-function-cache.service';\nimport { safeReadPathKeys } from '../../utils/safe-read-path-keys';\nimport { withPreviousValue } from '../../utils/resource-composition/with-previous-value';\nimport { derivedFromDeferred } from '../../utils/derived-from-deferred/derived-from-deferred';\n\n/**\n * Creates a logic function for an async condition.\n *\n * Uses Angular's `rxResource()` API with snapshot composition for async resolution:\n * the LogicFn updates a `trigger` signal (serialized evaluation context), a debounced\n * version feeds into an `rxResource()` that manages the async function lifecycle, and\n * `withPreviousValue()` preserves the last resolved boolean during re-evaluation\n * to prevent UI flicker.\n *\n * Must be called in injection context (same as `createLogicFunction`).\n */\nexport function createAsyncConditionLogicFunction<TValue>(condition: AsyncCondition): LogicFn<TValue, boolean> {\n const fieldContextRegistry = inject(FieldContextRegistryService);\n const functionRegistry = inject(FunctionRegistryService);\n const injector = inject(Injector);\n const logger = inject(DynamicFormLogger) as Logger;\n const cacheService = inject(AsyncConditionFunctionCacheService);\n\n const pendingValue = condition.pendingValue ?? false;\n const debounceMs = condition.debounceMs ?? 300;\n\n // Check function cache\n const cacheKey = stableStringify(condition);\n\n const cached = cacheService.asyncConditionFunctionCache.get(cacheKey);\n if (cached) {\n return cached as LogicFn<TValue, boolean>;\n }\n\n // Each condition needs its own per-field signal store.\n const perFunctionSignalStore = new Map<\n string,\n {\n trigger: WritableSignal<string | undefined>;\n resultResource: Resource<boolean>;\n // Captures the FieldContext at the moment each trigger snapshot is produced.\n // The loader reads from this map using the trigger key, ensuring it always\n // uses the context that was active when the trigger was set — not a stale ref\n // that could be overwritten by a later LogicFn call before the loader executes.\n ctxByTrigger: Map<string, FieldContext<TValue>>;\n }\n >();\n\n const fn: LogicFn<TValue, boolean> = (ctx: FieldContext<TValue>) => {\n const contextKey = safeReadPathKeys(ctx as FieldContext<unknown>).join('.');\n let signalPair = perFunctionSignalStore.get(contextKey);\n\n if (!signalPair) {\n const trigger = signal<string | undefined>(undefined);\n const ctxByTrigger = new Map<string, FieldContext<TValue>>();\n\n // Wrap in untracked() to avoid NG0602: resource() internally creates effects,\n // which cannot be created inside a reactive context (computed). The LogicFn runs\n // inside Angular Signal Forms' BooleanOrLogic.compute (a computed), so we must\n // clear the active reactive consumer before creating the resource pipeline.\n const resultResource = untracked(() => {\n // Debounce the trigger to batch rapid form value changes.\n const debouncedTrigger = derivedFromDeferred(trigger, pipe(debounceTime(debounceMs), distinctUntilChanged()), {\n initialValue: undefined as string | undefined,\n injector,\n });\n\n // rxResource() manages the async function lifecycle natively with Observables:\n // auto-cancellation via unsubscription and signal-based reactivity.\n const asyncResource = rxResource({\n params: () => debouncedTrigger() ?? undefined,\n stream: ({ params: triggerKey }) => {\n // Look up the async function at call time (fresh reference)\n const asyncFn = functionRegistry.getAsyncConditionFunction(condition.asyncFunctionName);\n if (!asyncFn) {\n logger.warn(\n `Async Condition - function '${condition.asyncFunctionName}' not found. ` +\n `Register it in customFnConfig.asyncConditions.`,\n );\n return of(pendingValue);\n }\n\n // Retrieve the FieldContext that was captured when this trigger key was set.\n // This avoids a race condition where a mutable ref could be overwritten by\n // a later LogicFn call before the loader finishes executing.\n const capturedCtx = ctxByTrigger.get(triggerKey);\n if (!capturedCtx) return of(pendingValue);\n\n const evaluationContext = untracked(() =>\n fieldContextRegistry.createReactiveEvaluationContext(capturedCtx, functionRegistry.getCustomFunctions()),\n );\n\n // asyncFn may return Promise<boolean> or Observable<boolean>.\n // from() normalizes both to Observable.\n return from(asyncFn(evaluationContext)).pipe(\n map((result) => !!result),\n catchError((error) => {\n logger.warn('Async Condition - function failed:', error);\n return of(pendingValue);\n }),\n );\n },\n defaultValue: pendingValue,\n injector,\n });\n\n // Snapshot composition: preserve the previous boolean result during re-evaluation.\n // Without this, the condition would briefly flash to pendingValue when the async\n // function is re-invoked, causing visible UI flicker.\n return withPreviousValue(asyncResource);\n });\n\n signalPair = { trigger, resultResource, ctxByTrigger };\n perFunctionSignalStore.set(contextKey, signalPair);\n }\n\n // Build reactive evaluation context (creates signal dependencies on form values)\n const evaluationContext = fieldContextRegistry.createReactiveEvaluationContext(ctx, functionRegistry.getCustomFunctions());\n\n // Serialize evaluation context to detect changes\n const contextSnapshot = stableStringify({\n formValue: evaluationContext.formValue,\n fieldValue: evaluationContext.fieldValue,\n externalData: evaluationContext.externalData,\n });\n\n // Capture the FieldContext for this trigger key so the loader can retrieve it.\n // Only keep the latest — previous entries are stale once the trigger changes.\n const { trigger: triggerSignal, resultResource, ctxByTrigger } = signalPair;\n ctxByTrigger.clear();\n ctxByTrigger.set(contextSnapshot, ctx);\n\n untracked(() => {\n const current = triggerSignal();\n if (current !== contextSnapshot) {\n triggerSignal.set(contextSnapshot);\n }\n });\n\n return resultResource.value();\n };\n\n cacheService.asyncConditionFunctionCache.set(cacheKey, fn as LogicFn<unknown, boolean>);\n return fn;\n}\n","import { Signal, WritableSignal } from '@angular/core';\nimport { LogicFn } from '@angular/forms/signals';\n\n/**\n * Per-field debounced signal pair.\n */\ninterface DebouncedSignalPair {\n immediateValue: WritableSignal<boolean>;\n debouncedValue: Signal<boolean | undefined>;\n}\n\n/**\n * DI-scoped cache for logic functions and debounced signals.\n *\n * Replaces module-scoped WeakMaps to ensure SSR safety.\n * Scoped to the DynamicForm component via `provideDynamicFormDI()`.\n */\nexport class LogicFunctionCacheService {\n /** Cache for memoized logic functions, keyed by serialized expression. */\n readonly logicFunctionCache = new Map<string, LogicFn<unknown, boolean>>();\n\n /** Cache for debounced logic functions, keyed by serialized expression + debounceMs. */\n readonly debouncedLogicFunctionCache = new Map<string, LogicFn<unknown, boolean>>();\n\n /** Per-field signal store for debounced logic, keyed by field path. */\n readonly debouncedSignalStore = new Map<string, DebouncedSignalPair>();\n}\n","import { inject, Injector, signal, untracked } from '@angular/core';\nimport { toObservable, toSignal } from '@angular/core/rxjs-interop';\nimport { FieldContext, LogicFn } from '@angular/forms/signals';\nimport { debounceTime, distinctUntilChanged, startWith } from 'rxjs';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\nimport { stableStringify } from '../../utils/stable-stringify';\nimport { FieldContextRegistryService } from '../registry/field-context-registry.service';\nimport { FunctionRegistryService } from '../registry/function-registry.service';\nimport { evaluateCondition } from './condition-evaluator';\nimport { createHttpConditionLogicFunction } from './http-condition-logic-function';\nimport { createAsyncConditionLogicFunction } from './async-condition-logic-function';\nimport { LogicFunctionCacheService } from './logic-function-cache.service';\nimport { safeReadPathKeys } from '../../utils/safe-read-path-keys';\n\n/**\n * Recursively validates that HTTP/async conditions are not nested inside and/or composites.\n * These conditions require async resolution and cannot be evaluated synchronously\n * inside composite conditions.\n */\nfunction validateNoNestedHttpConditions(expression: ConditionalExpression): void {\n if (expression.type === 'and' || expression.type === 'or') {\n for (const sub of expression.conditions) {\n if (sub.type === 'http' || sub.type === 'async') {\n const label = sub.type === 'http' ? 'HTTP' : 'Async';\n throw new DynamicFormError(\n `${label} conditions cannot be nested inside '${expression.type}' composites. ` +\n `Move the ${label} condition to a separate logic entry on the field.`,\n );\n }\n validateNoNestedHttpConditions(sub);\n }\n }\n}\n\n/**\n * Create a logic function from a conditional expression.\n *\n * This function is used for creating logic functions for hidden, readonly, disabled, and required.\n * It uses the REACTIVE evaluation context, which allows the logic function to create\n * reactive dependencies on form values. When dependent fields change, the logic function\n * will be automatically re-evaluated.\n *\n * NOTE: For validators, use createEvaluationContext directly (with untracked) to prevent\n * infinite reactive loops. Validators with cross-field dependencies should be hoisted\n * to form-level using validateTree.\n *\n * @param expression The conditional expression to evaluate\n * @returns A LogicFn that evaluates the condition in the context of a field\n */\nexport function createLogicFunction<TValue>(expression: ConditionalExpression): LogicFn<TValue, boolean> {\n // Async conditions handle their own debouncing and async resolution\n if (expression?.type === 'async') {\n return createAsyncConditionLogicFunction(expression);\n }\n\n // HTTP conditions handle their own debouncing and async resolution\n if (expression?.type === 'http') {\n return createHttpConditionLogicFunction(expression);\n }\n\n // Validate that HTTP conditions aren't nested inside and/or composites\n if (expression) {\n validateNoNestedHttpConditions(expression);\n }\n\n // Inject services during factory creation, not during execution\n const functionRegistry = inject(FunctionRegistryService);\n const fieldContextRegistry = inject(FieldContextRegistryService);\n const cacheService = inject(LogicFunctionCacheService);\n\n // Generate cache key from serialized expression\n const cacheKey = stableStringify(expression);\n\n // Check cache first\n const cached = cacheService.logicFunctionCache.get(cacheKey);\n if (cached) {\n return cached as LogicFn<TValue, boolean>;\n }\n\n const fn: LogicFn<TValue, boolean> = (ctx: FieldContext<TValue>) => {\n // Create REACTIVE evaluation context for logic functions\n // This allows logic to re-evaluate when dependent fields change\n const evaluationContext = fieldContextRegistry.createReactiveEvaluationContext(ctx, functionRegistry.getCustomFunctions());\n\n return evaluateCondition(expression, evaluationContext);\n };\n\n // Cache the function\n cacheService.logicFunctionCache.set(cacheKey, fn as LogicFn<unknown, boolean>);\n return fn;\n}\n\n/**\n * Create a debounced logic function from a conditional expression.\n *\n * This function wraps the condition evaluation in a debounce mechanism,\n * so state changes only take effect after the specified delay.\n * Useful for avoiding UI flicker during rapid typing.\n *\n * @param expression The conditional expression to evaluate\n * @param debounceMs The debounce duration in milliseconds\n * @returns A LogicFn that evaluates the condition with debouncing\n */\nexport function createDebouncedLogicFunction<TValue>(expression: ConditionalExpression, debounceMs: number): LogicFn<TValue, boolean> {\n // Async conditions handle their own debouncing via condition.debounceMs\n if (expression?.type === 'async') {\n return createAsyncConditionLogicFunction(expression);\n }\n\n // HTTP conditions handle their own debouncing via condition.http.debounceMs\n if (expression?.type === 'http') {\n return createHttpConditionLogicFunction(expression);\n }\n\n // Validate that HTTP conditions aren't nested inside and/or composites\n if (expression) {\n validateNoNestedHttpConditions(expression);\n }\n\n // Inject services during factory creation, not during execution\n const functionRegistry = inject(FunctionRegistryService);\n const fieldContextRegistry = inject(FieldContextRegistryService);\n const injector = inject(Injector);\n const cacheService = inject(LogicFunctionCacheService);\n\n // Generate cache key including debounceMs\n const cacheKey = `${stableStringify(expression)}:${debounceMs}`;\n\n // Check cache first\n const cached = cacheService.debouncedLogicFunctionCache.get(cacheKey);\n if (cached) {\n return cached as LogicFn<TValue, boolean>;\n }\n\n const fn: LogicFn<TValue, boolean> = (ctx: FieldContext<TValue>) => {\n const contextKey = safeReadPathKeys(ctx as FieldContext<unknown>).join('.');\n let signalPair = cacheService.debouncedSignalStore.get(contextKey);\n\n if (!signalPair) {\n // Create a signal to hold the immediate evaluation result\n const immediateValue = signal(false);\n\n // Wrap in untracked() to avoid NG0602: toObservable() internally calls effect(),\n // which cannot be created inside a reactive context (computed). The LogicFn runs\n // inside Angular Signal Forms' BooleanOrLogic.compute (a computed).\n const debouncedValue = untracked(() => {\n const immediateValue$ = toObservable(immediateValue, { injector }).pipe(\n debounceTime(debounceMs),\n distinctUntilChanged(),\n startWith(false),\n );\n\n return toSignal(immediateValue$, { injector, initialValue: false });\n });\n\n signalPair = { immediateValue, debouncedValue };\n cacheService.debouncedSignalStore.set(contextKey, signalPair);\n }\n\n // Create REACTIVE evaluation context for logic functions\n const evaluationContext = fieldContextRegistry.createReactiveEvaluationContext(ctx, functionRegistry.getCustomFunctions());\n\n // Evaluate the condition and update the immediate signal\n const result = evaluateCondition(expression, evaluationContext);\n\n // Update immediate value (this triggers the debounce chain)\n // signalPair is guaranteed to exist here due to the initialization above\n const { immediateValue, debouncedValue } = signalPair;\n untracked(() => {\n if (immediateValue() !== result) {\n immediateValue.set(result);\n }\n });\n\n // Return the debounced value\n return debouncedValue() ?? false;\n };\n\n // Cache the function\n cacheService.debouncedLogicFunctionCache.set(cacheKey, fn as LogicFn<unknown, boolean>);\n return fn;\n}\n","import { LogicFn } from '@angular/forms/signals';\n\n/**\n * DI-scoped cache for dynamic value functions.\n *\n * Replaces module-scoped WeakMap to ensure SSR safety.\n * Scoped to the DynamicForm component via `provideDynamicFormDI()`.\n */\nexport class DynamicValueFunctionCacheService {\n /** Cache for memoized dynamic value functions, keyed by expression string. */\n readonly dynamicValueFunctionCache = new Map<string, LogicFn<unknown, unknown>>();\n}\n","import { inject } from '@angular/core';\nimport { FieldContext, LogicFn } from '@angular/forms/signals';\nimport { FieldContextRegistryService } from '../registry/field-context-registry.service';\nimport { ExpressionParser } from '../expressions/parser/expression-parser';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { DynamicValueFunctionCacheService } from './dynamic-value-function-cache.service';\n\n/**\n * Create a dynamic value function from an expression string.\n * Uses secure AST-based parsing.\n *\n * @param expression The expression string to evaluate\n * @returns A LogicFn that evaluates the expression in the context of a field\n */\nexport function createDynamicValueFunction<TValue, TReturn>(expression: string): LogicFn<TValue, TReturn> {\n // Inject services during factory creation, not during execution\n // This captures the service instance in the closure\n const fieldContextRegistry = inject(FieldContextRegistryService);\n const logger = inject(DynamicFormLogger);\n const cacheService = inject(DynamicValueFunctionCacheService);\n\n // Check cache first\n const cached = cacheService.dynamicValueFunctionCache.get(expression);\n if (cached) {\n return cached as LogicFn<TValue, TReturn>;\n }\n\n const fn: LogicFn<TValue, TReturn> = (ctx: FieldContext<TValue>) => {\n // Create evaluation context using the registry-based approach\n const evaluationContext = fieldContextRegistry.createEvaluationContext(ctx);\n\n try {\n // Use secure AST-based expression parser (already has LRU cache)\n return ExpressionParser.evaluate(expression, evaluationContext) as TReturn;\n } catch (error) {\n logger.error('Error evaluating dynamic expression:', expression, error);\n return undefined as TReturn;\n }\n };\n\n // Cache the function\n cacheService.dynamicValueFunctionCache.set(expression, fn as LogicFn<unknown, unknown>);\n return fn;\n}\n","import type { SchemaPath, SchemaPathTree } from '@angular/forms/signals';\nimport {\n email,\n FieldContext,\n LogicFn,\n max,\n maxLength,\n min,\n minLength,\n pattern,\n required,\n validate,\n validateAsync,\n validateHttp,\n ValidationError,\n} from '@angular/forms/signals';\nimport { inject } from '@angular/core';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\nimport {\n AsyncValidatorConfig,\n CustomValidatorConfig,\n DeclarativeHttpValidatorConfig,\n FunctionHttpValidatorConfig,\n isFunctionHttpValidator,\n ValidatorConfig,\n} from '../../models/validation/validator-config';\nimport { resolveHttpRequest } from '../http/http-request-resolver';\nimport { evaluateHttpValidationResponse } from '../http/http-response-evaluator';\nimport { createLogicFunction } from '../expressions/logic-function-factory';\nimport { createDynamicValueFunction } from '../values/dynamic-value-factory';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { FunctionRegistryService } from '../registry/function-registry.service';\nimport { FieldContextRegistryService } from '../registry/field-context-registry.service';\nimport { ExpressionParser } from '../expressions/parser/expression-parser';\nimport {\n isCrossFieldValidator,\n isCrossFieldBuiltInValidator,\n hasCrossFieldWhenCondition,\n isResourceBasedValidator,\n} from '../cross-field/cross-field-detector';\n\nfunction applyEmailValidator(path: SchemaPath<string>): void {\n email(path);\n}\n\nfunction applyMinValidator(path: SchemaPath<number>, value: number, expression?: string): void {\n if (expression) {\n min(path, createDynamicValueFunction<string | number | null, number | undefined>(expression));\n } else {\n min(path, value);\n }\n}\n\nfunction applyMaxValidator(path: SchemaPath<number>, value: number, expression?: string): void {\n if (expression) {\n max(path, createDynamicValueFunction<string | number | null, number | undefined>(expression));\n } else {\n max(path, value);\n }\n}\n\nfunction applyMinLengthValidator(path: SchemaPath<string>, value: number, expression?: string): void {\n if (expression) {\n minLength(path, createDynamicValueFunction<string, number>(expression));\n } else {\n minLength(path, value);\n }\n}\n\nfunction applyMaxLengthValidator(path: SchemaPath<string>, value: number, expression?: string): void {\n if (expression) {\n maxLength(path, createDynamicValueFunction<string, number>(expression));\n } else {\n maxLength(path, value);\n }\n}\n\nfunction applyPatternValidator(path: SchemaPath<string>, value: RegExp, expression?: string): void {\n if (expression) {\n pattern(\n path,\n createDynamicValueFunction<string | undefined, RegExp | undefined>(expression) as LogicFn<string | undefined, RegExp | undefined>,\n );\n } else {\n pattern(path, value);\n }\n}\n\nfunction createConditionalLogic(when: ConditionalExpression | undefined): LogicFn<unknown, boolean> | undefined {\n return when ? (createLogicFunction(when) as LogicFn<unknown, boolean>) : undefined;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Dynamic forms require any at the Angular API boundary\nexport function applyValidator(config: ValidatorConfig, fieldPath: SchemaPath<any> | SchemaPathTree<any>): void {\n const path = fieldPath as SchemaPath<unknown>;\n\n if (!isResourceBasedValidator(config) && (isCrossFieldBuiltInValidator(config) || hasCrossFieldWhenCondition(config))) {\n return;\n }\n\n switch (config.type) {\n case 'required':\n if (config.when) {\n required(path, { when: createLogicFunction(config.when) });\n } else {\n required(path);\n }\n break;\n case 'email':\n applyEmailValidator(fieldPath as SchemaPath<string>);\n break;\n case 'min':\n if (typeof config.value === 'number') {\n applyMinValidator(fieldPath as SchemaPath<number>, config.value, config.expression);\n }\n break;\n case 'max':\n if (typeof config.value === 'number') {\n applyMaxValidator(fieldPath as SchemaPath<number>, config.value, config.expression);\n }\n break;\n case 'minLength':\n if (typeof config.value === 'number') {\n applyMinLengthValidator(fieldPath as SchemaPath<string>, config.value, config.expression);\n }\n break;\n case 'maxLength':\n if (typeof config.value === 'number') {\n applyMaxLengthValidator(fieldPath as SchemaPath<string>, config.value, config.expression);\n }\n break;\n case 'pattern':\n if (config.value instanceof RegExp || typeof config.value === 'string') {\n let regexPattern: RegExp;\n if (typeof config.value === 'string') {\n try {\n regexPattern = new RegExp(config.value);\n } catch (e) {\n throw new DynamicFormError(\n `Invalid regex pattern in validator: '${config.value}' — ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n } else {\n regexPattern = config.value;\n }\n applyPatternValidator(fieldPath as SchemaPath<string>, regexPattern, config.expression);\n }\n break;\n case 'custom':\n applyCustomValidator(config, path);\n break;\n case 'async':\n applyAsyncValidator(config, path);\n break;\n case 'http':\n applyUnifiedHttpValidator(config, path);\n break;\n }\n}\n\nfunction applyCustomValidator(config: CustomValidatorConfig, fieldPath: SchemaPath<unknown>): void {\n if (isCrossFieldValidator(config)) {\n return;\n }\n\n let validatorFn: (ctx: FieldContext<unknown>) => ValidationError | ValidationError[] | null;\n\n if (config.expression) {\n validatorFn = createExpressionValidator(config);\n } else if (config.functionName) {\n validatorFn = createFunctionValidator(config);\n } else {\n const logger = inject(DynamicFormLogger);\n logger.warn('Custom validator must have either \"expression\" or \"functionName\"');\n return;\n }\n\n const whenLogic = createConditionalLogic(config.when);\n validate(fieldPath, (ctx: FieldContext<unknown>) => {\n if (whenLogic && !whenLogic(ctx)) return null;\n return validatorFn(ctx);\n });\n}\n\nfunction createFunctionValidator(\n config: CustomValidatorConfig,\n): (ctx: FieldContext<unknown>) => ValidationError | ValidationError[] | null {\n const logger = inject(DynamicFormLogger);\n const functionName = config.functionName;\n if (!functionName) {\n logger.warn('Custom validator missing functionName');\n return () => null;\n }\n\n const registry = inject(FunctionRegistryService);\n const validatorFn = registry.getValidator(functionName);\n\n if (!validatorFn) {\n throw new DynamicFormError(`Custom validator \"${functionName}\" not found. Register it with customFnConfig.validators.`);\n }\n\n return (ctx: FieldContext<unknown>) => validatorFn(ctx, config.params);\n}\n\nfunction createExpressionValidator(\n config: CustomValidatorConfig,\n): (ctx: FieldContext<unknown>) => ValidationError | ValidationError[] | null {\n const logger = inject(DynamicFormLogger);\n const expression = config.expression;\n if (!expression) {\n logger.warn('Custom validator missing expression');\n return () => null;\n }\n\n const fieldContextRegistry = inject(FieldContextRegistryService);\n const functionRegistry = inject(FunctionRegistryService);\n\n return (ctx: FieldContext<unknown>) => {\n try {\n const evaluationContext = fieldContextRegistry.createEvaluationContext(ctx, functionRegistry.getCustomFunctions());\n const result = ExpressionParser.evaluate(expression, evaluationContext);\n\n if (result) {\n return null;\n }\n\n const kind = config.kind || 'custom';\n const validationError: ValidationError & Record<string, unknown> = { kind };\n\n if (config.errorParams) {\n Object.entries(config.errorParams).forEach(([key, expression]) => {\n try {\n validationError[key] = ExpressionParser.evaluate(expression, evaluationContext);\n } catch (err) {\n logger.warn(`Error evaluating errorParam \"${key}\":`, expression, err);\n }\n });\n }\n\n return validationError;\n } catch (error) {\n // Gracefully degrade on errors (e.g., typos in field names, undefined functions)\n // Log for debugging while keeping form functional\n logger.error('Error evaluating custom validator expression:', expression, error);\n return { kind: config.kind || 'custom' };\n }\n };\n}\n\n/**\n * Apply async validator to field path using Angular's public validateAsync() API\n *\n * Angular's validateAsync uses the resource API, which requires:\n * - params: Function that computes params from field context\n * - factory: Function that creates ResourceRef from params signal\n * - onSuccess: Maps resource result to validation errors\n * - onError: Optional handler for resource errors\n */\nfunction applyAsyncValidator(config: AsyncValidatorConfig, fieldPath: SchemaPath<unknown>): void {\n const registry = inject(FunctionRegistryService);\n const validatorConfig = registry.getAsyncValidator(config.functionName);\n\n if (!validatorConfig) {\n throw new DynamicFormError(`Async validator \"${config.functionName}\" not found. Register it with customFnConfig.asyncValidators.`);\n }\n\n const whenLogic = createConditionalLogic(config.when);\n const asyncOptions = {\n params: (ctx: FieldContext<unknown>) => {\n if (whenLogic && !whenLogic(ctx)) return undefined;\n return validatorConfig.params(ctx, config.params);\n },\n factory: validatorConfig.factory,\n onSuccess: validatorConfig.onSuccess,\n onError: validatorConfig.onError,\n };\n\n validateAsync(fieldPath, asyncOptions as Parameters<typeof validateAsync>[1]);\n}\n\n/**\n * Unified handler for `type: 'http'` — discriminates between function-based and declarative\n * based on property presence.\n */\nfunction applyUnifiedHttpValidator(\n config: FunctionHttpValidatorConfig | DeclarativeHttpValidatorConfig,\n fieldPath: SchemaPath<unknown>,\n): void {\n if (isFunctionHttpValidator(config)) {\n applyFunctionHttpValidator(config, fieldPath);\n } else {\n applyDeclarativeHttpValidator(config, fieldPath);\n }\n}\n\n/**\n * Apply function-based HTTP validator to field path using Angular's public validateHttp() API.\n *\n * Angular's validateHttp requires:\n * - request: Function that returns URL string or HttpResourceRequest\n * - onSuccess: Maps HTTP response to validation errors (inverted logic!)\n * - onError: Optional handler for HTTP errors\n */\nfunction applyFunctionHttpValidator(config: FunctionHttpValidatorConfig, fieldPath: SchemaPath<unknown>): void {\n const registry = inject(FunctionRegistryService);\n const httpValidatorConfig = registry.getHttpValidator(config.functionName);\n\n if (!httpValidatorConfig) {\n throw new DynamicFormError(`HTTP validator \"${config.functionName}\" not found. Register it with customFnConfig.httpValidators.`);\n }\n\n const whenLogic = createConditionalLogic(config.when);\n const httpOptions = {\n request: (ctx: FieldContext<unknown>) => {\n if (whenLogic && !whenLogic(ctx)) return undefined;\n return httpValidatorConfig.request(ctx, config.params);\n },\n onSuccess: httpValidatorConfig.onSuccess,\n onError: httpValidatorConfig.onError,\n };\n\n validateHttp(fieldPath, httpOptions as Parameters<typeof validateHttp>[1]);\n}\n\n/**\n * Apply declarative HTTP validator — fully JSON-serializable, no function registration needed.\n *\n * Uses `resolveHttpRequest` to build the request from expressions and `evaluateHttpValidationResponse`\n * to map the HTTP response to a validation result.\n */\nfunction applyDeclarativeHttpValidator(config: DeclarativeHttpValidatorConfig, fieldPath: SchemaPath<unknown>): void {\n const fieldContextRegistry = inject(FieldContextRegistryService);\n const functionRegistry = inject(FunctionRegistryService);\n const logger = inject(DynamicFormLogger);\n const whenLogic = createConditionalLogic(config.when);\n\n validateHttp(fieldPath, {\n request: (ctx: FieldContext<unknown>) => {\n if (whenLogic && !whenLogic(ctx)) return undefined;\n // Use createReactiveEvaluationContext (not createEvaluationContext) because\n // validateHttp's request runs inside Angular's resource API — it NEEDS reactive\n // dependencies to re-trigger when the field value changes.\n const evalCtx = fieldContextRegistry.createReactiveEvaluationContext(ctx, functionRegistry.getCustomFunctions());\n // resolveHttpRequest returns null when a path param is undefined — convert to undefined to skip validation\n return resolveHttpRequest(config.http, evalCtx) ?? undefined;\n },\n onSuccess: (response: unknown) => {\n return evaluateHttpValidationResponse(response, config.responseMapping, logger);\n },\n onError: (error: unknown) => {\n logger.warn('HTTP validator request failed:', error);\n return { kind: config.responseMapping.errorKind };\n },\n } as Parameters<typeof validateHttp>[1]);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Dynamic forms require any at the Angular API boundary\nexport function applyValidators(configs: ValidatorConfig[], fieldPath: SchemaPath<any> | SchemaPathTree<any>): void {\n configs.forEach((config) => applyValidator(config, fieldPath));\n}\n","import { isDevMode } from '@angular/core';\nimport { disabled, hidden, readonly, required, LogicFn } from '@angular/forms/signals';\nimport type { SchemaPath, SchemaPathTree } from '@angular/forms/signals';\nimport {\n LogicConfig,\n isStateLogicConfig,\n isDerivationLogicConfig,\n LogicTrigger,\n type StateLogicType,\n} from '../../models/logic/logic-config';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { createLogicFunction, createDebouncedLogicFunction } from '../expressions/logic-function-factory';\nimport { DEFAULT_DEBOUNCE_MS } from '../../utils/debounce/debounce';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\n\ntype AnyLogicFn<TValue> = LogicFn<TValue, boolean> | (() => boolean);\n\n/**\n * Extracts the trigger from a StateLogicConfig, handling the discriminated union.\n */\nfunction getConfigTrigger(config: LogicConfig): LogicTrigger {\n if (!isStateLogicConfig(config)) {\n return 'onChange';\n }\n return config.trigger ?? 'onChange';\n}\n\n/**\n * Extracts debounceMs from a StateLogicConfig if trigger is 'debounced'.\n */\nfunction getConfigDebounceMs(config: LogicConfig): number | undefined {\n if (!isStateLogicConfig(config)) {\n return undefined;\n }\n // Type narrowing: debounceMs only exists when trigger is 'debounced'\n if (config.trigger === 'debounced') {\n return config.debounceMs;\n }\n return undefined;\n}\n\nexport function applyLogic<TValue>(config: LogicConfig, fieldPath: SchemaPath<TValue> | SchemaPathTree<TValue>): void {\n // Value derivations (including property derivations via targetProperty) are handled by their orchestrators — skip them.\n if (isDerivationLogicConfig(config)) return;\n\n // Guard against unrecognized logic types that may be added in the future.\n if (!isStateLogicConfig(config)) {\n if (isDevMode()) {\n console.warn(\n `[Dynamic Forms] Unrecognized logic config type '${(config as { type: string }).type}' in applyLogic. ` +\n 'This config will be ignored. If this is a new logic type, ensure it is handled explicitly.',\n );\n }\n return;\n }\n\n const path = fieldPath as SchemaPath<TValue>;\n const trigger = getConfigTrigger(config);\n const debounceMs = getConfigDebounceMs(config) ?? DEFAULT_DEBOUNCE_MS;\n\n if (typeof config.condition === 'boolean') {\n applyLogicFn(config.type, path, () => config.condition as boolean);\n return;\n }\n\n // Create appropriate logic function based on trigger\n const logicFn =\n trigger === 'debounced'\n ? createDebouncedLogicFunction(config.condition as ConditionalExpression, debounceMs)\n : createLogicFunction(config.condition as ConditionalExpression);\n\n applyLogicFn(config.type, path, logicFn);\n}\n\nfunction applyLogicFn<TValue>(type: StateLogicType, path: SchemaPath<TValue>, logicFn: AnyLogicFn<TValue>): void {\n switch (type) {\n case 'hidden':\n hidden(path, logicFn);\n break;\n case 'readonly':\n readonly(path, logicFn);\n break;\n case 'disabled':\n disabled(path, logicFn);\n break;\n case 'required':\n required(path, { when: logicFn });\n break;\n default: {\n const _exhaustive: never = type;\n throw new DynamicFormError(`Unhandled state logic type: ${_exhaustive}`);\n }\n }\n}\n\nexport function applyMultipleLogic<TValue>(configs: LogicConfig[], fieldPath: SchemaPath<TValue> | SchemaPathTree<TValue>): void {\n configs.forEach((config) => applyLogic(config, fieldPath));\n}\n","import type { Logger } from '../../providers/features/logger/logger.interface';\nimport { ExpressionParser } from '../expressions/parser/expression-parser';\n\n/**\n * Create a type predicate function from a predicate string.\n *\n * Uses the secure ExpressionParser with whitelist-based evaluation instead of\n * dynamic code execution. This provides security through:\n * - AST-based parsing (no code execution)\n * - Whitelisted operators only\n * - Whitelisted methods only (Array.isArray, typeof, instanceof, etc.)\n * - No access to global scope beyond whitelisted constructors\n *\n * @param predicate - A JavaScript expression that evaluates to boolean. The value to check is available as `value`.\n * @param logger - Logger for error reporting\n * @returns A type predicate function\n *\n * @example\n * createTypePredicateFunction('typeof value === \"string\"')\n * createTypePredicateFunction('Array.isArray(value)')\n * createTypePredicateFunction('value instanceof Date')\n */\nexport function createTypePredicateFunction<T = unknown>(predicate: string, logger: Logger): (value: unknown) => value is T {\n return (value: unknown): value is T => {\n try {\n // Evaluate using secure AST-based parser with value in scope\n const result = ExpressionParser.evaluate(predicate, { value });\n return Boolean(result);\n } catch (error) {\n logger.error('Error evaluating type predicate:', predicate, error);\n return false;\n }\n };\n}\n","import { inject } from '@angular/core';\nimport { apply, applyEach, applyWhen, applyWhenValue, SchemaOrSchemaFn } from '@angular/forms/signals';\nimport type { SchemaPath, SchemaPathTree } from '@angular/forms/signals';\nimport { SchemaApplicationConfig, SchemaDefinition } from '../models/schemas/schema-definition';\nimport { SchemaRegistryService } from './registry/schema-registry.service';\nimport { createLogicFunction } from './expressions/logic-function-factory';\nimport { createTypePredicateFunction } from './values/type-predicate-factory';\nimport { applyValidator } from './validation/validator-factory';\nimport { applyLogic } from './logic/logic-applicator';\nimport { DynamicFormLogger } from '../providers/features/logger/logger.token';\n\n/**\n * Apply schema configuration.\n * Accepts both SchemaPath and SchemaPathTree for flexibility.\n *\n * Note: We cast fieldPath to suppress TypeScript's union type errors. This is safe because:\n * 1. We only use signal forms (not AbstractControl), so SchemaPathTree is always the supported branch\n * 2. The Angular apply functions accept SchemaPath with any value type\n * 3. The actual schema application happens at runtime via the schema function\n */\nexport function applySchema(config: SchemaApplicationConfig, fieldPath: SchemaPath<unknown> | SchemaPathTree<unknown>): void {\n const logger = inject(DynamicFormLogger);\n const schemaRegistry = inject(SchemaRegistryService);\n const schema = schemaRegistry.resolveSchema(config.schema);\n\n if (!schema) {\n const availableSchemas = Array.from(schemaRegistry.getAllSchemas().keys()).join(', ') || '<none>';\n logger.error(\n `Schema not found: '${config.schema}'. ` +\n `Available schemas: ${availableSchemas}. ` +\n `Ensure the schema is registered in your schema registry.`,\n );\n return;\n }\n\n const schemaFn = createSchemaFunction(schema);\n\n // Cast to suppress union type errors - safe because we only use signal forms (see function docs)\n const path = fieldPath as SchemaPath<unknown>;\n\n switch (config.type) {\n case 'apply':\n apply(path, schemaFn);\n break;\n\n case 'applyWhen':\n if (config.condition) {\n const conditionFn = createLogicFunction(config.condition);\n applyWhen(path, conditionFn, schemaFn);\n }\n break;\n\n case 'applyWhenValue':\n if (config.typePredicate) {\n const predicate = createTypePredicateFunction(config.typePredicate, logger);\n applyWhenValue(path, predicate, schemaFn);\n }\n break;\n\n case 'applyEach':\n applyEach(path as SchemaPath<unknown[]>, schemaFn);\n break;\n }\n}\n\n/**\n * Create a schema function from schema definition.\n *\n * Schema functions receive SchemaPathTree which includes both the base SchemaPath\n * and nested child access properties. The validator/logic/schema application functions\n * accept SchemaPath | SchemaPathTree, so we can pass the path directly.\n */\nexport function createSchemaFunction(schema: SchemaDefinition): SchemaOrSchemaFn<unknown> {\n return (path: SchemaPathTree<unknown>) => {\n // Apply validators - path is SchemaPathTree which is accepted by applyValidator\n schema.validators?.forEach((validatorConfig) => {\n applyValidator(validatorConfig, path);\n });\n\n // Apply logic - path is SchemaPathTree which is accepted by applyLogic\n schema.logic?.forEach((logicConfig) => {\n applyLogic(logicConfig, path);\n });\n\n // Apply sub-schemas - path is SchemaPathTree which is accepted by applySchema\n schema.subSchemas?.forEach((subSchemaConfig) => {\n applySchema(subSchemaConfig, path);\n });\n };\n}\n","import {\n disabled,\n email,\n hidden,\n max,\n maxLength,\n min,\n minLength,\n pattern,\n readonly,\n required,\n applyEach,\n schema,\n} from '@angular/forms/signals';\nimport type { SchemaPath, SchemaPathTree } from '@angular/forms/signals';\nimport { FieldDef } from '../definitions/base/field-def';\nimport { FieldWithValidation } from '../definitions/base/field-with-validation';\nimport { applyValidator } from './validation/validator-factory';\nimport { applyLogic } from './logic/logic-applicator';\nimport { applySchema } from './schema-application';\nimport { isGroupField } from '../definitions/default/group-field';\nimport { isArrayField } from '../definitions/default/array-field';\nimport { isPageField } from '../definitions/default/page-field';\nimport { isRowField } from '../definitions/default/row-field';\nimport { isContainerTypedField } from '../definitions/default/container-field';\nimport { DynamicFormError } from '../errors/dynamic-form-error';\n\n// Type alias for schema path parameters\ntype AnySchemaPath = SchemaPath<unknown> | SchemaPathTree<unknown>;\n\n// ============================================================================\n// Type-safe validator application functions\n// ============================================================================\n\ninterface StringValidationConfig {\n email?: boolean;\n minLength?: number;\n maxLength?: number;\n pattern?: string | RegExp;\n}\n\ninterface NumberValidationConfig {\n min?: number;\n max?: number;\n}\n\n/**\n * Applies string-specific validators to a schema path.\n * This function is properly typed - no casts needed internally.\n */\nfunction applyStringValidators(path: SchemaPath<string>, config: StringValidationConfig): void {\n if (config.email) {\n email(path);\n }\n if (config.minLength !== undefined) {\n minLength(path, config.minLength);\n }\n if (config.maxLength !== undefined) {\n maxLength(path, config.maxLength);\n }\n if (config.pattern) {\n let regex: RegExp;\n if (typeof config.pattern === 'string') {\n try {\n regex = new RegExp(config.pattern);\n } catch (e) {\n throw new DynamicFormError(`Invalid regex pattern: '${config.pattern}' — ${e instanceof Error ? e.message : String(e)}`);\n }\n } else {\n regex = config.pattern;\n }\n pattern(path, regex);\n }\n}\n\n/**\n * Applies number-specific validators to a schema path.\n * This function is properly typed - no casts needed internally.\n */\nfunction applyNumberValidators(path: SchemaPath<number>, config: NumberValidationConfig): void {\n if (config.min !== undefined) {\n min(path, config.min);\n }\n if (config.max !== undefined) {\n max(path, config.max);\n }\n}\n\n/**\n * Extracts string validation config from a field definition.\n * Returns undefined if no string validators are configured.\n */\nfunction getStringValidationConfig(fieldDef: FieldWithValidation): StringValidationConfig | undefined {\n if (!fieldDef.email && fieldDef.minLength === undefined && fieldDef.maxLength === undefined && !fieldDef.pattern) {\n return undefined;\n }\n return {\n email: fieldDef.email,\n minLength: fieldDef.minLength,\n maxLength: fieldDef.maxLength,\n pattern: fieldDef.pattern,\n };\n}\n\n/**\n * Extracts number validation config from a field definition.\n * Handles both 'min'/'max' (standard) and 'minValue'/'maxValue' (SliderField).\n * Returns undefined if no number validators are configured.\n */\nfunction getNumberValidationConfig(fieldDef: FieldWithValidation): NumberValidationConfig | undefined {\n const minVal = fieldDef.min ?? (fieldDef as { minValue?: number }).minValue;\n const maxVal = fieldDef.max ?? (fieldDef as { maxValue?: number }).maxValue;\n\n if (minVal === undefined && maxVal === undefined) {\n return undefined;\n }\n return { min: minVal, max: maxVal };\n}\n\n/**\n * Maps a field definition to the Angular Signal Forms schema.\n *\n * This is the main entry point that should be called from the dynamic form component.\n * It handles all field types: leaf fields, containers (page, row, group), and arrays.\n *\n * Cross-field logic (formValue.*) is handled automatically by createLogicFunction\n * which uses RootFormRegistryService.\n *\n * Cross-field validators are skipped at field level and applied at form level via validateTree.\n */\nexport function mapFieldToForm(fieldDef: FieldDef<unknown>, fieldPath: AnySchemaPath): void {\n // Layout containers (page, row, container) - flatten children to current level\n if (isPageField(fieldDef) || isRowField(fieldDef) || isContainerTypedField(fieldDef)) {\n mapContainerChildren(fieldDef.fields as FieldDef<unknown>[] | undefined, fieldPath);\n return;\n }\n\n // Group fields - map children under the group's path\n if (isGroupField(fieldDef)) {\n mapContainerChildren(fieldDef.fields, fieldPath);\n return;\n }\n\n // Array fields - use applyEach for item schema\n if (isArrayField(fieldDef)) {\n mapArrayFieldToForm(fieldDef, fieldPath);\n return;\n }\n\n // Leaf field - apply validation, logic, and configuration\n mapLeafField(fieldDef, fieldPath);\n}\n\n/**\n * Maps children of a container field (page, row, group) to the form schema.\n */\nfunction mapContainerChildren(fields: readonly FieldDef<unknown>[] | undefined, parentPath: AnySchemaPath): void {\n if (!fields) return;\n\n const pathRecord = parentPath as Record<string, AnySchemaPath>;\n\n for (const field of fields) {\n if (!field.key) continue;\n\n const childPath = pathRecord[field.key];\n if (childPath) {\n mapFieldToForm(field, childPath);\n }\n }\n}\n\n/**\n * Maps a leaf field (value-bearing field) to the form schema.\n */\nfunction mapLeafField(fieldDef: FieldDef<unknown>, fieldPath: AnySchemaPath): void {\n const validationField = fieldDef as FieldDef<unknown> & FieldWithValidation;\n const path = fieldPath as SchemaPath<unknown>;\n\n // Apply simple validation rules from field properties\n applySimpleValidationRules(validationField, path);\n\n if (validationField.validators) {\n for (const config of validationField.validators) {\n applyValidator(config, fieldPath);\n }\n }\n\n // Apply logic rules\n if (validationField.logic) {\n for (const config of validationField.logic) {\n applyLogic(config, fieldPath);\n }\n }\n\n // Apply schemas\n if (validationField.schemas) {\n for (const config of validationField.schemas) {\n applySchema(config, fieldPath);\n }\n }\n\n // Apply field state configuration\n applyFieldState(fieldDef, path);\n}\n\n/**\n * Applies simple validation rules from field properties.\n * Casts are isolated to the boundary between untyped field definitions and typed validator functions.\n */\nfunction applySimpleValidationRules(fieldDef: FieldWithValidation, path: SchemaPath<unknown>): void {\n if (fieldDef.required) {\n required(path);\n }\n\n // String validators - single cast at boundary\n const stringConfig = getStringValidationConfig(fieldDef);\n if (stringConfig) {\n applyStringValidators(path as SchemaPath<string>, stringConfig);\n }\n\n // Number validators - single cast at boundary\n const numberConfig = getNumberValidationConfig(fieldDef);\n if (numberConfig) {\n applyNumberValidators(path as SchemaPath<number>, numberConfig);\n }\n}\n\n/**\n * Applies field state configuration (disabled, readonly, hidden).\n */\nfunction applyFieldState(fieldDef: FieldDef<unknown>, path: SchemaPath<unknown>): void {\n if (fieldDef.disabled) {\n disabled(path);\n }\n\n if (fieldDef.readonly) {\n readonly(path);\n }\n\n if (fieldDef.hidden) {\n hidden(path, () => true);\n }\n}\n\n/**\n * Maps an array field to the form schema using applyEach.\n *\n * Supports two item formats:\n * - Primitive items: single FieldDef (not wrapped in array) → primitive value schema\n * - Object items: FieldDef[] (array of fields) → object schema with field keys\n *\n * Supports:\n * - Empty arrays (fields: []) - no initial items, add via buttons\n * - Primitive arrays - simple value lists like ['tag1', 'tag2']\n * - Object arrays - structured items like [{ name: 'Alice', email: '...' }]\n * - Heterogeneous arrays - mixed primitives and objects\n * - Container templates (row, group, page) that wrap children\n */\nfunction mapArrayFieldToForm(arrayField: FieldDef<unknown>, fieldPath: AnySchemaPath): void {\n if (!isArrayField(arrayField)) {\n return;\n }\n\n // Apply array-level length validation\n if (arrayField.minLength !== undefined) {\n minLength(fieldPath as SchemaPath<unknown[]>, arrayField.minLength);\n }\n if (arrayField.maxLength !== undefined) {\n maxLength(fieldPath as SchemaPath<unknown[]>, arrayField.maxLength);\n }\n\n // Fields can be either FieldDef (primitive) or FieldDef[] (object)\n const itemDefinitions = arrayField.fields as readonly (FieldDef<unknown> | readonly FieldDef<unknown>[])[];\n\n // Empty array is valid - items will be added via buttons with their own templates\n // Create a minimal schema that just accepts any value\n if (!itemDefinitions || itemDefinitions.length === 0) {\n const emptyItemSchema = schema<unknown>(() => {\n // No fields to map - items will be added dynamically via buttons\n });\n applyEach(fieldPath as SchemaPath<unknown[]>, emptyItemSchema);\n return;\n }\n\n // Analyze item definitions to determine schema type\n let hasPrimitiveItems = false;\n const allObjectFields: FieldDef<unknown>[] = [];\n\n for (const itemDef of itemDefinitions) {\n if (!Array.isArray(itemDef)) {\n // Primitive item: single FieldDef\n hasPrimitiveItems = true;\n } else {\n // Object item: collect fields for superset schema\n collectFieldsFromObjectItem(itemDef as readonly FieldDef<unknown>[], allObjectFields);\n }\n }\n\n // For pure primitive arrays, use a simple schema\n if (hasPrimitiveItems && allObjectFields.length === 0) {\n const primitiveItemSchema = schema<unknown>(() => {\n // Primitive items don't need field mapping - just accept any value\n });\n applyEach(fieldPath as SchemaPath<unknown[]>, primitiveItemSchema);\n return;\n }\n\n // For object or mixed arrays, use object schema with optional fields\n // Mixed arrays use the superset of all object fields (primitive items are just values)\n const itemSchema = schema<Record<string, unknown>>((itemPath) => {\n const pathRecord = itemPath as Record<string, AnySchemaPath>;\n\n // Map ALL unique template fields from all object items\n for (const templateField of allObjectFields) {\n if (isRowField(templateField) || isPageField(templateField) || isContainerTypedField(templateField)) {\n // Row/page/container templates flatten their children\n mapContainerChildren(templateField.fields as FieldDef<unknown>[] | undefined, itemPath);\n } else if (isGroupField(templateField)) {\n // Group template - access group's path first\n const groupKey = templateField.key;\n if (groupKey) {\n const groupPath = pathRecord[groupKey];\n if (groupPath) {\n mapContainerChildren(templateField.fields, groupPath);\n }\n } else {\n // No group key - apply children directly (edge case)\n mapContainerChildren(templateField.fields, itemPath);\n }\n } else {\n // Simple field template - get the specific field's path\n const fieldKey = templateField.key;\n if (fieldKey) {\n const fieldPathForKey = pathRecord[fieldKey];\n if (fieldPathForKey) {\n mapFieldToForm(templateField, fieldPathForKey);\n }\n }\n }\n }\n });\n\n applyEach(fieldPath as SchemaPath<Record<string, unknown>[]>, itemSchema);\n}\n\n/**\n * Collects unique field definitions from an object item template.\n * Uses field key as the uniqueness identifier.\n * When the same key appears in multiple templates, uses the first occurrence.\n */\nfunction collectFieldsFromObjectItem(itemFields: readonly FieldDef<unknown>[], allFields: FieldDef<unknown>[]): void {\n const seenKeys = new Set(allFields.map((f) => f.key).filter(Boolean));\n\n for (const field of itemFields) {\n // For row/page/container fields, we need to collect their children's keys\n if (isRowField(field) || isPageField(field) || isContainerTypedField(field)) {\n // Use a synthetic key for container fields to dedupe them\n const containerKey = `__container_${field.type}_${JSON.stringify(field.fields?.map((f) => f.key))}`;\n if (!seenKeys.has(containerKey)) {\n seenKeys.add(containerKey);\n allFields.push(field);\n }\n } else {\n const key = field.key;\n if (key && !seenKeys.has(key)) {\n seenKeys.add(key);\n allFields.push(field);\n }\n }\n }\n}\n","import { InjectionToken } from '@angular/core';\nimport { FieldDef } from '../definitions/base/field-def';\nimport { MapperFn } from '../mappers/types';\nimport { LazyComponentLoader } from './wrapper-type';\n\n/**\n * Defines how a field type handles form values and data collection.\n *\n * - 'include': Field contributes to form values (default for input fields)\n * - 'exclude': Field is excluded from form values (for display/layout fields)\n * - 'flatten': Field's children are flattened to parent level (for container fields)\n */\nexport type ValueHandlingMode = 'include' | 'exclude' | 'flatten';\n\n/**\n * Semantic grouping of interchangeable field UI alternatives.\n *\n * Used by tooling (e.g., openapi-generator) to discover which field types\n * can substitute for each other. A field with scope 'boolean' means it's\n * one of several ways to render a boolean value (checkbox, toggle, etc.).\n */\nexport type FieldScope = 'boolean' | 'single-select' | 'multi-select' | 'text-input' | 'numeric' | 'date';\n\n/**\n * Mapped component inputs that must be available before a field component is instantiated.\n *\n * This protects components that declare required Angular inputs and eagerly read them in\n * host bindings or computed signals. Renderers should defer component creation until all\n * listed mapped inputs are present.\n */\nexport type RenderReadyInput = 'field' | (string & {});\n\n/**\n * Configuration interface for registering custom field types.\n *\n * Defines how a field type should be handled by the dynamic form system,\n * including its component loading strategy and field-to-component mapping logic.\n * Supports both eager-loaded and lazy-loaded components.\n *\n * @typeParam T - The field definition type this field type handles\n *\n * @example\n * ```typescript\n * const CustomInputType: FieldTypeDefinition<InputFieldDef> = {\n * name: 'custom-input',\n * loadComponent: () => import('./custom-input.component').then(m => m.CustomInputComponent),\n * mapper: customInputMapper\n * };\n *\n * // Register with providers\n * provideDynamicForm(CustomInputType)\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Intentionally using `any` for maximum flexibility in field type registration\nexport interface FieldTypeDefinition<T extends FieldDef<any> = any> {\n /** Unique identifier for the field type */\n name: string;\n /** Field definition type marker (internal use) */\n _fieldDef?: T;\n /**\n * Function to load the component (supports lazy loading).\n * Returns a Promise that resolves to the component class or module with default export.\n *\n * Optional - omit for componentless fields (e.g., hidden fields) that only\n * contribute to form values without rendering any UI.\n */\n loadComponent?: LazyComponentLoader;\n /**\n * Mapper function that converts field definition to component bindings.\n *\n * Optional - omit for componentless fields (like hidden fields) that don't need\n * input mapping. When omitted for componentless fields (no loadComponent), an empty\n * signal is returned. When omitted for regular fields with a component, falls back\n * to baseFieldMapper.\n */\n mapper?: MapperFn<T>;\n /** How this field type handles form values and data collection (defaults to 'include') */\n valueHandling?: ValueHandlingMode;\n /**\n * List of prop keys to forward to the meta object.\n *\n * Some props (like `type` for inputs, `rows`/`cols` for textareas) are actually\n * native HTML attributes. Specifying them here causes them to be merged into\n * the meta object before being passed to the component, ensuring they're applied\n * via the meta tracking mechanism.\n *\n * Note: Meta values always take precedence over forwarded props.\n *\n * @example\n * ```typescript\n * {\n * name: 'input',\n * propsToMeta: ['type'],\n * // ...\n * }\n * ```\n */\n propsToMeta?: string[];\n /** Semantic scope for tooling to discover interchangeable field alternatives */\n scope?: FieldScope | FieldScope[];\n /** Mapped component inputs that must exist before the renderer instantiates the component */\n renderReadyWhen?: RenderReadyInput[];\n}\n\n/**\n * Injection token for the global field type registry.\n *\n * Provides access to the map of registered field types throughout the application.\n * The registry is populated by the provideDynamicForm function and used by\n * field rendering components to resolve field types to their implementations.\n *\n * @example\n * ```typescript\n * constructor(@Inject(FIELD_REGISTRY) private registry: Map<string, FieldTypeDefinition>) {\n * const inputType = registry.get('input');\n * }\n * ```\n */\nexport const FIELD_REGISTRY = new InjectionToken<Map<string, FieldTypeDefinition>>('FIELD_REGISTRY', {\n providedIn: 'root',\n factory: () => new Map(),\n});\n\n/**\n * Gets the value handling mode for a specific field type from the registry.\n *\n * @param fieldType - The field type identifier\n * @param registry - The field type registry\n * @returns The value handling mode ('include' is the default if not specified)\n */\nexport function getFieldValueHandling(fieldType: string, registry: Map<string, FieldTypeDefinition>): ValueHandlingMode {\n const definition = registry.get(fieldType);\n return definition?.valueHandling ?? 'include';\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { FieldTypeDefinition, getFieldValueHandling } from '../../models/field-type';\n\n/**\n * Generates appropriate default values for different field types in dynamic forms.\n *\n * Uses registry configuration to determine how each field type should handle values.\n * Supports exclude/flatten/include modes based on field type registration.\n *\n * @param field - Field definition to generate default value for\n * @param registry - Field type registry for value handling configuration\n * @returns Appropriate default value based on field type and configuration\n *\n * @example\n * ```typescript\n * // Basic input field defaults to empty string\n * getFieldDefaultValue({ type: 'input', key: 'email' }, registry); // ''\n *\n * // Excluded fields (like text/row) return undefined\n * getFieldDefaultValue({ type: 'text', key: 'label' }, registry); // undefined\n *\n * // Group field returns object with child defaults\n * getFieldDefaultValue({\n * type: 'group',\n * key: 'address',\n * fields: [\n * { type: 'input', key: 'street' },\n * { type: 'input', key: 'city', value: 'New York' }\n * ]\n * }, registry); // { street: '', city: 'New York' }\n * ```\n */\nexport function getFieldDefaultValue(field: FieldDef<unknown>, registry: Map<string, FieldTypeDefinition>): unknown {\n const valueHandling = getFieldValueHandling(field.type, registry);\n\n // Fields with 'exclude' handling don't contribute values\n if (valueHandling === 'exclude') {\n return undefined;\n }\n\n // Flatten fields (row/page) return flattened object of children's values\n // This is used by array fields to get the template structure\n // Note: fieldsToDefaultValues will skip these at top-level since they have keys and return objects\n if (valueHandling === 'flatten' && 'fields' in field && field.fields) {\n const childFields = field.fields as readonly FieldDef<unknown>[];\n\n // Collect only fields that contribute values (exclude buttons, text, etc.)\n const flattenedValues: Record<string, unknown> = {};\n for (const childField of childFields) {\n if ('key' in childField && childField.key) {\n const childValue = getFieldDefaultValue(childField, registry);\n if (childValue !== undefined) {\n flattenedValues[childField.key] = childValue;\n }\n }\n }\n\n // Return flattened object if there are any values, otherwise undefined\n return Object.keys(flattenedValues).length > 0 ? flattenedValues : undefined;\n }\n\n // Group fields with 'include' handling create nested objects\n if (field.type === 'group' && 'fields' in field) {\n const fields = field.fields as readonly FieldDef<unknown>[];\n if (!fields || fields.length === 0) {\n return undefined;\n }\n\n const groupDefaults: Record<string, unknown> = {};\n for (const childField of fields) {\n const childValueHandling = getFieldValueHandling(childField.type, registry);\n\n // Flatten row/page fields into the group (they are presentational containers)\n if (childValueHandling === 'flatten' && 'fields' in childField && childField.fields) {\n const nestedFields = childField.fields as readonly FieldDef<unknown>[];\n for (const nestedField of nestedFields) {\n if ('key' in nestedField && nestedField.key) {\n const nestedValue = getFieldDefaultValue(nestedField, registry);\n if (nestedValue !== undefined) {\n groupDefaults[nestedField.key] = nestedValue;\n }\n }\n }\n } else if ('key' in childField && childField.key) {\n const childValue = getFieldDefaultValue(childField, registry);\n if (childValue !== undefined) {\n groupDefaults[childField.key] = childValue;\n }\n }\n }\n return groupDefaults;\n }\n\n // Narrow once: `field` is FieldDef<unknown>, but value/nullable are defined on BaseValueField.\n // This cast avoids per-access `as` and documents what we're reading.\n const valueField = field as FieldDef<unknown> & { value?: unknown; nullable?: boolean };\n const isNullable = valueField.nullable === true;\n\n // Use explicit value if provided (including null when nullable)\n if ('value' in field) {\n if (valueField.value !== null && valueField.value !== undefined) {\n return valueField.value;\n }\n\n // Preserve explicit null for nullable fields\n if (valueField.value === null && isNullable) {\n return null;\n }\n\n // Non-nullable null and undefined both fall through to type-specific defaults below\n }\n\n // Nullable fields with no explicit value default to null\n if (isNullable) {\n return null;\n }\n\n // Type-specific defaults when no value is specified\n if (field.type === 'checkbox') {\n return false;\n }\n\n if (field.type === 'array') {\n // Array field supports two item formats:\n // - Primitive items: single FieldDef (not wrapped in array) → extracts field value directly\n // - Object items: FieldDef[] (array of fields) → merges fields into object\n const arrayField = field as { fields?: readonly (FieldDef<unknown> | readonly FieldDef<unknown>[])[] };\n const itemDefinitions = arrayField.fields;\n\n if (!itemDefinitions || itemDefinitions.length === 0) {\n return [];\n }\n\n // Process each item definition\n return itemDefinitions.map((itemDef) => {\n // Primitive item: single FieldDef (not wrapped in array)\n // Extract field value directly - key is for internal tracking only\n if (!Array.isArray(itemDef)) {\n return getFieldDefaultValue(itemDef as FieldDef<unknown>, registry);\n }\n\n // Object item: FieldDef[] - merge fields into object\n const itemFields = itemDef as readonly FieldDef<unknown>[];\n let itemValue: Record<string, unknown> = {};\n\n for (const templateField of itemFields) {\n const fieldValue = getFieldDefaultValue(templateField, registry);\n const fieldValueHandling = getFieldValueHandling(templateField.type, registry);\n\n if (templateField.type === 'group' && 'key' in templateField && templateField.key) {\n // Groups wrap their value under the group key\n itemValue[templateField.key] = fieldValue;\n } else if (templateField.type === 'row' || templateField.type === 'container') {\n // Rows and containers flatten their fields directly\n if (fieldValue && typeof fieldValue === 'object') {\n itemValue = { ...itemValue, ...(fieldValue as Record<string, unknown>) };\n }\n } else if (fieldValueHandling === 'include' && 'key' in templateField && templateField.key) {\n itemValue[templateField.key] = fieldValue;\n }\n }\n\n return itemValue;\n });\n }\n\n // Number inputs need a number type default for Angular signal forms\n // to use valueAsNumber for coercion. NaN is ideal because:\n // - typeof NaN === 'number' (triggers Angular's valueAsNumber path)\n // - NaN displays as empty in number inputs\n // - valueAsNumber returns NaN when input is cleared\n if (field.type === 'input' && 'props' in field) {\n const props = field.props as { type?: string } | undefined;\n if (props?.type === 'number') {\n return NaN;\n }\n }\n\n return '';\n}\n","import { schema, Schema, SchemaPathTree, validateStandardSchema } from '@angular/forms/signals';\n// Import from secondary entry point - this is correct for ng-packagr's entry point architecture\n// (different from importing internal barrel files which should be avoided)\nimport { isStandardSchemaMarker, type FormSchema } from '@ng-forge/dynamic-forms/schema';\n\n/**\n * Applies a form-level schema validation to a schema path.\n * Supports both Standard Schema (Zod, Valibot, ArkType) and raw Angular schema callbacks.\n *\n * This is a helper function used internally by `createSchemaFromFields`\n * to apply form-level validation after field-level validation.\n *\n * @typeParam TModel - The form value type\n * @param path - The schema path to validate (from Angular's schema callback)\n * @param formLevelSchema - Form-level schema (Standard Schema marker or Angular callback)\n *\n * @remarks\n * Type assertions are required due to Angular's complex generic constraints:\n * - `validateStandardSchema` uses `IgnoreUnknownProperties<TSchema>` to accommodate Zod's strict types\n * - `SchemaPathTree` includes `SchemaPath` via conditional types that TypeScript can't narrow\n * These assertions are safe because the path originates from Angular's schema() function.\n *\n * @internal\n */\nexport function applyFormLevelSchema<TModel>(path: SchemaPathTree<TModel>, formLevelSchema: FormSchema<TModel>): void {\n if (isStandardSchemaMarker(formLevelSchema)) {\n // Standard Schema (Zod, Valibot, ArkType, etc.)\n // Cast via Parameters: validateStandardSchema's IgnoreUnknownProperties<TSchema> creates type incompatibility\n // that TypeScript cannot resolve. The cast is safe as path comes from Angular's schema() callback.\n (validateStandardSchema as (...args: unknown[]) => void)(path, formLevelSchema.schema);\n } else if (typeof formLevelSchema === 'function') {\n // Angular schema callback - execute directly with the path\n // Cast via Function: AngularSchemaCallback expects intersection type SchemaPath & SchemaPathTree.\n // SchemaPathTree structurally includes SchemaPath, so this is safe at runtime.\n (formLevelSchema as (path: unknown) => void)(path);\n }\n}\n\n/**\n * Creates a schema from only form-level schema (when no field-level schema exists).\n *\n * Use this when the form has fields without validation rules but still\n * needs form-level validation via a Standard Schema.\n *\n * @typeParam TModel - The form value type\n * @param formLevelSchema - Form-level Standard Schema\n * @returns Schema that applies form-level validation\n *\n * @example\n * ```typescript\n * import { z } from 'zod';\n * import { standardSchema } from '@ng-forge/dynamic-forms/schema';\n *\n * const FormSchema = z.object({\n * email: z.string().email(),\n * password: z.string().min(8),\n * });\n *\n * // Create schema from form-level schema only\n * const formSchema = createFormLevelSchema(standardSchema(FormSchema));\n * ```\n */\nexport function createFormLevelSchema<TModel>(formLevelSchema: FormSchema<TModel>): Schema<TModel> {\n return schema<TModel>((path) => {\n applyFormLevelSchema(path, formLevelSchema);\n });\n}\n","import { inject } from '@angular/core';\nimport { Schema, schema, validateTree, FieldContext, ValidationError, FieldTree } from '@angular/forms/signals';\nimport type { SchemaPath, SchemaPathTree } from '@angular/forms/signals';\nimport { FieldDef } from '../definitions/base/field-def';\nimport { mapFieldToForm } from './form-mapping';\nimport { FieldTypeDefinition, getFieldValueHandling } from '../models/field-type';\nimport { getFieldDefaultValue } from '../utils/default-value/default-value';\nimport { CrossFieldValidatorEntry } from './cross-field/cross-field-types';\nimport { FunctionRegistryService } from './registry/function-registry.service';\nimport { ExpressionParser } from './expressions/parser/expression-parser';\nimport { evaluateCondition } from './expressions/condition-evaluator';\nimport { CustomValidatorConfig, ValidatorConfig } from '../models/validation/validator-config';\nimport { hasChildFields } from '../models/types/type-guards';\nimport { DynamicFormLogger } from '../providers/features/logger/logger.token';\nimport type { Logger } from '../providers/features/logger/logger.interface';\nimport { EvaluationContext } from '../models/expressions/evaluation-context';\nimport { normalizeFieldsArray } from '../utils/object-utils';\nimport { getNestedValue } from './expressions/value-utils';\nimport { applyFormLevelSchema } from './form-schema-merger';\nimport type { FormSchema } from '@ng-forge/dynamic-forms/schema';\n\nconst emailPattern = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/**\n * Gets a FieldTree by key, supporting nested paths with dot notation.\n *\n * @example\n * getFieldTreeByKey(ctx, 'address.street') // Returns FieldTree for nested 'street' field\n */\nfunction getFieldTreeByKey<TModel>(ctx: FieldContext<TModel>, key: string): FieldTree<unknown> | undefined {\n // Simple case - no nesting\n if (!key.includes('.')) {\n return (ctx.fieldTree as Record<string, FieldTree<unknown>>)[key];\n }\n\n // Nested path - traverse through the structure\n const parts = key.split('.');\n let current: unknown = ctx.fieldTree;\n\n for (const part of parts) {\n // FieldTree is callable (function), so typeof returns 'function' not 'object'.\n // Accept both to correctly traverse group sub-fields.\n if (!current || (typeof current !== 'object' && typeof current !== 'function')) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n\n return current as FieldTree<unknown> | undefined;\n}\n\n/**\n * Options for creating a schema from field definitions.\n */\nexport interface CreateSchemaOptions<TModel = unknown> {\n /**\n * Optional array of collected cross-field validators.\n */\n crossFieldValidators?: CrossFieldValidatorEntry[];\n\n /**\n * Optional form-level Standard Schema for additional validation.\n *\n * Supports Zod, Valibot, ArkType, and other Standard Schema compliant libraries.\n * Useful for cross-field validation rules.\n *\n * @example\n * ```typescript\n * import { z } from 'zod';\n * import { standardSchema } from '@ng-forge/dynamic-forms/schema';\n *\n * const PasswordSchema = z.object({\n * password: z.string().min(8),\n * confirmPassword: z.string(),\n * }).refine(\n * (data) => data.password === data.confirmPassword,\n * { message: 'Passwords must match', path: ['confirmPassword'] }\n * );\n *\n * const schema = createSchemaFromFields(fields, registry, {\n * formLevelSchema: standardSchema(PasswordSchema),\n * });\n * ```\n */\n formLevelSchema?: FormSchema<TModel>;\n}\n\n/**\n * Creates an Angular signal forms schema from field definitions\n * This is the single entry point at dynamic form level that replaces createSchemaFromFields\n * Uses the new modular signal forms adapter structure\n *\n * Cross-field logic (formValue.*) is handled automatically by createLogicFunction\n * which uses RootFormRegistryService. No special context needed.\n *\n * Cross-field validators are passed directly and applied at form level using validateTree.\n *\n * @param fields Field definitions to create schema from\n * @param registry Field type registry\n * @param optionsOrValidators Optional configuration object or array of cross-field validators (for backwards compatibility)\n */\nexport function createSchemaFromFields<TModel = unknown>(\n fields: FieldDef<unknown>[],\n registry: Map<string, FieldTypeDefinition>,\n optionsOrValidators?: CrossFieldValidatorEntry[] | CreateSchemaOptions<TModel>,\n): Schema<TModel> {\n // Inject services for cross-field validation\n // These will be available because createSchemaFromFields is called within runInInjectionContext\n const functionRegistry = inject(FunctionRegistryService);\n const logger = inject(DynamicFormLogger);\n\n // Normalize options - support both old array signature and new options object\n const options: CreateSchemaOptions<TModel> = Array.isArray(optionsOrValidators)\n ? { crossFieldValidators: optionsOrValidators }\n : (optionsOrValidators ?? {});\n\n const { crossFieldValidators, formLevelSchema } = options;\n\n return schema<TModel>((path) => {\n for (const fieldDef of fields) {\n const valueHandling = getFieldValueHandling(fieldDef.type, registry);\n\n // Handle different value handling modes\n if (valueHandling === 'exclude') {\n // Skip fields that don't contribute to form values\n continue;\n }\n\n if (valueHandling === 'flatten' && hasChildFields(fieldDef)) {\n for (const childField of normalizeFieldsArray(fieldDef.fields)) {\n if (!childField.key) continue;\n\n const childPath = (path as Record<string, SchemaPath<unknown>>)[childField.key];\n if (childPath) {\n mapFieldToForm(childField, childPath);\n }\n }\n continue;\n }\n\n // Regular field processing for 'include' fields\n const fieldPath = (path as Record<string, SchemaPath<unknown>>)[fieldDef.key];\n\n if (!fieldPath) {\n continue;\n }\n\n // Use the new modular form mapping function\n // This will progressively apply validators, logic, and schemas\n // Cross-field logic is handled automatically via RootFormRegistryService\n mapFieldToForm(fieldDef, fieldPath);\n }\n\n // Apply cross-field validators using validateTree\n if (crossFieldValidators && crossFieldValidators.length > 0) {\n applyCrossFieldTreeValidator(path as SchemaPathTree<TModel>, crossFieldValidators, functionRegistry, logger);\n }\n\n // Apply form-level Standard Schema validation\n if (formLevelSchema) {\n applyFormLevelSchema(path as SchemaPathTree<TModel>, formLevelSchema);\n }\n });\n}\n\n/**\n * Applies cross-field validators using Angular's validateTree API.\n *\n * This is the key integration point that routes cross-field validation errors\n * to the appropriate target fields via Angular's form state system.\n *\n * The validateTree function allows returning errors with a `fieldTree` property\n * that targets specific fields, which Angular automatically routes to those\n * fields' errors() signal.\n *\n * Supports two types of hoisted validators:\n * 1. Custom validators with cross-field expressions (e.g., `formValue.password === formValue.confirmPassword`)\n * 2. Built-in validators with cross-field `when` conditions (e.g., `required` when `country === 'USA'`)\n *\n * @param rootPath The root schema path tree\n * @param validators Array of collected cross-field validators\n * @param functionRegistry Registry containing custom functions for expression evaluation\n * @param logger Logger for error reporting\n */\nfunction applyCrossFieldTreeValidator<TModel>(\n rootPath: SchemaPathTree<TModel>,\n validators: CrossFieldValidatorEntry[],\n functionRegistry: FunctionRegistryService,\n logger: Logger,\n): void {\n // Get custom functions for expression evaluation\n const customFunctions = functionRegistry.getCustomFunctions();\n\n validateTree(rootPath as SchemaPath<TModel>, (ctx: FieldContext<TModel>) => {\n if (validators.length === 0) {\n return null; // ValidationSuccess - no errors\n }\n\n // Read form value reactively - don't wrap in untracked() so Angular can track dependencies\n const formValue = ctx.value() as Record<string, unknown>;\n const errors: ValidationError.WithOptionalField[] = [];\n\n for (const entry of validators) {\n const { sourceFieldKey, config } = entry;\n\n try {\n const error = evaluateCrossFieldValidator(entry, formValue, sourceFieldKey, ctx, customFunctions, logger);\n\n if (error) {\n errors.push(error);\n }\n } catch (err) {\n logger.error(`Error evaluating cross-field validator for ${sourceFieldKey}:`, err);\n\n // On error, add a validation error to indicate the failure\n const targetField = getFieldTreeByKey(ctx, sourceFieldKey);\n\n if (targetField) {\n const customConfig = config as CustomValidatorConfig;\n errors.push({\n kind: customConfig.kind || config.type || 'custom',\n fieldTree: targetField,\n });\n }\n }\n }\n\n return errors.length > 0 ? errors : null;\n });\n}\n\n/**\n * Evaluates a single cross-field validator entry and returns an error if validation fails.\n */\nfunction evaluateCrossFieldValidator<TModel>(\n entry: CrossFieldValidatorEntry,\n formValue: Record<string, unknown>,\n sourceFieldKey: string,\n ctx: FieldContext<TModel>,\n customFunctions: EvaluationContext['customFunctions'],\n logger: Logger,\n): ValidationError.WithOptionalField | null {\n const { config } = entry;\n const fieldValue = getNestedValue(formValue, sourceFieldKey);\n\n // Create evaluation context for condition/expression evaluation\n const evaluationContext: EvaluationContext = {\n fieldValue,\n formValue,\n fieldPath: sourceFieldKey,\n customFunctions,\n logger,\n };\n\n // Check if this is a custom validator (with expression) or a built-in validator (with when condition)\n if (config.type === 'custom') {\n return evaluateCustomCrossFieldValidator(config as CustomValidatorConfig, evaluationContext, sourceFieldKey, ctx);\n } else {\n // Built-in validator with cross-field when condition\n return evaluateBuiltInCrossFieldValidator(config, evaluationContext, sourceFieldKey, ctx);\n }\n}\n\n/**\n * Evaluates a custom cross-field validator with an expression.\n */\nfunction evaluateCustomCrossFieldValidator<TModel>(\n config: CustomValidatorConfig,\n evaluationContext: EvaluationContext,\n sourceFieldKey: string,\n ctx: FieldContext<TModel>,\n): ValidationError.WithOptionalField | null {\n if (!config.expression) {\n return null;\n }\n\n const { fieldValue, formValue, logger, customFunctions } = evaluationContext;\n\n // First, evaluate the when condition if present\n // If the condition is false, the validator doesn't apply (validation passes)\n if (config.when) {\n const conditionMet = evaluateCondition(config.when, {\n fieldValue,\n formValue,\n fieldPath: sourceFieldKey,\n customFunctions: customFunctions || {},\n logger,\n });\n\n if (!conditionMet) {\n return null; // Condition not met, skip validation\n }\n }\n\n // Evaluate expression using the secure AST parser\n const result = ExpressionParser.evaluate(config.expression, evaluationContext);\n\n // If expression returns truthy, validation passes (no error)\n if (result) {\n return null;\n }\n\n // Validation failed - create error targeting the source field\n const targetField = getFieldTreeByKey(ctx, sourceFieldKey);\n if (!targetField) {\n evaluationContext.logger.warn(`Cross-field validator references non-existent field \"${sourceFieldKey}\"`);\n return null;\n }\n\n const errorObj: Record<string, unknown> = {\n kind: config.kind || 'custom',\n fieldTree: targetField,\n };\n\n // Evaluate and include errorParams for message interpolation\n if (config.errorParams) {\n for (const [key, expression] of Object.entries(config.errorParams)) {\n try {\n errorObj[key] = ExpressionParser.evaluate(expression, evaluationContext);\n } catch (error) {\n evaluationContext.logger.warn(`Failed to evaluate error param expression \"${key}\": ${expression}`, error);\n }\n }\n }\n\n return errorObj as unknown as ValidationError.WithOptionalField;\n}\n\n/**\n * Evaluates a built-in validator with a cross-field when condition.\n * First checks the when condition, then applies the built-in validation logic.\n */\nfunction evaluateBuiltInCrossFieldValidator<TModel>(\n config: ValidatorConfig,\n evaluationContext: EvaluationContext,\n sourceFieldKey: string,\n ctx: FieldContext<TModel>,\n): ValidationError.WithOptionalField | null {\n const { fieldValue, formValue, logger, customFunctions } = evaluationContext;\n\n // First, evaluate the when condition\n // If the condition is false, the validator doesn't apply (validation passes)\n if (config.when) {\n const conditionMet = evaluateCondition(config.when, {\n fieldValue,\n formValue,\n fieldPath: sourceFieldKey,\n customFunctions: customFunctions || {},\n logger,\n });\n\n if (!conditionMet) {\n return null; // Condition not met, skip validation\n }\n }\n\n // Now apply the built-in validation logic based on the validator type\n const isValid = applyBuiltInValidationLogic(config, fieldValue);\n\n if (isValid) {\n return null; // Validation passed\n }\n\n // Validation failed - create error targeting the source field\n const targetField = getFieldTreeByKey(ctx, sourceFieldKey);\n if (!targetField) {\n logger.warn(`Cross-field validator references non-existent field \"${sourceFieldKey}\"`);\n return null;\n }\n\n return {\n kind: config.type,\n fieldTree: targetField,\n } as ValidationError.WithOptionalField;\n}\n\n/**\n * Applies built-in validation logic based on the validator type.\n * Returns true if validation passes, false if it fails.\n */\nfunction applyBuiltInValidationLogic(config: ValidatorConfig, fieldValue: unknown): boolean {\n switch (config.type) {\n case 'required':\n // Required: value must be non-null, non-undefined, and non-empty string\n if (fieldValue === null || fieldValue === undefined) {\n return false;\n }\n if (typeof fieldValue === 'string' && fieldValue.trim() === '') {\n return false;\n }\n return true;\n\n case 'min':\n // Min: numeric value must be >= min\n if (fieldValue === null || fieldValue === undefined) {\n return true; // Empty values pass min validation (use required for emptiness)\n }\n if ('value' in config && typeof config.value === 'number') {\n return (fieldValue as number) >= config.value;\n }\n return true;\n\n case 'max':\n // Max: numeric value must be <= max\n if (fieldValue === null || fieldValue === undefined) {\n return true;\n }\n if ('value' in config && typeof config.value === 'number') {\n return (fieldValue as number) <= config.value;\n }\n return true;\n\n case 'minLength':\n // MinLength: string length must be >= minLength\n if (fieldValue === null || fieldValue === undefined || fieldValue === '') {\n return true;\n }\n if ('value' in config && typeof config.value === 'number') {\n return String(fieldValue).length >= config.value;\n }\n return true;\n\n case 'maxLength':\n // MaxLength: string length must be <= maxLength\n if (fieldValue === null || fieldValue === undefined || fieldValue === '') {\n return true;\n }\n if ('value' in config && typeof config.value === 'number') {\n return String(fieldValue).length <= config.value;\n }\n return true;\n\n case 'email':\n // Email: must match email pattern\n if (fieldValue === null || fieldValue === undefined || fieldValue === '') {\n return true;\n }\n\n return emailPattern.test(String(fieldValue));\n\n case 'pattern':\n // Pattern: must match regex pattern\n if (fieldValue === null || fieldValue === undefined || fieldValue === '') {\n return true;\n }\n if ('value' in config && config.value) {\n const regex = config.value instanceof RegExp ? config.value : new RegExp(String(config.value));\n return regex.test(String(fieldValue));\n }\n return true;\n\n default:\n // Unknown validator type, consider valid\n return true;\n }\n}\n\n/**\n * Utility to convert field definitions to default values object\n */\nexport function fieldsToDefaultValues<TModel = unknown>(fields: FieldDef<unknown>[], registry: Map<string, FieldTypeDefinition>): TModel {\n const defaultValues: Record<string, unknown> = {};\n\n for (const field of fields) {\n if (!field.key) continue;\n\n // Skip flatten fields (row/page) at top level - they are presentational containers\n const valueHandling = getFieldValueHandling(field.type, registry);\n if (valueHandling === 'flatten') {\n continue;\n }\n\n const value = getFieldDefaultValue(field, registry);\n if (value !== undefined) {\n defaultValues[field.key] = value;\n }\n }\n\n return defaultValues as TModel;\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { FieldWithValidation } from '../../definitions/base/field-with-validation';\nimport { isStateLogicConfig, LogicConfig, StateLogicConfig } from '../../models/logic/logic-config';\nimport { ValidatorConfig, CustomValidatorConfig, BuiltInValidatorConfig } from '../../models/validation/validator-config';\nimport { ConditionalExpression } from '../../models/expressions/conditional-expression';\nimport { SchemaApplicationConfig } from '../../models/schemas/schema-definition';\nimport { hasChildFields, isGroupField } from '../../models/types/type-guards';\nimport { normalizeFieldsArray } from '../../utils/object-utils';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\nimport {\n isCrossFieldValidator,\n isCrossFieldBuiltInValidator,\n hasCrossFieldWhenCondition,\n isCrossFieldStateLogic,\n isCrossFieldSchema,\n extractExpressionDependencies,\n extractStringDependencies,\n} from './cross-field-detector';\nimport { CrossFieldValidatorEntry, CrossFieldLogicEntry, CrossFieldSchemaEntry, LogicType } from './cross-field-types';\n\n/** Collected cross-field entries from traversing field definitions. */\nexport interface CrossFieldCollection {\n validators: CrossFieldValidatorEntry[];\n logic: CrossFieldLogicEntry[];\n schemas: CrossFieldSchemaEntry[];\n}\n\n/** Creates an empty cross-field collection. */\nexport function createEmptyCollection(): CrossFieldCollection {\n return {\n validators: [],\n logic: [],\n schemas: [],\n };\n}\n\n/** Traverses field definitions and collects cross-field entries (validators, logic, schemas). */\nexport function collectCrossFieldEntries(fields: FieldDef<unknown>[]): CrossFieldCollection {\n const collection = createEmptyCollection();\n traverseFields(fields, collection, '');\n return collection;\n}\n\nfunction traverseFields(fields: FieldDef<unknown>[], collection: CrossFieldCollection, pathPrefix: string): void {\n for (const field of fields) {\n collectFromField(field, collection, pathPrefix);\n\n // Recursively process container fields (page, row, group, array)\n if (hasChildFields(field)) {\n // Groups add their key to the path prefix; page/row/array are transparent —\n // their children are still traversed, but those containers don't contribute a\n // key segment. Arrays are transparent rather than skipped because array items\n // use dynamic indices that aren't statically knowable, so no path prefix can\n // be built for them.\n const groupKey = isGroupField(field) ? field.key : undefined;\n const childPrefix = groupKey ? (pathPrefix ? `${pathPrefix}.${groupKey}` : groupKey) : pathPrefix;\n traverseFields(normalizeFieldsArray(field.fields) as FieldDef<unknown>[], collection, childPrefix);\n }\n }\n}\n\nfunction collectFromField(field: FieldDef<unknown>, collection: CrossFieldCollection, pathPrefix: string): void {\n const fieldKey = field.key;\n if (!fieldKey) return;\n\n const fullKey = pathPrefix ? `${pathPrefix}.${fieldKey}` : fieldKey;\n\n const validationField = field as FieldDef<unknown> & FieldWithValidation;\n\n // Collect cross-field validators\n if (validationField.validators) {\n for (const config of validationField.validators) {\n const entry = tryCreateValidatorEntry(fullKey, config);\n if (entry) {\n collection.validators.push(entry);\n }\n }\n }\n\n // Collect cross-field logic\n if (validationField.logic) {\n for (const config of validationField.logic) {\n const entry = tryCreateLogicEntry(fullKey, config);\n if (entry) {\n collection.logic.push(entry);\n }\n }\n }\n\n // Collect cross-field schemas\n if (validationField.schemas) {\n for (const config of validationField.schemas) {\n const entry = tryCreateSchemaEntry(fullKey, config);\n if (entry) {\n collection.schemas.push(entry);\n }\n }\n }\n}\n\n/** Returns a validator entry if cross-field, null otherwise. */\nfunction tryCreateValidatorEntry(fieldKey: string, config: ValidatorConfig): CrossFieldValidatorEntry | null {\n // Check for custom validators with cross-field expressions\n if (config.type === 'custom') {\n const customConfig = config as CustomValidatorConfig;\n if (isCrossFieldValidator(customConfig)) {\n return {\n sourceFieldKey: fieldKey,\n config,\n dependsOn: extractStringDependencies(customConfig.expression || ''),\n category: 'validator',\n };\n }\n }\n\n // Check for built-in validators with cross-field dynamic expressions\n if (isCrossFieldBuiltInValidator(config)) {\n const builtInConfig = config as BuiltInValidatorConfig;\n return {\n sourceFieldKey: fieldKey,\n config: convertBuiltInToCustomValidator(builtInConfig),\n validatorType: config.type,\n dependsOn: extractStringDependencies(builtInConfig.expression || ''),\n category: 'validator',\n };\n }\n\n // Check for validators with cross-field when conditions\n if (hasCrossFieldWhenCondition(config)) {\n const whenCondition = config.when as ConditionalExpression;\n return {\n sourceFieldKey: fieldKey,\n config,\n validatorType: config.type,\n dependsOn: extractExpressionDependencies(whenCondition),\n category: 'validator',\n };\n }\n\n return null;\n}\n\n/**\n * Returns a logic entry if cross-field state logic, null otherwise.\n *\n * Note: Derivation logic is handled separately by the derivation system\n * and is not collected here.\n */\nfunction tryCreateLogicEntry(fieldKey: string, config: LogicConfig): CrossFieldLogicEntry | null {\n // Only process state logic (hidden, readonly, disabled, required)\n // Derivation logic is handled by the derivation collector\n if (!isStateLogicConfig(config)) {\n return null;\n }\n\n if (!isCrossFieldStateLogic(config)) {\n return null;\n }\n\n const condition = config.condition as ConditionalExpression;\n return {\n sourceFieldKey: fieldKey,\n logicType: config.type as LogicType,\n condition,\n config: config as StateLogicConfig,\n dependsOn: extractExpressionDependencies(condition),\n category: 'logic',\n };\n}\n\n/** Returns a schema entry if cross-field, null otherwise. */\nfunction tryCreateSchemaEntry(fieldKey: string, config: SchemaApplicationConfig): CrossFieldSchemaEntry | null {\n if (!isCrossFieldSchema(config)) {\n return null;\n }\n\n const condition = config.condition as ConditionalExpression;\n return {\n sourceFieldKey: fieldKey,\n config,\n condition,\n dependsOn: extractExpressionDependencies(condition),\n category: 'schema',\n };\n}\n\n/** Converts a built-in validator with cross-field expression to a custom validator. */\nfunction convertBuiltInToCustomValidator(config: BuiltInValidatorConfig): CustomValidatorConfig {\n const expression = config.expression;\n if (!expression) {\n throw new DynamicFormError(`Built-in validator ${config.type} missing required expression for cross-field conversion`);\n }\n let validationExpression: string;\n\n switch (config.type) {\n case 'min':\n validationExpression = `fieldValue == null || fieldValue >= (${expression})`;\n break;\n case 'max':\n validationExpression = `fieldValue == null || fieldValue <= (${expression})`;\n break;\n case 'minLength':\n validationExpression = `fieldValue == null || (typeof fieldValue !== 'string' && !Array.isArray(fieldValue)) || fieldValue.length >= (${expression})`;\n break;\n case 'maxLength':\n validationExpression = `fieldValue == null || (typeof fieldValue !== 'string' && !Array.isArray(fieldValue)) || fieldValue.length <= (${expression})`;\n break;\n case 'pattern':\n // Validate regex pattern before injection to prevent runtime errors\n try {\n new RegExp(expression);\n } catch (e) {\n throw new DynamicFormError(\n `Invalid regex pattern in cross-field validator: '${expression}' — ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n validationExpression = `fieldValue == null || new RegExp(${JSON.stringify(expression)}).test(fieldValue)`;\n break;\n default:\n throw new DynamicFormError(`Cannot convert ${config.type} validator to custom validator`);\n }\n\n return {\n type: 'custom',\n expression: validationExpression,\n kind: config.type,\n when: config.when,\n errorParams: {\n [config.type]: expression,\n },\n };\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { isRowField } from '../../definitions/default/row-field';\nimport { isGroupField } from '../../definitions/default/group-field';\nimport { isArrayField } from '../../definitions/default/array-field';\nimport { isContainerTypedField } from '../../definitions/default/container-field';\nimport { FieldTypeDefinition, getFieldValueHandling } from '../../models/field-type';\nimport { normalizeFieldsArray } from '../object-utils';\n\n/**\n * Represents a field definition that has been processed through the flattening algorithm.\n *\n * Guarantees that the field has a valid key property, either from the original\n * field definition or auto-generated during the flattening process.\n *\n * @public\n */\nexport interface FlattenedField extends FieldDef<unknown> {\n /** Guaranteed non-empty key for form binding and field identification */\n readonly key: string;\n}\n\n/**\n * Flattens a hierarchical field structure into a linear array for form processing.\n *\n * Handles different field types with specific flattening strategies:\n * - **Page fields**: Children are flattened and merged into the result (no wrapper)\n * - **Row fields**: Children are flattened and merged into the result (no wrapper), unless preserveRows=true\n * - **Group fields**: Maintains group structure with flattened children nested under the group key\n * - **Array fields**: Maintains array structure with flattened children nested under the array key\n * - **Other fields**: Pass through unchanged with guaranteed key generation\n *\n * Auto-generates keys for fields missing the key property to ensure form binding works correctly.\n *\n * @param fields - Array of field definitions that may contain nested structures\n * @param registry - Field type registry for determining value handling behavior\n * @param options - Configuration options for flattening behavior\n * @param options.preserveRows - When true, keep row fields in structure for DOM rendering (grid layout)\n * @returns Flattened array of field definitions with guaranteed keys\n *\n * @example\n * ```typescript\n * const hierarchicalFields = [\n * {\n * type: 'row',\n * fields: [\n * { type: 'input', key: 'firstName' },\n * { type: 'input', key: 'lastName' }\n * ]\n * },\n * {\n * type: 'group',\n * key: 'address',\n * fields: [\n * { type: 'input', key: 'street' },\n * { type: 'input', key: 'city' }\n * ]\n * }\n * ];\n *\n * const flattened = flattenFields(hierarchicalFields, registry);\n * // Result: [\n * // { type: 'input', key: 'firstName' },\n * // { type: 'input', key: 'lastName' },\n * // { type: 'group', key: 'address', fields: [...] }\n * // ]\n * ```\n *\n * @example\n * ```typescript\n * // Auto-key generation for fields without keys\n * const fieldsWithoutKeys = [\n * { type: 'input', label: 'Name' },\n * { type: 'button', label: 'Submit' }\n * ];\n *\n * const flattened = flattenFields(fieldsWithoutKeys, registry);\n * // Result: [\n * // { type: 'input', label: 'Name', key: 'auto_field_0' },\n * // { type: 'button', label: 'Submit', key: 'auto_field_1' }\n * // ]\n * ```\n *\n * @public\n */\nexport function flattenFields(\n fields: FieldDef<unknown>[],\n registry: Map<string, FieldTypeDefinition>,\n options: { preserveRows?: boolean } = {},\n): FlattenedField[] {\n const result: FlattenedField[] = [];\n let autoKeyCounter = 0;\n\n // Process each field using appropriate strategy based on field type and configuration\n for (const field of fields) {\n // Step 1: Determine how this field type should handle its value in the form\n // valueHandling can be: 'include', 'exclude', or 'flatten'\n const valueHandling = getFieldValueHandling(field.type, registry);\n\n // Step 2: Check if this is a row or container field that should be preserved for DOM rendering\n // Row fields need to render their container element for grid layouts to work\n // Container fields need to render their container for the wrapper chain\n if (options.preserveRows && (isRowField(field) || isContainerTypedField(field))) {\n if (field.fields) {\n // Recursively flatten children while preserving row structure\n const flattenedChildren = flattenFields(normalizeFieldsArray(field.fields as FieldDef<unknown>[]), registry, options);\n\n // Keep the row/container field in the result with its flattened children\n // This allows the container component to render while children are flattened\n const autoPrefix = isRowField(field) ? 'auto_row' : 'auto_container';\n result.push({\n ...field,\n fields: flattenedChildren,\n key: field.key || `${autoPrefix}_${autoKeyCounter++}`,\n } as unknown as FlattenedField);\n }\n } else if (valueHandling === 'flatten' && 'fields' in field) {\n // Step 3: Handle fields with 'flatten' value handling (typically page/row fields)\n // These fields are pure containers - merge their children directly into the parent level\n if (field.fields) {\n const fields = field.fields as FieldDef<unknown>[] | Record<string, FieldDef<unknown>>;\n const flattenedChildren = flattenFields(normalizeFieldsArray(fields), registry, options);\n\n // Spread children directly into result - the container field itself is discarded\n // This is used for page fields (form structure) and row fields (form values)\n result.push(...flattenedChildren);\n }\n } else if (isGroupField(field)) {\n // Step 4: Handle group fields - preserve structure for nested form values\n // Group fields create a nested object in the form value: { groupKey: { field1: value1, ... } }\n const childFieldsArray = Object.values(field.fields) as FieldDef<unknown>[];\n const flattenedChildren = flattenFields(childFieldsArray, registry, options);\n\n // Keep the group field with its recursively flattened children nested under its key\n result.push({\n ...field,\n fields: flattenedChildren,\n key: field.key || `auto_group_${autoKeyCounter++}`,\n } as FlattenedField);\n } else if (isArrayField(field)) {\n // Step 5: Handle array fields - preserve structure for array form values\n // Array fields create an array in the form value: { arrayKey: [item1, item2, ...] }\n // field.fields is ArrayItemDefinition[] — each item is either:\n // - ArrayAllowedChildren (primitive item) → preserved as single FlattenedField\n // - ArrayItemTemplate (readonly ArrayAllowedChildren[]) → flattened as FlattenedField[]\n //\n // IMPORTANT: Preserve the primitive/object distinction so getFieldDefaultValue\n // can produce flat values (['angular']) vs nested values ([{value: 'angular'}]).\n const flattenedItemTemplates = field.fields.map((itemDef) => {\n if (!Array.isArray(itemDef)) {\n // Primitive item: single ArrayAllowedChildren → flatten, preserve non-array structure\n const flattened = flattenFields([itemDef as FieldDef<unknown>], registry, options);\n return flattened[0];\n }\n // Object item: ArrayItemTemplate (field[]) → flatten all fields as array\n return flattenFields([...(itemDef as FieldDef<unknown>[])], registry, options);\n });\n\n // Keep the array field with its flattened item templates nested under its key\n result.push({\n ...field,\n fields: flattenedItemTemplates,\n key: field.key || `auto_array_${autoKeyCounter++}`,\n } as FlattenedField);\n } else {\n // Step 6: Handle all other fields (inputs, buttons, etc.) - pass through unchanged\n // These fields are leaf nodes that don't contain children and map directly to form controls\n const key = field.key || `auto_field_${autoKeyCounter++}`;\n result.push({\n ...field,\n key,\n } as FlattenedField);\n }\n }\n\n return result;\n}\n","import { InjectionToken } from '@angular/core';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { FieldTypeDefinition } from '../../models/field-type';\nimport { flattenFields } from '../flattener/field-flattener';\nimport { getFieldDefaultValue } from '../default-value/default-value';\nimport { keyBy, memoize, mapValues } from '../object-utils';\n\n/**\n * Creates memoized field processing functions shared across container components.\n *\n * These functions are used by both `FormStateManager` and `GroupFieldComponent`\n * to compute flattened fields, field lookups, and default values from field definitions.\n *\n * @returns Object containing memoized processing functions\n */\nexport function createContainerFieldProcessors() {\n const createFieldsResolver =\n (preserveRows = false) =>\n (fields: readonly FieldDef<unknown>[], registry: Map<string, FieldTypeDefinition>) => {\n let key = '';\n for (const f of fields) {\n key += (f.key ?? '') + ':' + (f.type ?? '') + '|';\n }\n return key + registry.size + '|' + preserveRows;\n };\n\n const memoizedFlattenFields = memoize(\n (fields: readonly FieldDef<unknown>[], registry: Map<string, FieldTypeDefinition>) => flattenFields([...fields], registry),\n {\n // registry.size is a valid cache key proxy because the field registry is populated\n // once at bootstrap and never mutated at runtime. If the registry were mutable,\n // we would need a content-based hash instead.\n resolver: createFieldsResolver(),\n maxSize: 10,\n },\n );\n\n const memoizedFlattenFieldsForRendering = memoize(\n (fields: readonly FieldDef<unknown>[], registry: Map<string, FieldTypeDefinition>) =>\n flattenFields([...fields], registry, { preserveRows: true }),\n {\n // registry.size is a valid cache key proxy because the field registry is populated\n // once at bootstrap and never mutated at runtime. If the registry were mutable,\n // we would need a content-based hash instead.\n resolver: createFieldsResolver(true),\n maxSize: 10,\n },\n );\n\n const memoizedKeyBy = memoize(<T extends { key: string }>(fields: T[]) => keyBy(fields, 'key'), {\n resolver: (fields) => {\n let key = '';\n for (const f of fields) {\n key += f.key + '|';\n }\n return key;\n },\n maxSize: 10,\n });\n\n const memoizedDefaultValues = memoize(\n <T extends FieldDef<unknown>>(fieldsById: Record<string, T>, registry: Map<string, FieldTypeDefinition>) =>\n mapValues(fieldsById, (field) => getFieldDefaultValue(field, registry)),\n {\n // registry.size is a valid cache key proxy because the field registry is populated\n // once at bootstrap and never mutated at runtime.\n resolver: (fieldsById, registry) => {\n const keys = Object.keys(fieldsById).sort();\n return keys.join('|') + '|' + registry.size;\n },\n maxSize: 10,\n },\n );\n\n return { memoizedFlattenFields, memoizedFlattenFieldsForRendering, memoizedKeyBy, memoizedDefaultValues };\n}\n\n/**\n * Shared container field processors injection token.\n *\n * Provided at the DynamicForm component level via `provideDynamicFormDI()` so one\n * form + all its nested groups share a single memoize cache, while different form\n * instances stay isolated.\n *\n * The `providedIn: 'root'` factory is a fallback only — it ensures tests and\n * standalone containers (e.g. a bare GroupFieldComponent in a unit test) can\n * resolve the token without an explicit provider. In a running application, the\n * component-level provider from `provideDynamicFormDI()` always shadows this root\n * instance, so each form gets its own isolated cache.\n *\n * @internal\n */\nexport const CONTAINER_FIELD_PROCESSORS = new InjectionToken<ReturnType<typeof createContainerFieldProcessors>>(\n 'CONTAINER_FIELD_PROCESSORS',\n {\n providedIn: 'root',\n factory: () => createContainerFieldProcessors(),\n },\n);\n","import { FieldDef } from '../../definitions/base/field-def';\n\n/**\n * Generates CSS class string for responsive grid layout based on field column configuration.\n *\n * Creates Bootstrap-style column classes for implementing responsive form layouts.\n * Validates column values to ensure they fall within the standard 12-column grid system.\n *\n * @param fieldDef - Field definition containing column configuration\n * @returns CSS class string for grid layout, empty if no valid column configuration\n *\n * @example\n * ```typescript\n * // Full width field\n * const fullWidth = getGridClassString({ type: 'input', key: 'name', col: 12 });\n * // Returns: 'df-col-12'\n *\n * // Half width field\n * const halfWidth = getGridClassString({ type: 'input', key: 'email', col: 6 });\n * // Returns: 'df-col-6'\n *\n * // Invalid column value\n * const invalid = getGridClassString({ type: 'input', key: 'phone', col: 15 });\n * // Returns: ''\n * ```\n *\n * @public\n */\nexport function getGridClassString(fieldDef: FieldDef<unknown>): string {\n const col = fieldDef.col;\n if (typeof col === 'number' && Number.isInteger(col) && col > 0 && col <= 12) {\n return `df-col-${col}`;\n }\n return '';\n}\n\n/**\n * Builds a combined className string from a field definition.\n *\n * Combines user-provided className with generated grid classes into a single string.\n * Returns undefined if no classes are present (allowing conditional spreading in objects).\n *\n * @param fieldDef - Field definition containing className and col properties\n * @returns Combined class string, or undefined if no classes\n *\n * @example\n * ```typescript\n * // With both className and col\n * buildClassName({ key: 'test', type: 'group', className: 'my-class', col: 6 });\n * // Returns: 'df-col-6 my-class'\n *\n * // With only className\n * buildClassName({ key: 'test', type: 'group', className: 'my-class' });\n * // Returns: 'my-class'\n *\n * // With only col\n * buildClassName({ key: 'test', type: 'group', col: 6 });\n * // Returns: 'df-col-6'\n *\n * // With neither\n * buildClassName({ key: 'test', type: 'group' });\n * // Returns: undefined\n * ```\n *\n * @public\n */\nexport function buildClassName(fieldDef: FieldDef<unknown>): string | undefined {\n const gridClass = getGridClassString(fieldDef);\n const userClass = fieldDef.className;\n\n const classes: string[] = [];\n\n if (gridClass) {\n classes.push(gridClass);\n }\n\n if (userClass) {\n classes.push(userClass);\n }\n\n return classes.length > 0 ? classes.join(' ') : undefined;\n}\n","import { computed, Signal } from '@angular/core';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { getGridClassString } from '../../utils/grid-classes/grid-classes';\n\n/**\n * Builds base input properties from a field definition.\n *\n * This is a helper function that extracts common field properties.\n * Used by mappers to build the inputs record.\n *\n * @param fieldDef The field definition to extract properties from\n * @param defaultProps Optional form-level default props to merge with field props\n * @returns Record of input names to values\n */\nexport function buildBaseInputs(fieldDef: FieldDef<unknown>, defaultProps?: Record<string, unknown>): Record<string, unknown> {\n const { key, label, className, tabIndex, props, meta } = fieldDef;\n const inputs: Record<string, unknown> = {};\n\n // Always include key - required by components for accessibility and identification\n inputs['key'] = key;\n\n if (label !== undefined) {\n inputs['label'] = label;\n }\n\n // Combine user className with generated grid classes\n const gridClassString = getGridClassString(fieldDef);\n const allClasses: string[] = [];\n\n if (gridClassString) {\n allClasses.push(gridClassString);\n }\n\n if (className) {\n allClasses.push(className);\n }\n\n if (allClasses.length > 0) {\n inputs['className'] = allClasses.join(' ');\n }\n\n if (tabIndex !== undefined) {\n inputs['tabIndex'] = tabIndex;\n }\n\n // Merge props: form-level defaultProps as base, field-level props override\n // Cast props to Record since it's typed as unknown but always represents an object at runtime\n const fieldProps = props as Record<string, unknown> | undefined;\n const mergedProps =\n fieldProps !== undefined || defaultProps !== undefined ? { ...(defaultProps ?? {}), ...(fieldProps ?? {}) } : undefined;\n\n if (mergedProps !== undefined) {\n inputs['props'] = mergedProps;\n }\n\n if (meta !== undefined) {\n inputs['meta'] = meta;\n }\n\n return inputs;\n}\n\n/**\n * Base field mapper that extracts common field properties into component inputs.\n *\n * Returns a Signal containing the Record of input names to values that will be\n * passed to ngComponentOutlet. The signal enables reactive updates.\n *\n * @param fieldDef The field definition to map\n * @returns Signal containing Record of input names to values\n */\nexport function baseFieldMapper(fieldDef: FieldDef<unknown>): Signal<Record<string, unknown>> {\n // For base mapper, inputs are static (no reactive dependencies)\n // Wrap in computed for consistency with the MapperFn type\n return computed(() => buildBaseInputs(fieldDef));\n}\n","import { InjectionToken, signal, Signal, WritableSignal } from '@angular/core';\nimport { isEqual } from '../../utils/object-utils';\n\n/**\n * Per-field signal store for property overrides.\n *\n * Each field that has property derivations gets a WritableSignal containing\n * a record of property names to their override values. Mappers read from\n * this store reactively — only the specific field's signal is read, so\n * changes to one field's overrides don't cause other fields to recompute.\n *\n * @public\n */\nexport interface PropertyOverrideStore {\n /**\n * Gets the override signal for a field.\n *\n * Lazily creates a per-field signal on first access. Subsequent calls\n * return the same signal instance.\n *\n * @param fieldKey - The store key (e.g., 'endDate' or 'contacts.0.email')\n * @returns Signal containing the current overrides record\n */\n getOverrides(fieldKey: string): Signal<Record<string, unknown>>;\n\n /**\n * Sets a single property override for a field.\n *\n * Uses deep equality to skip no-op updates. Setting `undefined` as the value\n * removes the property key from the override record.\n *\n * @param fieldKey - The store key\n * @param targetProperty - The property name (e.g., 'minDate', 'options')\n * @param value - The override value, or undefined to remove\n */\n setOverride(fieldKey: string, targetProperty: string, value: unknown): void;\n\n /**\n * Registers a field as having property derivations.\n *\n * Called by the orchestrator during collection. Enables the fast-path\n * check in mappers via `hasField()`.\n *\n * @param fieldKey - The store key to register\n */\n registerField(fieldKey: string): void;\n\n /**\n * Non-reactive check for whether a field has been registered.\n *\n * Uses plain Map.has() — O(1), no signal creation. Used by mappers\n * to skip the computed() wrapper for fields without property derivations.\n *\n * @param fieldKey - The store key (or prefix for array fields)\n * @returns true if the field has property derivation entries\n */\n hasField(fieldKey: string): boolean;\n\n /**\n * Clears all overrides and registered fields.\n *\n * Prunes the internal Map entirely, releasing all signal references.\n * Called when the form config changes (new collection = reset).\n */\n clear(): void;\n}\n\nconst EMPTY_OVERRIDES: Record<string, unknown> = Object.freeze({});\n\n/**\n * Creates a new PropertyOverrideStore instance.\n *\n * @returns A fresh PropertyOverrideStore\n *\n * @public\n */\nexport function createPropertyOverrideStore(): PropertyOverrideStore {\n const store = new Map<string, WritableSignal<Record<string, unknown>>>();\n const registeredFields = new Set<string>();\n\n function getOrCreateSignal(fieldKey: string): WritableSignal<Record<string, unknown>> {\n let existing = store.get(fieldKey);\n if (!existing) {\n existing = signal(EMPTY_OVERRIDES);\n store.set(fieldKey, existing);\n }\n return existing;\n }\n\n return {\n getOverrides(fieldKey: string): Signal<Record<string, unknown>> {\n return getOrCreateSignal(fieldKey);\n },\n\n setOverride(fieldKey: string, targetProperty: string, value: unknown): void {\n const fieldSignal = getOrCreateSignal(fieldKey);\n const current = fieldSignal();\n\n if (value === undefined) {\n // Remove the property key\n if (!(targetProperty in current)) {\n return; // Already absent, no-op\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { [targetProperty]: _, ...rest } = current;\n fieldSignal.set(Object.keys(rest).length === 0 ? EMPTY_OVERRIDES : rest);\n } else {\n // Set or update the property\n const currentValue = current[targetProperty];\n if (isEqual(currentValue, value)) {\n return; // Value unchanged, no-op\n }\n fieldSignal.set({ ...current, [targetProperty]: value });\n }\n },\n\n registerField(fieldKey: string): void {\n registeredFields.add(fieldKey);\n },\n\n hasField(fieldKey: string): boolean {\n return registeredFields.has(fieldKey);\n },\n\n clear(): void {\n store.clear();\n registeredFields.clear();\n },\n };\n}\n\n/**\n * Injection token for the PropertyOverrideStore.\n *\n * @public\n */\nexport const PROPERTY_OVERRIDE_STORE = new InjectionToken<PropertyOverrideStore>('PROPERTY_OVERRIDE_STORE');\n","import { isDevMode } from '@angular/core';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\nimport { BaseValueField } from '../../definitions/base/base-value-field';\nimport { FieldWithValidation } from '../../definitions/base/field-with-validation';\n\n/** Properties defined by individual field components, not part of the shared base interfaces. */\ntype AdapterFieldKey = 'options' | 'hint' | 'tooltip' | 'prefix' | 'suffix' | 'step' | 'rows' | 'cols' | 'multiple' | 'appearance';\n\n/**\n * Known standard field properties where a missing key likely indicates a typo.\n * Override keys not in this set are assumed to be intentional dynamic properties\n * and will not trigger dev-mode warnings.\n */\nconst KNOWN_FIELD_PROPERTY_NAMES = [\n 'label',\n 'placeholder',\n 'disabled',\n 'readonly',\n 'required',\n 'className',\n 'tabIndex',\n 'validationMessages',\n 'options',\n 'props',\n 'hint',\n 'tooltip',\n 'prefix',\n 'suffix',\n 'min',\n 'max',\n 'minLength',\n 'maxLength',\n 'step',\n 'pattern',\n 'rows',\n 'cols',\n 'multiple',\n 'appearance',\n] as const satisfies ReadonlyArray<keyof BaseValueField<unknown, unknown> | keyof FieldWithValidation | AdapterFieldKey>;\n\nconst KNOWN_FIELD_PROPERTIES = new Set<string>(KNOWN_FIELD_PROPERTY_NAMES);\n\n/**\n * Applies property overrides to a field's input record.\n *\n * Supports dot-notation for nested properties (max 2 levels):\n * - Simple: `overrides['minDate']` → `inputs['minDate'] = value`\n * - Nested (1 dot): `overrides['props.appearance']` → `inputs.props.appearance = value`\n * - Deeper paths (2+ dots): throws DynamicFormError\n *\n * **Important:** Only simple (e.g., `'minDate'`) and single-nested (e.g., `'props.appearance'`)\n * paths are supported. Paths with 2+ dots will throw a `DynamicFormError` at runtime.\n * This is an architectural constraint — deeper nesting would require recursive cloning\n * and complicate the override merging strategy.\n *\n * Array-valued overrides replace wholesale (no merging).\n * Returns `inputs` unchanged if overrides is empty (no clone).\n *\n * In dev mode, warns when a known standard field property override key doesn't match\n * any existing input property, which may indicate a typo in the `targetProperty`\n * configuration. Dynamic/custom property keys are silently accepted.\n *\n * @param inputs - The current field inputs record\n * @param overrides - Record of property names to override values\n * @returns Updated inputs record with overrides applied\n *\n * @public\n */\nexport function applyPropertyOverrides(inputs: Record<string, unknown>, overrides: Record<string, unknown>): Record<string, unknown> {\n const keys = Object.keys(overrides);\n if (keys.length === 0) {\n return inputs;\n }\n\n const result = { ...inputs };\n\n for (const key of keys) {\n const value = overrides[key];\n const dotIndex = key.indexOf('.');\n\n // Dev-mode check: warn only when a known standard field property is missing from inputs,\n // which likely indicates a typo. Dynamic/custom keys are intentionally skipped to avoid\n // false positives for properties added by derivations that aren't in the initial config.\n if (isDevMode()) {\n const topLevelKey = dotIndex === -1 ? key : key.substring(0, dotIndex);\n if (KNOWN_FIELD_PROPERTIES.has(topLevelKey) && !(topLevelKey in inputs)) {\n console.warn(\n `[Dynamic Forms] Property override '${key}' does not match any existing input property. ` +\n 'This may indicate a typo in the targetProperty configuration. ' +\n `Available properties: ${Object.keys(inputs).join(', ')}`,\n );\n }\n }\n\n if (dotIndex === -1) {\n // Simple property: direct assignment\n result[key] = value;\n } else {\n // Nested property — split at first dot only\n const parentKey = key.substring(0, dotIndex);\n const childKey = key.substring(dotIndex + 1);\n\n // Validate max 2 levels (1 dot)\n if (childKey.includes('.')) {\n throw new DynamicFormError(\n `Property override path '${key}' exceeds maximum depth of 2 levels. ` +\n `Only simple ('minDate') and single-nested ('props.appearance') paths are supported.`,\n );\n }\n\n // Shallow-clone the parent object and set the child property\n const parentValue = result[parentKey];\n const clonedParent = parentValue && typeof parentValue === 'object' ? { ...(parentValue as Record<string, unknown>) } : {};\n clonedParent[childKey] = value;\n result[parentKey] = clonedParent;\n }\n }\n\n return result;\n}\n","import { computed, inject, isSignal, Signal } from '@angular/core';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { FieldMeta } from '../../definitions/base/field-meta';\nimport { FieldTypeDefinition } from '../../models/field-type';\nimport { ARRAY_CONTEXT } from '../../models/field-signal-context.token';\nimport { ArrayContext } from '../../mappers/types';\nimport { baseFieldMapper } from '../../mappers/base/base-field-mapper';\nimport { PROPERTY_OVERRIDE_STORE } from '../../core/property-derivation/property-override-store';\nimport { applyPropertyOverrides } from '../../core/property-derivation/apply-property-overrides';\nimport { buildPropertyOverrideKey, PLACEHOLDER_INDEX } from '../../core/property-derivation/property-override-key';\n\n/**\n * Merges forwarded props into meta, with meta taking precedence.\n *\n * @param inputs The current inputs record\n * @param propsToMeta Array of prop keys to forward to meta\n * @returns Updated inputs record with merged meta\n */\nfunction mergeForwardedPropsToMeta(inputs: Record<string, unknown>, propsToMeta: string[]): Record<string, unknown> {\n const props = inputs['props'] as Record<string, unknown> | undefined;\n if (!props || propsToMeta.length === 0) {\n return inputs;\n }\n\n // Extract values to forward from props\n // Values are typed as FieldMeta-compatible since they're forwarded attributes (type, rows, cols, etc.)\n const forwardedValues: FieldMeta = {};\n for (const key of propsToMeta) {\n const value = props[key];\n if (value !== undefined && value !== null) {\n // Props being forwarded are known HTML attributes (string, number, boolean)\n forwardedValues[key] = value as string | number | boolean;\n }\n }\n\n // If nothing to forward, return inputs unchanged\n if (Object.keys(forwardedValues).length === 0) {\n return inputs;\n }\n\n // Merge: forwarded props first, then meta (meta wins)\n const existingMeta = inputs['meta'] as FieldMeta | undefined;\n const mergedMeta: FieldMeta = {\n ...forwardedValues,\n ...existingMeta,\n };\n\n return {\n ...inputs,\n meta: mergedMeta,\n };\n}\n\n/**\n * Applies index suffix to the key property for array items.\n * This ensures unique DOM IDs while keeping form schema keys clean.\n *\n * @param inputs The current inputs record\n * @param index The array item index\n * @returns Updated inputs record with suffixed key\n */\nfunction applyIndexSuffix(inputs: Record<string, unknown>, index: number): Record<string, unknown> {\n const key = inputs['key'];\n if (typeof key !== 'string') {\n return inputs;\n }\n\n return {\n ...inputs,\n key: `${key}_${index}`,\n };\n}\n\n/**\n * Main field mapper function that uses the field registry to get the appropriate mapper\n * based on the field's type property.\n *\n * This function must be called within an injection context where FIELD_SIGNAL_CONTEXT\n * is provided, as mappers inject the context to access form state.\n *\n * For componentless fields (no loadComponent and no mapper), returns undefined\n * since there's no component to bind inputs to. Callers should check for undefined\n * and skip rendering logic for such fields.\n *\n * If the field type definition specifies `propsToMeta`, the specified props\n * will be merged into the meta object (with meta taking precedence).\n *\n * When running inside an array item context (ARRAY_CONTEXT is provided), the key\n * is automatically suffixed with the item index to ensure unique DOM IDs. The form\n * schema keys remain clean (unsuffixed) so derivations and validations work correctly.\n *\n * Property overrides from the PropertyOverrideStore are applied AFTER all static\n * mapper logic, so they always take precedence. Only fields with registered property\n * derivations incur the overhead of reading from the store.\n *\n * @param fieldDef The field definition to map\n * @param fieldRegistry The registry of field type definitions\n * @returns Signal containing Record of input names to values, or undefined for componentless fields\n */\nexport function mapFieldToInputs(\n fieldDef: FieldDef<unknown>,\n fieldRegistry: Map<string, FieldTypeDefinition>,\n): Signal<Record<string, unknown>> | undefined {\n // Get the field type definition from registry\n const fieldType = fieldRegistry.get(fieldDef.type);\n\n // Componentless field (no mapper and no loadComponent) - nothing to map\n if (fieldType && !fieldType.loadComponent && !fieldType.mapper) {\n return undefined;\n }\n\n // Check if we're inside an array item context - if so, we need to suffix keys\n // Optional because ARRAY_CONTEXT is only provided inside array item injectors\n const arrayContext = inject(ARRAY_CONTEXT, { optional: true });\n\n // Inject the property override store for property derivation overrides\n // Always available — provided at the DynamicForm component level via provideDynamicFormDI\n const store = inject(PROPERTY_OVERRIDE_STORE);\n\n // Get the base mapper result\n const mapperResult: Signal<Record<string, unknown>> = fieldType?.mapper ? fieldType.mapper(fieldDef) : baseFieldMapper(fieldDef);\n\n const propsToMeta = fieldType?.propsToMeta;\n const hasPropsForwarding = propsToMeta && propsToMeta.length > 0;\n // Check that arrayContext exists and has a valid index signal (guards against mock injectors)\n const indexSignal = arrayContext?.index;\n const hasArrayContext = indexSignal !== undefined && isSignal(indexSignal);\n\n // Fast-path check for property overrides: only fields with registered derivations\n // enter the computed() wrapper for overrides. hasField() is a non-reactive Map.has() — O(1).\n // Uses PLACEHOLDER_INDEX to produce the wildcard format (e.g., 'items.$.endDate') matching\n // what the collector/orchestrator registers. The computed block below uses a concrete index instead.\n const hasOverrides =\n store?.hasField(buildPropertyOverrideKey(arrayContext?.arrayKey, arrayContext ? PLACEHOLDER_INDEX : undefined, fieldDef.key)) ?? false;\n\n // Fast path: no transformations needed\n if (!hasPropsForwarding && !hasArrayContext && !hasOverrides) {\n return mapperResult;\n }\n\n // Wrap in computed to apply transformations\n return computed(() => {\n let inputs = mapperResult();\n\n // Apply props forwarding if configured\n if (hasPropsForwarding) {\n inputs = mergeForwardedPropsToMeta(inputs, propsToMeta);\n }\n\n // Apply index suffix for array items\n if (hasArrayContext) {\n const index = indexSignal();\n inputs = applyIndexSuffix(inputs, index);\n }\n\n // Apply property overrides from the store (AFTER all static transformations)\n if (hasOverrides) {\n // Build the store key inside computed() so index signal read establishes reactive dependency\n // Safe to access arrayContext/indexSignal directly — hasArrayContext already confirmed they exist\n const key = hasArrayContext\n ? buildPropertyOverrideKey((arrayContext as ArrayContext).arrayKey, (indexSignal as Signal<number>)(), fieldDef.key)\n : fieldDef.key;\n const overrides = store.getOverrides(key)();\n inputs = applyPropertyOverrides(inputs, overrides);\n }\n\n return inputs;\n });\n}\n","import { computed, DestroyRef, Injector, runInInjectionContext, Signal, Type } from '@angular/core';\nimport { catchError, forkJoin, from, map, Observable, of, OperatorFunction, pipe, scan, switchMap } from 'rxjs';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { FieldTypeDefinition } from '../../models/field-type';\nimport { mapFieldToInputs } from '../field-mapper/field-mapper';\n\n/**\n * Resolved field ready for rendering with ngComponentOutlet / DfFieldOutlet.\n */\nexport interface ResolvedField {\n key: string;\n /** The original field definition (used by DfFieldOutlet to resolve wrappers). */\n fieldDef: FieldDef<unknown>;\n component: Type<unknown>;\n injector: Injector;\n inputs: Signal<Record<string, unknown>>;\n renderReady: Signal<boolean>;\n}\n\nexport function createRenderReadySignal(\n inputs: Signal<Record<string, unknown>>,\n definition: FieldTypeDefinition | undefined,\n): Signal<boolean> {\n const explicitRenderReadyWhen = definition?.renderReadyWhen;\n const requiredInputs = definition?.mapper && explicitRenderReadyWhen === undefined ? ['field'] : (explicitRenderReadyWhen ?? []);\n\n if (requiredInputs.length === 0) {\n return computed(() => true);\n }\n\n return computed(() => {\n const currentInputs = inputs();\n return requiredInputs.every((inputName) => currentInputs[inputName] !== undefined);\n });\n}\n\n/**\n * Context required to resolve a field.\n */\nexport interface ResolveFieldContext {\n /**\n * The field registry to load components from.\n * Returns undefined for componentless fields (e.g., hidden fields).\n */\n loadTypeComponent: (type: string) => Promise<Type<unknown> | undefined>;\n /** The raw field registry map for mappers */\n registry: Map<string, FieldTypeDefinition>;\n /** The injector to use for the resolved field */\n injector: Injector;\n /** DestroyRef to check if component is destroyed */\n destroyRef: DestroyRef;\n /** Optional error handler for logging */\n onError?: (fieldDef: FieldDef<unknown>, error: unknown) => void;\n}\n\n/**\n * Resolves a single field definition to a ResolvedField using RxJS.\n * Loads the component asynchronously and maps inputs in the injection context.\n *\n * For componentless fields (e.g., hidden fields), returns undefined since\n * there's nothing to render. These fields still contribute to form values\n * through the form schema.\n *\n * @param fieldDef - The field definition to resolve\n * @param context - The context containing dependencies for resolution\n * @returns Observable that emits ResolvedField or undefined (for componentless fields or on error)\n */\nexport function resolveField(fieldDef: FieldDef<unknown>, context: ResolveFieldContext): Observable<ResolvedField | undefined> {\n return from(context.loadTypeComponent(fieldDef.type)).pipe(\n map((component) => {\n // Check if component is destroyed before proceeding\n if (context.destroyRef.destroyed) {\n return undefined;\n }\n\n // Componentless fields (e.g., hidden) return undefined - nothing to render\n if (!component) {\n return undefined;\n }\n\n // Run mapper in injection context\n const inputs = runInInjectionContext(context.injector, () => mapFieldToInputs(fieldDef, context.registry));\n const definition = context.registry.get(fieldDef.type);\n\n // Fields with components should always have inputs (componentless fields are handled above)\n if (!inputs) {\n return undefined;\n }\n\n return {\n key: fieldDef.key,\n fieldDef,\n component,\n injector: context.injector,\n inputs,\n renderReady: createRenderReadySignal(inputs, definition),\n };\n }),\n catchError((error) => {\n // Only call onError if component is not destroyed to avoid accessing cleaned-up state\n if (!context.destroyRef.destroyed) {\n context.onError?.(fieldDef, error);\n }\n return of(undefined);\n }),\n );\n}\n\n/**\n * Context for synchronous field resolution when components are already cached.\n */\nexport interface SyncResolveFieldContext {\n /** Returns a previously loaded component, or undefined if not cached */\n getLoadedComponent: (type: string) => Type<unknown> | undefined;\n /** The raw field registry map for mappers */\n registry: Map<string, FieldTypeDefinition>;\n /** The injector to use for the resolved field */\n injector: Injector;\n}\n\n/**\n * Synchronously resolves a field definition to a ResolvedField using cached components.\n *\n * This is the fast path for fields whose components have already been loaded.\n * Returns undefined for componentless fields (e.g., hidden fields).\n *\n * @param fieldDef - The field definition to resolve\n * @param context - The context containing cached components and dependencies\n * @returns ResolvedField or undefined (for componentless fields)\n */\nexport function resolveFieldSync(fieldDef: FieldDef<unknown>, context: SyncResolveFieldContext): ResolvedField | undefined {\n const component = context.getLoadedComponent(fieldDef.type);\n\n if (!component) {\n return undefined;\n }\n\n const inputs = runInInjectionContext(context.injector, () => mapFieldToInputs(fieldDef, context.registry));\n const definition = context.registry.get(fieldDef.type);\n\n if (!inputs) {\n return undefined;\n }\n\n return {\n key: fieldDef.key,\n fieldDef,\n component,\n injector: context.injector,\n inputs,\n renderReady: createRenderReadySignal(inputs, definition),\n };\n}\n\n/**\n * Reconciles previous and current resolved fields to preserve injector instances\n * for fields that haven't changed type, preventing unnecessary component recreation.\n *\n * @param prev - Previous resolved fields array\n * @param curr - Current resolved fields array\n * @returns Reconciled fields with preserved injectors where applicable\n */\nexport function reconcileFields(prev: ResolvedField[], curr: ResolvedField[]): ResolvedField[] {\n const prevMap = new Map(prev.map((f) => [f.key, f]));\n\n return curr.map((field) => {\n const existing = prevMap.get(field.key);\n\n if (existing && existing.component === field.component && existing.injector === field.injector) {\n // Truly unchanged - preserve object identity for signal stability\n return existing;\n }\n\n // New field, type changed, or context changed (new injector) - use new field\n return field;\n });\n}\n\n/**\n * Creates an RxJS pipe for resolving field definitions to rendered components.\n * Used by container components (page, group) to resolve their child fields.\n */\nexport function createFieldResolutionPipe(getContext: () => ResolveFieldContext): OperatorFunction<FieldDef<unknown>[], ResolvedField[]> {\n return pipe(\n switchMap((fields) => {\n if (!fields || fields.length === 0) {\n return of([] as (ResolvedField | undefined)[]);\n }\n const context = getContext();\n return forkJoin(fields.map((f) => resolveField(f, context)));\n }),\n map((fields) => fields.filter((f): f is ResolvedField => f !== undefined)),\n scan(reconcileFields, [] as ResolvedField[]),\n );\n}\n","import { detectFormMode, FormModeDetectionResult, isPageField } from '../../models/types/form-mode';\nimport { RegisteredFieldTypes } from '../../models/registry';\nimport { validatePageNesting } from '../../definitions/default/page-field';\nimport { isRowField, validateRowNesting } from '../../definitions/default/row-field';\nimport { isGroupField } from '../../definitions/default/group-field';\nimport { isArrayField, isSimplifiedArrayField } from '../../definitions/default/array-field';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\n\n/**\n * Comprehensive form configuration validator that checks:\n * 1. Form mode consistency (paged vs non-paged)\n * 2. Page nesting rules\n * 3. Row nesting rules (no hidden fields in rows)\n * 4. Field placement constraints\n */\nexport class FormModeValidator {\n /**\n * Validates a form configuration and returns detailed validation results\n * @param fields The form field definitions to validate\n * @returns Validation result with mode detection and error details\n */\n static validateFormConfiguration<TFields extends RegisteredFieldTypes[]>(fields: TFields): FormConfigurationValidationResult {\n const modeDetection = detectFormMode(fields);\n const additionalErrors: string[] = [];\n\n // Additional validation for paged forms\n if (modeDetection.mode === 'paged' && modeDetection.isValid) {\n // Validate each page field individually\n for (let i = 0; i < fields.length; i++) {\n const field = fields[i];\n if (isPageField(field)) {\n if (!validatePageNesting(field)) {\n additionalErrors.push(\n `Page field at index ${i} (key: \"${field.key || 'unknown'}\") contains nested page fields, which is not allowed.`,\n );\n }\n }\n }\n }\n\n const allErrors = [...modeDetection.errors, ...additionalErrors];\n const isFullyValid = modeDetection.isValid && additionalErrors.length === 0;\n\n return {\n mode: modeDetection.mode,\n isValid: isFullyValid,\n errors: allErrors,\n warnings: this.generateWarnings(fields, modeDetection),\n };\n }\n\n /**\n * Validates form configuration and throws an error if invalid\n * @param fields The form field definitions to validate\n * @throws Error with detailed validation messages if form is invalid\n */\n static validateFormConfigurationOrThrow<TFields extends RegisteredFieldTypes[]>(fields: TFields): void {\n const result = this.validateFormConfiguration(fields);\n\n if (!result.isValid) {\n const errorMessage = [`Invalid form configuration (${result.mode} mode):`, ...result.errors.map((error) => ` - ${error}`)].join(\n '\\n',\n );\n\n throw new DynamicFormError(errorMessage);\n }\n }\n\n /**\n * Generates helpful warnings for form configurations\n * @param fields The form field definitions\n * @param modeDetection The mode detection result\n * @returns Array of warning messages\n */\n private static generateWarnings<TFields extends RegisteredFieldTypes[]>(\n fields: TFields,\n modeDetection: FormModeDetectionResult,\n ): string[] {\n const warnings: string[] = [];\n\n // Warn about single page forms\n if (modeDetection.mode === 'paged' && fields.length === 1) {\n warnings.push('Single page form detected. Consider using non-paged mode for better performance if page navigation is not needed.');\n }\n\n // Warn about empty pages\n if (modeDetection.mode === 'paged') {\n for (let i = 0; i < fields.length; i++) {\n const field = fields[i];\n if (isPageField(field)) {\n if (!field.fields || field.fields.length === 0) {\n warnings.push(`Page field at index ${i} (key: \"${field.key || 'unknown'}\") contains no fields and will render as empty.`);\n }\n }\n }\n }\n\n // Warn about hidden fields in rows (they work but don't render, which may be confusing)\n const rowWarnings = this.collectRowHiddenFieldWarnings(fields);\n warnings.push(...rowWarnings);\n\n return warnings;\n }\n\n /**\n * Recursively collects warnings for hidden fields inside rows\n * @param fields The form field definitions to check\n * @param path Current path for warning messages\n * @returns Array of warning messages\n */\n private static collectRowHiddenFieldWarnings(fields: readonly FieldDef<unknown>[] | undefined, path = ''): string[] {\n if (!fields) {\n return [];\n }\n\n const warnings: string[] = [];\n\n for (let i = 0; i < fields.length; i++) {\n const field = fields[i];\n const fieldPath = path ? `${path}.fields[${i}]` : `fields[${i}]`;\n const fieldKey = field.key || 'unknown';\n\n if (isRowField(field)) {\n if (!validateRowNesting(field)) {\n warnings.push(\n `Row field at ${fieldPath} (key: \"${fieldKey}\") contains hidden fields. ` +\n `Hidden fields in rows don't render anything - consider placing them outside the row.`,\n );\n }\n // Continue checking nested rows within the row's children\n warnings.push(...this.collectRowHiddenFieldWarnings(field.fields, fieldPath));\n } else if (isPageField(field)) {\n // Check rows within pages\n warnings.push(...this.collectRowHiddenFieldWarnings(field.fields, fieldPath));\n } else if (isGroupField(field)) {\n // Check rows within groups\n warnings.push(...this.collectRowHiddenFieldWarnings(field.fields, fieldPath));\n } else if (isSimplifiedArrayField(field)) {\n // Simplified arrays are normalized later; check template fields if present\n const templateFields = Array.isArray(field.template) ? [...field.template] : [field.template];\n warnings.push(...this.collectRowHiddenFieldWarnings(templateFields as FieldDef<unknown>[], fieldPath));\n } else if (isArrayField(field)) {\n // Check rows within array templates — items may be single FieldDef (primitive) or FieldDef[] (object)\n const itemTemplates = field.fields as readonly (FieldDef<unknown> | readonly FieldDef<unknown>[])[];\n for (let j = 0; j < itemTemplates.length; j++) {\n const itemFields = itemTemplates[j];\n const fieldsArray = Array.isArray(itemFields) ? [...itemFields] : [itemFields];\n warnings.push(...this.collectRowHiddenFieldWarnings(fieldsArray, `${fieldPath}.fields[${j}]`));\n }\n }\n }\n\n return warnings;\n }\n}\n\n/**\n * Extended validation result including warnings\n */\nexport interface FormConfigurationValidationResult extends FormModeDetectionResult {\n /** Array of warning messages that don't prevent form operation */\n warnings: string[];\n}\n\n/**\n * Convenience function for quick form mode validation\n * @param fields The form field definitions to validate\n * @returns True if form configuration is valid, false otherwise\n */\nexport function isValidFormConfiguration<TFields extends RegisteredFieldTypes[]>(fields: TFields): boolean {\n return FormModeValidator.validateFormConfiguration(fields).isValid;\n}\n","import { inject, InjectionToken, Type } from '@angular/core';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\nimport { FIELD_REGISTRY, FieldTypeDefinition } from '../../models/field-type';\nimport { resolveDefaultExport } from '../wrapper-chain/wrapper-chain';\n\n/**\n * Cache for resolved field type components.\n *\n * Using an InjectionToken with `providedIn: 'root'` ensures:\n * - SSR safety: Angular creates a fresh root injector per SSR request,\n * so the cache is properly isolated and garbage-collected\n * - Shared across all `injectFieldRegistry()` calls within the same app/request\n *\n * @internal\n */\nexport const COMPONENT_CACHE = new InjectionToken<Map<string, Type<unknown>>>('COMPONENT_CACHE', {\n providedIn: 'root',\n factory: () => new Map(),\n});\n\n/**\n * Injection function for accessing the dynamic form field registry.\n *\n * Provides a convenient API for interacting with registered field types,\n * including type checking, component loading, and registration management.\n * Must be called within an injection context.\n *\n * @returns Object with methods for field registry interaction\n *\n * @example\n * ```typescript\n * @Component({...})\n * export class MyComponent {\n * private fieldRegistry = injectFieldRegistry();\n *\n * async loadCustomField() {\n * if (this.fieldRegistry.hasType('custom-input')) {\n * const component = await this.fieldRegistry.loadTypeComponent('custom-input');\n * // Use component...\n * }\n * }\n * }\n * ```\n *\n * @example\n * ```typescript\n * // In a service\n * @Injectable()\n * export class FormBuilderService {\n * private fieldRegistry = injectFieldRegistry();\n *\n * getAvailableFieldTypes(): string[] {\n * return this.fieldRegistry.getTypes().map(type => type.name);\n * }\n * }\n * ```\n *\n * @public\n */\nexport function injectFieldRegistry() {\n const registry = inject(FIELD_REGISTRY);\n const componentCache = inject(COMPONENT_CACHE);\n\n return {\n /**\n * Retrieves a field type definition by its registered name.\n *\n * @param name - The registered name of the field type\n * @returns The field type definition if found, undefined otherwise\n *\n * @example\n * ```typescript\n * const inputType = fieldRegistry.getType('input');\n * if (inputType) {\n * console.log('Input field type found:', inputType.name);\n * }\n * ```\n */\n getType(name: string): FieldTypeDefinition | undefined {\n return registry.get(name);\n },\n\n /**\n * Checks if a field type is registered in the registry.\n *\n * @param name - The name of the field type to check\n * @returns True if the field type exists, false otherwise\n *\n * @example\n * ```typescript\n * if (fieldRegistry.hasType('custom-input')) {\n * // Safe to use custom-input field type\n * const component = await fieldRegistry.loadTypeComponent('custom-input');\n * }\n * ```\n */\n hasType(name: string): boolean {\n return registry.has(name);\n },\n\n /**\n * Loads a field type component with support for lazy loading.\n *\n * Handles both synchronous component references and asynchronous\n * dynamic imports. Automatically extracts default exports from ES modules.\n *\n * Returns `undefined` for componentless field types (e.g., hidden fields)\n * that only contribute to form values without rendering UI.\n *\n * @param name - The name of the field type to load\n * @returns Promise resolving to the component constructor, or undefined for componentless fields\n * @throws {Error} When field type is not registered or loading fails\n *\n * @example\n * ```typescript\n * const component = await fieldRegistry.loadTypeComponent('input');\n * if (component) {\n * const componentRef = vcr.createComponent(component);\n * }\n * // For componentless fields like 'hidden', component will be undefined\n * ```\n */\n async loadTypeComponent(name: string): Promise<Type<unknown> | undefined> {\n const fieldType = registry.get(name);\n\n if (!fieldType) {\n throw new DynamicFormError(`Field type \"${name}\" is not registered`);\n }\n\n // Componentless field types (e.g., hidden) don't have loadComponent\n if (!fieldType.loadComponent) {\n return undefined;\n }\n\n // Check cache first for instant resolution\n const cached = componentCache.get(name);\n if (cached) {\n return cached;\n }\n\n try {\n const component = resolveDefaultExport(await fieldType.loadComponent());\n\n if (component) {\n componentCache.set(name, component);\n }\n\n return component;\n } catch (error) {\n throw new DynamicFormError(`Failed to load component for field type \"${name}\": ${error}`);\n }\n },\n\n /**\n * Returns a previously loaded component from cache, or undefined if not yet loaded.\n *\n * This enables synchronous field resolution for components that have already\n * been loaded (e.g., after first render). Returns undefined for:\n * - Components not yet loaded (first render)\n * - Componentless field types (e.g., hidden)\n * - Unregistered field types\n *\n * @param name - The name of the field type\n * @returns The cached component constructor, or undefined\n */\n getLoadedComponent(name: string): Type<unknown> | undefined {\n return componentCache.get(name);\n },\n\n /**\n * Gets all registered field type definitions.\n *\n * @returns Array of all field type definitions in the registry\n *\n * @example\n * ```typescript\n * const allTypes = fieldRegistry.getTypes();\n * const typeNames = allTypes.map(type => type.name);\n * console.log('Available field types:', typeNames);\n * ```\n */\n getTypes(): FieldTypeDefinition[] {\n return Array.from(registry.values());\n },\n\n /**\n * Registers multiple field types at once.\n *\n * Useful for bulk registration of custom field types. Overwrites\n * existing registrations with the same name.\n *\n * @param types - Array of field type definitions to register\n *\n * @example\n * ```typescript\n * fieldRegistry.registerTypes([\n * CustomInputType,\n * CustomSelectType,\n * CustomDatePickerType\n * ]);\n * ```\n */\n registerTypes(types: FieldTypeDefinition[]): void {\n types.forEach((type) => {\n registry.set(type.name, type);\n });\n },\n\n /**\n * Provides direct access to the underlying registry Map.\n *\n * Use with caution - direct modification can affect form behavior.\n * Primarily intended for advanced use cases and debugging.\n *\n * @returns The raw Map containing field type registrations\n *\n * @example\n * ```typescript\n * const rawRegistry = fieldRegistry.raw;\n * console.log('Registry size:', rawRegistry.size);\n * ```\n */\n get raw() {\n return registry;\n },\n };\n}\n","import { FieldDef } from '../../definitions/base/field-def';\nimport { FieldWithValidation } from '../../definitions/base/field-with-validation';\nimport { FieldTypeDefinition } from '../../models/field-type';\nimport { hasChildFields } from '../../models/types/type-guards';\nimport { normalizeFieldsArray } from '../object-utils';\nimport { DynamicFormError } from '../../errors/dynamic-form-error';\nimport { Logger } from '../../providers/features/logger/logger.interface';\n\n/** Data collected during a single config traversal. */\ninterface ConfigTraversalData {\n keys: string[];\n types: Set<string>;\n regexErrors: string[];\n}\n\n/**\n * Collects all field keys, types, and validates regex patterns from a field tree\n * by recursively traversing containers (page, row, group, array).\n *\n * @param collectKeys - Whether to add field keys to data.keys for duplicate detection.\n * Set to false when inside an array container: array item fields share template keys\n * across items by design (e.g. every item has 'name', 'email'), so they must not\n * participate in global duplicate-key checking.\n */\nfunction collectFieldData(fields: FieldDef<unknown>[], data: ConfigTraversalData, collectKeys = true): void {\n for (const field of fields) {\n if (collectKeys && field.key) {\n data.keys.push(field.key);\n }\n if (field.type) {\n data.types.add(field.type);\n }\n\n const fieldWithValidation = field as FieldWithValidation;\n if ('pattern' in field && typeof fieldWithValidation.pattern === 'string') {\n validateRegexPattern(fieldWithValidation.pattern, field.key || '<unknown>', data.regexErrors);\n }\n\n if ('validators' in field && fieldWithValidation.validators) {\n for (const validator of fieldWithValidation.validators) {\n if (validator.type === 'pattern' && 'value' in validator && typeof validator.value === 'string') {\n validateRegexPattern(validator.value, field.key || '<unknown>', data.regexErrors);\n }\n }\n }\n\n if (hasChildFields(field)) {\n // Array item fields share template keys across items by design — stop collecting keys\n // once inside an array. Types and regex patterns are still validated.\n const childCollectKeys = collectKeys && field.type !== 'array';\n const children = normalizeFieldsArray(field.fields) as (FieldDef<unknown> | FieldDef<unknown>[])[];\n for (const child of children) {\n if (Array.isArray(child)) {\n collectFieldData(child as FieldDef<unknown>[], data, childCollectKeys);\n } else {\n collectFieldData([child], data, childCollectKeys);\n }\n }\n }\n }\n}\n\n/**\n * Validates a single regex pattern string, collecting errors rather than throwing.\n */\nfunction validateRegexPattern(pattern: string, fieldKey: string, errors: string[]): void {\n try {\n new RegExp(pattern);\n } catch (e) {\n errors.push(`Invalid regex pattern in validator for field '${fieldKey}': '${pattern}' — ${e instanceof Error ? e.message : String(e)}`);\n }\n}\n\n/**\n * Validates that no duplicate field keys exist in the config.\n * Throws a DynamicFormError listing all duplicates if any are found.\n *\n * @throws {DynamicFormError} When duplicate keys are detected\n */\nfunction validateNoDuplicateKeys(allKeys: string[]): void {\n const seen = new Set<string>();\n const duplicates = new Set<string>();\n\n for (const key of allKeys) {\n if (seen.has(key)) {\n duplicates.add(key);\n }\n seen.add(key);\n }\n\n if (duplicates.size > 0) {\n const duplicateList = Array.from(duplicates)\n .map((k) => `'${k}'`)\n .join(', ');\n throw new DynamicFormError(`Duplicate field keys detected: ${duplicateList}. Each field key must be unique within a form config.`);\n }\n}\n\n/**\n * Validates that every field type referenced in the config exists in the registry.\n * Logs a warning for unregistered types — unknown fields are skipped during rendering\n * rather than blocking the whole form (graceful degradation).\n *\n * Skips validation when the registry is empty (no UI adapter has been registered),\n * since the core library tests operate without a field registry.\n */\nfunction validateFieldTypesRegistered(allTypes: Set<string>, registry: Map<string, FieldTypeDefinition>, logger: Logger): void {\n if (registry.size === 0) return;\n\n const unregistered: string[] = [];\n\n for (const type of allTypes) {\n if (!registry.has(type)) {\n unregistered.push(type);\n }\n }\n\n if (unregistered.length > 0) {\n const typeList = unregistered.map((t) => `'${t}'`).join(', ');\n logger.warn(\n `Unknown field type(s): ${typeList}. Register them via provideDynamicForm(...withXxxFields()) or a custom registry entry. These fields will be skipped during rendering.`,\n );\n }\n}\n\n/**\n * Validates a form config at bootstrap time, checking for:\n * - Duplicate field keys (throws — this is always a developer error)\n * - Unregistered field types (warns — form degrades gracefully, skipping unknown fields)\n * - Invalid regex patterns in validators (throws — invalid regex will cause runtime errors)\n *\n * Should be called once during form setup, before fields are processed.\n *\n * @throws {DynamicFormError} When duplicate keys or invalid regex patterns are detected\n */\nexport function validateFormConfig(fields: FieldDef<unknown>[], registry: Map<string, FieldTypeDefinition>, logger: Logger): void {\n const data: ConfigTraversalData = {\n keys: [],\n types: new Set<string>(),\n regexErrors: [],\n };\n\n collectFieldData(fields, data);\n\n validateNoDuplicateKeys(data.keys);\n validateFieldTypesRegistered(data.types, registry, logger);\n\n if (data.regexErrors.length > 0) {\n throw new DynamicFormError(\n data.regexErrors.length === 1\n ? data.regexErrors[0]\n : `Invalid regex pattern(s) found:\\n${data.regexErrors.map((e) => ` - ${e}`).join('\\n')}`,\n );\n }\n}\n","import { InjectionToken } from '@angular/core';\nimport { ResolvedValueExclusionConfig } from '../../../models/value-exclusion-config';\n\n/**\n * Injection token for global value exclusion defaults.\n *\n * Controls which field values are excluded from form submission output\n * based on their reactive state (hidden, disabled, readonly).\n *\n * By default, all three exclusion rules are enabled:\n * - Hidden fields are excluded from submission\n * - Disabled fields are excluded from submission\n * - Readonly fields are excluded from submission\n *\n * This token is configured via `withValueExclusionDefaults()` feature function.\n * Per-form overrides can be set via `FormOptions`.\n * Per-field overrides can be set on individual `FieldDef` entries.\n *\n * **Resolution order:** Field > Form > Global (most specific wins).\n *\n * @internal\n */\nexport const VALUE_EXCLUSION_DEFAULTS = new InjectionToken<ResolvedValueExclusionConfig>('VALUE_EXCLUSION_DEFAULTS', {\n providedIn: 'root',\n factory: () => ({\n excludeValueIfHidden: true,\n excludeValueIfDisabled: true,\n excludeValueIfReadonly: true,\n }),\n});\n","import { FieldTree } from '@angular/forms/signals';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { isGroupField } from '../../definitions/default/group-field';\nimport { isArrayField } from '../../definitions/default/array-field';\nimport { FieldTypeDefinition, getFieldValueHandling } from '../../models/field-type';\nimport { ResolvedValueExclusionConfig, ValueExclusionConfig } from '../../models/value-exclusion-config';\n\n/**\n * Resolves the effective exclusion config for a field using the 3-tier hierarchy:\n * Field > Form > Global. For each property, the most specific defined value wins.\n *\n * @param global - Global defaults from VALUE_EXCLUSION_DEFAULTS token\n * @param form - Form-level overrides from FormOptions (may be undefined per property)\n * @param field - Field-level overrides from FieldDef (may be undefined per property)\n * @returns Fully resolved config with all properties defined\n */\nexport function resolveExclusionConfig(\n global: ResolvedValueExclusionConfig,\n form: ValueExclusionConfig | undefined,\n field: ValueExclusionConfig | undefined,\n): ResolvedValueExclusionConfig {\n return {\n excludeValueIfHidden: field?.excludeValueIfHidden ?? form?.excludeValueIfHidden ?? global.excludeValueIfHidden,\n excludeValueIfDisabled: field?.excludeValueIfDisabled ?? form?.excludeValueIfDisabled ?? global.excludeValueIfDisabled,\n excludeValueIfReadonly: field?.excludeValueIfReadonly ?? form?.excludeValueIfReadonly ?? global.excludeValueIfReadonly,\n };\n}\n\n/**\n * Determines whether a field's value should be excluded based on its reactive state\n * and the resolved exclusion config.\n */\nfunction shouldExcludeField(fieldState: FieldTree<unknown>, config: ResolvedValueExclusionConfig): boolean {\n const state = fieldState();\n\n if (config.excludeValueIfHidden && state.hidden()) {\n return true;\n }\n\n if (config.excludeValueIfDisabled && state.disabled()) {\n return true;\n }\n\n if (config.excludeValueIfReadonly && state.readonly()) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Filters form values based on field reactive state (hidden, disabled, readonly)\n * and the 3-tier exclusion config hierarchy.\n *\n * Only affects submission output — internal form state and two-way binding are unaffected.\n *\n * @param rawValue - The unfiltered form value object\n * @param schemaFields - Flattened schema fields from FormSetup (groups/arrays preserved, pages/rows unwrapped)\n * @param formTree - The Angular Signal Forms FieldTree, accessed as `formInstance[key]`\n * @param registry - Field type registry for valueHandling mode lookup\n * @param globalDefaults - Global exclusion defaults from VALUE_EXCLUSION_DEFAULTS\n * @param formOptions - Form-level exclusion overrides from FormOptions\n * @returns Filtered value with excluded field values omitted\n */\nexport function filterFormValue<T extends Record<string, unknown>>(\n rawValue: T,\n schemaFields: FieldDef<unknown>[],\n formTree: Record<string, FieldTree<unknown>>,\n registry: Map<string, FieldTypeDefinition>,\n globalDefaults: ResolvedValueExclusionConfig,\n formOptions: ValueExclusionConfig | undefined,\n): Partial<T> {\n const result: Record<string, unknown> = {};\n\n for (const field of schemaFields) {\n const key = field.key;\n if (!key) continue;\n\n // Skip fields that don't contribute to form values\n const valueHandling = getFieldValueHandling(field.type, registry);\n if (valueHandling === 'exclude' || valueHandling === 'flatten') continue;\n\n // If the key doesn't exist in the raw value, skip\n if (!(key in rawValue)) continue;\n\n // Try to access the field state from the form tree\n const fieldState = formTree[key] as FieldTree<unknown> | undefined;\n\n // If no field state is available (e.g., componentless hidden fields),\n // include the value as-is since we can't determine reactive state\n if (!fieldState || typeof fieldState !== 'function') {\n result[key] = rawValue[key];\n continue;\n }\n\n // Resolve per-field exclusion config\n const fieldExclusion: ValueExclusionConfig = {\n excludeValueIfHidden: field.excludeValueIfHidden,\n excludeValueIfDisabled: field.excludeValueIfDisabled,\n excludeValueIfReadonly: field.excludeValueIfReadonly,\n };\n const resolvedConfig = resolveExclusionConfig(globalDefaults, formOptions, fieldExclusion);\n\n // Check if this field should be excluded based on its state\n if (shouldExcludeField(fieldState, resolvedConfig)) {\n continue;\n }\n\n // Handle group fields: recurse into nested structure\n if (isGroupField(field) && field.fields) {\n const groupValue = rawValue[key] as Record<string, unknown> | undefined;\n if (groupValue && typeof groupValue === 'object') {\n const childFields = Object.values(field.fields) as FieldDef<unknown>[];\n const nestedTree = fieldState as unknown as Record<string, FieldTree<unknown>>;\n result[key] = filterFormValue(\n groupValue as Record<string, unknown>,\n childFields,\n nestedTree,\n registry,\n globalDefaults,\n formOptions,\n );\n } else {\n result[key] = groupValue;\n }\n continue;\n }\n\n // Handle array fields: if not excluded at array level, include entire array value\n // (v1: no per-item filtering)\n if (isArrayField(field)) {\n result[key] = rawValue[key];\n continue;\n }\n\n // Leaf field: include value\n result[key] = rawValue[key];\n }\n\n return result as Partial<T>;\n}\n","import { FieldDef } from '../definitions/base/field-def';\nimport { FieldTypeDefinition } from '../models/field-type';\nimport { FormConfig } from '../models/form-config';\nimport { RegisteredFieldTypes } from '../models/registry/field-registry';\nimport { FormMode } from '../models/types/form-mode';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Discriminant constants\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Lifecycle state discriminants.\n * @internal\n */\nexport const LifecycleState = {\n Uninitialized: 'uninitialized',\n Initializing: 'initializing',\n Ready: 'ready',\n Transitioning: 'transitioning',\n Destroyed: 'destroyed',\n} as const;\n\n/** Indexed access type for {@link LifecycleState} values. */\nexport type LifecycleStateType = (typeof LifecycleState)[keyof typeof LifecycleState];\n\n/**\n * Transition phase discriminants.\n * @internal\n */\nexport const Phase = {\n Teardown: 'teardown',\n Applying: 'applying',\n Restoring: 'restoring',\n} as const;\n\n/** Indexed access type for {@link Phase} values. */\nexport type PhaseType = (typeof Phase)[keyof typeof Phase];\n\n/**\n * Action type discriminants.\n * @internal\n */\nexport const Action = {\n Initialize: 'initialize',\n ConfigChange: 'config-change',\n SetupComplete: 'setup-complete',\n ValueCaptured: 'value-captured',\n TeardownComplete: 'teardown-complete',\n ApplyComplete: 'apply-complete',\n RestoreComplete: 'restore-complete',\n Destroy: 'destroy',\n} as const;\n\n/** Indexed access type for {@link Action} values. */\nexport type ActionType = (typeof Action)[keyof typeof Action];\n\n/**\n * Side effect type discriminants.\n * @internal\n */\nexport const Effect = {\n CaptureValue: 'capture-value',\n WaitFrameBoundary: 'wait-frame-boundary',\n CreateForm: 'create-form',\n RestoreValues: 'restore-values',\n} as const;\n\n/** Indexed access type for {@link Effect} values. */\nexport type EffectType = (typeof Effect)[keyof typeof Effect];\n\n// ─────────────────────────────────────────────────────────────────────────────\n// State types\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** @internal */\nexport type FormLifecycleState<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]> =\n | FormLifecycleUninitialized\n | FormLifecycleInitializing<TFields>\n | FormLifecycleReady<TFields>\n | FormLifecycleTransitioning<TFields>\n | FormLifecycleDestroyed;\n\nexport interface FormLifecycleUninitialized {\n readonly type: (typeof LifecycleState)['Uninitialized'];\n}\n\nexport interface FormLifecycleInitializing<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]> {\n readonly type: (typeof LifecycleState)['Initializing'];\n readonly config: FormConfig<TFields>;\n}\n\nexport interface FormLifecycleReady<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]> {\n readonly type: (typeof LifecycleState)['Ready'];\n readonly config: FormConfig<TFields>;\n readonly formSetup: FormSetup;\n}\n\nexport type TransitionPhase = PhaseType;\n\nexport interface FormLifecycleTransitioning<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]> {\n readonly type: (typeof LifecycleState)['Transitioning'];\n readonly phase: TransitionPhase;\n readonly currentConfig: FormConfig<TFields>;\n readonly pendingConfig: FormConfig<TFields>;\n readonly preservedValue?: Record<string, unknown>;\n /** FormSetup from the ready state that initiated this transition */\n readonly currentFormSetup: FormSetup;\n /** FormSetup computed for the pending config (set when apply-complete fires) */\n readonly pendingFormSetup?: FormSetup;\n}\n\nexport interface FormLifecycleDestroyed {\n readonly type: (typeof LifecycleState)['Destroyed'];\n}\n\n/** @internal */\nexport interface FormSetup {\n /** Fields to render (flattened for non-paged, empty for paged). */\n readonly fields: FieldDef<unknown>[];\n /** All schema fields for validation (flattened from all pages/containers). */\n readonly schemaFields: FieldDef<unknown>[];\n readonly originalFields?: FieldDef<unknown>[];\n readonly defaultValues: Record<string, unknown>;\n readonly mode: FormMode;\n readonly registry: Map<string, FieldTypeDefinition>;\n}\n\n/**\n * Actions that can be dispatched to the state machine.\n *\n * @internal\n */\nexport type FormStateAction<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]> =\n | InitializeAction<TFields>\n | ConfigChangeAction<TFields>\n | SetupCompleteAction\n | ValueCapturedAction\n | TeardownCompleteAction\n | ApplyCompleteAction\n | RestoreCompleteAction\n | DestroyAction;\n\nexport interface InitializeAction<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]> {\n readonly type: (typeof Action)['Initialize'];\n readonly config: FormConfig<TFields>;\n}\n\nexport interface ConfigChangeAction<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]> {\n readonly type: (typeof Action)['ConfigChange'];\n readonly config: FormConfig<TFields>;\n}\n\nexport interface SetupCompleteAction {\n readonly type: (typeof Action)['SetupComplete'];\n readonly formSetup: FormSetup;\n}\n\nexport interface ValueCapturedAction {\n readonly type: (typeof Action)['ValueCaptured'];\n readonly value: Record<string, unknown>;\n}\n\nexport interface TeardownCompleteAction {\n readonly type: (typeof Action)['TeardownComplete'];\n}\n\nexport interface ApplyCompleteAction {\n readonly type: (typeof Action)['ApplyComplete'];\n readonly formSetup: FormSetup;\n}\n\nexport interface RestoreCompleteAction {\n readonly type: (typeof Action)['RestoreComplete'];\n}\n\nexport interface DestroyAction {\n readonly type: (typeof Action)['Destroy'];\n}\n\n/**\n * State transition record for debugging and testing.\n *\n * @internal\n */\nexport interface StateTransition<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]> {\n readonly from: FormLifecycleState<TFields>;\n readonly to: FormLifecycleState<TFields>;\n readonly action: FormStateAction<TFields>;\n readonly timestamp: number;\n}\n\n/**\n * Result of a state transition.\n *\n * @internal\n */\nexport interface TransitionResult<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]> {\n readonly state: FormLifecycleState<TFields>;\n readonly sideEffects: SideEffect[];\n}\n\n/**\n * Side effects to execute after state transition.\n *\n * @internal\n */\nexport type SideEffect =\n | { readonly type: (typeof Effect)['CaptureValue'] }\n | { readonly type: (typeof Effect)['WaitFrameBoundary'] }\n | { readonly type: (typeof Effect)['CreateForm'] }\n | { readonly type: (typeof Effect)['RestoreValues']; readonly values: Record<string, unknown> };\n\n/**\n * Error from async field component loading.\n *\n * @public\n */\nexport interface FieldLoadingError {\n readonly fieldType: string;\n readonly fieldKey: string;\n readonly error: Error;\n}\n\n/** @internal */\nexport function isReadyState<TFields extends RegisteredFieldTypes[]>(\n state: FormLifecycleState<TFields>,\n): state is FormLifecycleReady<TFields> {\n return state.type === LifecycleState.Ready;\n}\n\n/** @internal */\nexport function isTransitioningState<TFields extends RegisteredFieldTypes[]>(\n state: FormLifecycleState<TFields>,\n): state is FormLifecycleTransitioning<TFields> {\n return state.type === LifecycleState.Transitioning;\n}\n\n/** @internal */\nexport function createUninitializedState(): FormLifecycleUninitialized {\n return { type: LifecycleState.Uninitialized };\n}\n\n/** @internal */\nexport function createInitializingState<TFields extends RegisteredFieldTypes[]>(\n config: FormConfig<TFields>,\n): FormLifecycleInitializing<TFields> {\n return { type: LifecycleState.Initializing, config };\n}\n\n/** @internal */\nexport function createReadyState<TFields extends RegisteredFieldTypes[]>(\n config: FormConfig<TFields>,\n formSetup: FormSetup,\n): FormLifecycleReady<TFields> {\n return { type: LifecycleState.Ready, config, formSetup };\n}\n\n/** @internal */\nexport function createTransitioningState<TFields extends RegisteredFieldTypes[]>(\n phase: TransitionPhase,\n currentConfig: FormConfig<TFields>,\n pendingConfig: FormConfig<TFields>,\n currentFormSetup: FormSetup,\n preservedValue?: Record<string, unknown>,\n pendingFormSetup?: FormSetup,\n): FormLifecycleTransitioning<TFields> {\n return { type: LifecycleState.Transitioning, phase, currentConfig, pendingConfig, currentFormSetup, preservedValue, pendingFormSetup };\n}\n\n/** @internal */\nexport function createDestroyedState(): FormLifecycleDestroyed {\n return { type: LifecycleState.Destroyed };\n}\n","import { afterNextRender, DestroyRef, Injector } from '@angular/core';\nimport { Observable, Subscriber } from 'rxjs';\n\n/**\n * Options for side effect execution.\n *\n * @internal\n */\nexport interface SideEffectOptions {\n /** Injector for accessing Angular services */\n readonly injector: Injector;\n /** DestroyRef for cleanup on component destruction */\n readonly destroyRef: DestroyRef;\n}\n\n/**\n * Scheduler for managing side effect timing in the state machine.\n * Provides blocking, frame-boundary (rAF), and after-render timing.\n *\n * @internal\n */\nexport class SideEffectScheduler {\n private readonly injector: Injector;\n private readonly abortController = new AbortController();\n\n /** Aborted when the owning component is destroyed. */\n private get destroyed(): boolean {\n return this.abortController.signal.aborted;\n }\n\n constructor(options: SideEffectOptions) {\n this.injector = options.injector;\n\n options.destroyRef.onDestroy(() => {\n this.abortController.abort();\n });\n }\n\n /** Executes a synchronous blocking effect. */\n executeBlocking<T>(effect: () => T): Observable<T> {\n return new Observable((subscriber: Subscriber<T>) => {\n if (this.destroyed) {\n subscriber.complete();\n return;\n }\n\n try {\n const result = effect();\n subscriber.next(result);\n subscriber.complete();\n } catch (error) {\n subscriber.error(error);\n }\n });\n }\n\n /**\n * Defers effect to next rAF (~16ms), giving CD and the async field resolution\n * pipeline time to settle before the state machine continues.\n *\n * When `options.skipIf` returns `true`, the effect executes synchronously\n * (like `executeBlocking`), eliminating ~16ms of unnecessary delay when\n * the field pipeline has already settled (e.g. all components cached).\n */\n executeAtFrameBoundary<T>(effect: () => T, options?: { skipIf?: () => boolean }): Observable<T> {\n if (options?.skipIf?.()) {\n return this.executeBlocking(effect);\n }\n\n return new Observable((subscriber: Subscriber<T>) => {\n if (this.destroyed) {\n subscriber.complete();\n return;\n }\n\n const frameId = requestAnimationFrame(() => {\n if (this.destroyed) {\n subscriber.complete();\n return;\n }\n\n try {\n const result = effect();\n subscriber.next(result);\n subscriber.complete();\n } catch (error) {\n subscriber.error(error);\n }\n });\n\n // Cleanup on unsubscribe\n return () => {\n cancelAnimationFrame(frameId);\n };\n });\n }\n\n /** Executes effect after Angular's next render cycle via `afterNextRender`. */\n executeAfterRender<T>(effect: () => T): Observable<T> {\n return new Observable((subscriber: Subscriber<T>) => {\n if (this.destroyed) {\n subscriber.complete();\n return;\n }\n\n const local = new AbortController();\n\n afterNextRender(\n () => {\n if (local.signal.aborted || this.destroyed) {\n subscriber.complete();\n return;\n }\n\n try {\n const result = effect();\n subscriber.next(result);\n subscriber.complete();\n } catch (error) {\n subscriber.error(error);\n }\n },\n { injector: this.injector },\n );\n\n // afterNextRender can't be deregistered — AbortSignal makes the callback no-op\n return () => {\n local.abort();\n };\n });\n }\n}\n\n/** @internal */\nexport function createSideEffectScheduler(injector: Injector): SideEffectScheduler {\n const destroyRef = injector.get(DestroyRef);\n return new SideEffectScheduler({ injector, destroyRef });\n}\n","import { DestroyRef, Injector, signal, Signal, untracked, WritableSignal } from '@angular/core';\nimport { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';\nimport { catchError, concatMap, EMPTY, Observable, of, Subject } from 'rxjs';\nimport { FormConfig } from '../models/form-config';\nimport { Logger } from '../providers/features/logger/logger.interface';\nimport { RegisteredFieldTypes } from '../models/registry/field-registry';\nimport {\n Action,\n createDestroyedState,\n createInitializingState,\n createReadyState,\n createTransitioningState,\n createUninitializedState,\n Effect,\n FormLifecycleState,\n FormSetup,\n FormStateAction,\n isReadyState,\n isTransitioningState,\n LifecycleState,\n Phase,\n SideEffect,\n StateTransition,\n TransitionResult,\n} from './state-types';\nimport { assertNever } from '../utils/object-utils';\nimport { SideEffectScheduler } from './side-effect-scheduler';\n\n/**\n * Configuration for the form state machine.\n *\n * @internal\n */\nexport interface FormStateMachineConfig<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]> {\n /** Injector for Angular service access */\n readonly injector: Injector;\n /** DestroyRef for cleanup */\n readonly destroyRef: DestroyRef;\n /** Side effect scheduler for controlled timing */\n readonly scheduler: SideEffectScheduler;\n /** Callback to create form setup from config */\n readonly createFormSetup: (config: FormConfig<TFields>) => FormSetup;\n /** Callback to capture current form value */\n readonly captureValue: () => Record<string, unknown>;\n /** Callback to restore form value */\n readonly restoreValue: (values: Record<string, unknown>, validKeys: Set<string>) => void;\n /** Predicate returning true when the field pipeline has already settled (all components cached) */\n readonly isFieldPipelineSettled?: () => boolean;\n /** Signal indicating whether the form is currently submitting */\n readonly isSubmitting?: Signal<boolean>;\n /** Callback when form is created (for registration) */\n readonly onFormCreated?: (formSetup: FormSetup) => void;\n /** Logger instance for error reporting */\n readonly logger: Logger;\n /** Callback for logging/debugging state transitions */\n readonly onTransition?: (transition: StateTransition<TFields>) => void;\n /** Callback when an action fails and error recovery runs */\n readonly onError?: (error: unknown, action: FormStateAction<TFields>) => void;\n}\n\n/**\n * RxJS-based state machine for form lifecycle management.\n * Uses `concatMap` for sequential action processing.\n *\n * Flow: uninitialized → initializing → ready ⇄ transitioning (teardown → applying → restoring)\n *\n * @internal\n */\nexport class FormStateMachine<TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[]> {\n private readonly config: FormStateMachineConfig<TFields>;\n private readonly actions$ = new Subject<FormStateAction<TFields>>();\n private readonly _state: WritableSignal<FormLifecycleState<TFields>>;\n\n /** Signal of current state - use this for deriving computed signals */\n readonly state: Signal<FormLifecycleState<TFields>>;\n\n /** Observable of current state - for RxJS interop */\n readonly state$: Observable<FormLifecycleState<TFields>>;\n\n /** Current state value (synchronous read) */\n get currentState(): FormLifecycleState<TFields> {\n return this._state();\n }\n\n constructor(config: FormStateMachineConfig<TFields>) {\n this.config = config;\n this._state = signal(createUninitializedState());\n this.state = this._state.asReadonly();\n this.state$ = toObservable(this._state, { injector: config.injector });\n\n this.setupActionProcessing();\n }\n\n /** Dispatches an action. Processed sequentially via `concatMap`. */\n dispatch(action: FormStateAction<TFields>): void {\n this.actions$.next(action);\n }\n\n /** Sets up sequential action processing via `concatMap`. */\n private setupActionProcessing(): void {\n this.actions$\n .pipe(\n concatMap((action) =>\n this.processAction(action).pipe(\n catchError((error) => {\n this.config.logger.error(`Action '${action.type}' failed:`, error);\n this.recoverFromError(error, action);\n return EMPTY;\n }),\n ),\n ),\n takeUntilDestroyed(this.config.destroyRef),\n )\n .subscribe();\n }\n\n /**\n * Processes a single action: computes next state (pure), updates `_state`,\n * then executes side effects. Effects may dispatch follow-up actions that\n * are queued via `concatMap` and go through the same transition pipeline.\n */\n private processAction(action: FormStateAction<TFields>): Observable<void> {\n const currentState = this._state();\n const result = this.computeTransition(currentState, action);\n\n this.config.onTransition?.({\n from: currentState,\n to: result.state,\n action,\n timestamp: Date.now(),\n });\n\n this._state.set(result.state);\n return this.executeSideEffects(result.sideEffects);\n }\n\n /**\n * Recovers from a failed action by reverting to the last stable state.\n * Initializing → Uninitialized, Transitioning → Ready (using current setup).\n */\n private recoverFromError(error: unknown, action: FormStateAction<TFields>): void {\n const state = this._state();\n\n if (state.type === LifecycleState.Initializing) {\n this._state.set(createUninitializedState());\n } else if (isTransitioningState(state)) {\n this._state.set(createReadyState(state.currentConfig, state.currentFormSetup));\n }\n\n this.config.onError?.(error, action);\n }\n\n /** Pure transition: current state + action → next state + side effects. */\n private computeTransition(state: FormLifecycleState<TFields>, action: FormStateAction<TFields>): TransitionResult<TFields> {\n switch (action.type) {\n case Action.Initialize:\n return this.handleInitialize(state, action.config);\n\n case Action.ConfigChange:\n return this.handleConfigChange(state, action.config);\n\n case Action.SetupComplete:\n return this.handleSetupComplete(state, action.formSetup as FormSetup);\n\n case Action.ValueCaptured:\n return this.handleValueCaptured(state, action.value);\n\n case Action.TeardownComplete:\n return this.handleTeardownComplete(state);\n\n case Action.ApplyComplete:\n return this.handleApplyComplete(state, action.formSetup as FormSetup);\n\n case Action.RestoreComplete:\n return this.handleRestoreComplete(state);\n\n case Action.Destroy:\n return this.handleDestroy();\n\n default:\n return assertNever(action);\n }\n }\n\n private handleInitialize(state: FormLifecycleState<TFields>, config: FormConfig<TFields>): TransitionResult<TFields> {\n if (state.type !== LifecycleState.Uninitialized) {\n return { state, sideEffects: [] };\n }\n\n return {\n state: createInitializingState(config),\n sideEffects: [{ type: Effect.CreateForm }],\n };\n }\n\n private handleConfigChange(state: FormLifecycleState<TFields>, config: FormConfig<TFields>): TransitionResult<TFields> {\n if (state.type === LifecycleState.Uninitialized) {\n return {\n state: createInitializingState(config),\n sideEffects: [{ type: Effect.CreateForm }],\n };\n }\n\n if (state.type === LifecycleState.Initializing) {\n return {\n state: createInitializingState(config),\n sideEffects: [{ type: Effect.CreateForm }],\n };\n }\n\n // Guard: reject config changes during active submission to prevent races\n // between the in-flight action Promise and form teardown/rebuild.\n if (this.config.isSubmitting?.()) {\n this.config.logger.warn('Config changed during active submission; ignoring. Apply config changes after submission completes.');\n return { state, sideEffects: [] };\n }\n\n if (isReadyState(state)) {\n return {\n state: createTransitioningState(Phase.Teardown, state.config, config, state.formSetup),\n sideEffects: [{ type: Effect.CaptureValue }, { type: Effect.WaitFrameBoundary }],\n };\n }\n\n if (isTransitioningState(state)) {\n // Already transitioning — update pending config (latest wins)\n return {\n state: createTransitioningState(\n state.phase,\n state.currentConfig,\n config,\n state.currentFormSetup,\n state.preservedValue,\n state.pendingFormSetup,\n ),\n sideEffects: [],\n };\n }\n\n return { state, sideEffects: [] };\n }\n\n private handleSetupComplete(state: FormLifecycleState<TFields>, formSetup: FormSetup): TransitionResult<TFields> {\n if (state.type === LifecycleState.Initializing) {\n return {\n state: createReadyState(state.config, formSetup),\n sideEffects: [],\n };\n }\n\n return { state, sideEffects: [] };\n }\n\n private handleValueCaptured(state: FormLifecycleState<TFields>, value: Record<string, unknown>): TransitionResult<TFields> {\n if (!isTransitioningState(state)) {\n return { state, sideEffects: [] };\n }\n\n return {\n state: createTransitioningState(\n state.phase,\n state.currentConfig,\n state.pendingConfig,\n state.currentFormSetup,\n value,\n state.pendingFormSetup,\n ),\n sideEffects: [],\n };\n }\n\n private handleTeardownComplete(state: FormLifecycleState<TFields>): TransitionResult<TFields> {\n if (!isTransitioningState(state) || state.phase !== Phase.Teardown) {\n return { state, sideEffects: [] };\n }\n\n return {\n state: createTransitioningState(\n Phase.Applying,\n state.currentConfig,\n state.pendingConfig,\n state.currentFormSetup,\n state.preservedValue,\n ),\n sideEffects: [{ type: Effect.CreateForm }],\n };\n }\n\n private handleApplyComplete(state: FormLifecycleState<TFields>, formSetup: FormSetup): TransitionResult<TFields> {\n if (!isTransitioningState(state) || state.phase !== Phase.Applying) {\n return { state, sideEffects: [] };\n }\n\n if (state.preservedValue && Object.keys(state.preservedValue).length > 0) {\n return {\n state: createTransitioningState(\n Phase.Restoring,\n state.currentConfig,\n state.pendingConfig,\n state.currentFormSetup,\n state.preservedValue,\n formSetup,\n ),\n sideEffects: [{ type: Effect.RestoreValues, values: state.preservedValue }],\n };\n }\n\n return {\n state: createReadyState(state.pendingConfig, formSetup),\n sideEffects: [],\n };\n }\n\n private handleRestoreComplete(state: FormLifecycleState<TFields>): TransitionResult<TFields> {\n if (!isTransitioningState(state) || state.phase !== Phase.Restoring) {\n return { state, sideEffects: [] };\n }\n\n if (!state.pendingFormSetup) {\n this.config.logger.warn(\n 'handleRestoreComplete: pendingFormSetup was not set — falling back to recomputing. ' +\n 'This indicates a bug in the transition flow.',\n );\n }\n const formSetup = state.pendingFormSetup ?? this.config.createFormSetup(state.pendingConfig);\n\n return {\n state: createReadyState(state.pendingConfig, formSetup),\n sideEffects: [],\n };\n }\n\n private handleDestroy(): TransitionResult<TFields> {\n return {\n state: createDestroyedState(),\n sideEffects: [],\n };\n }\n\n /**\n * Executes side effects in sequence. Effects may call `this.dispatch()` internally,\n * queuing follow-up actions into the same `concatMap` pipeline.\n */\n private executeSideEffects(effects: SideEffect[]): Observable<void> {\n if (effects.length === 0) {\n return of(undefined);\n }\n\n return effects.reduce(\n (chain$, effect) => chain$.pipe(concatMap(() => this.executeSideEffect(effect))),\n of(undefined) as Observable<void>,\n );\n }\n\n private executeSideEffect(effect: SideEffect): Observable<void> {\n const { scheduler } = this.config;\n\n switch (effect.type) {\n case Effect.CaptureValue: {\n return scheduler.executeBlocking(() => {\n const value = this.config.captureValue();\n this.dispatch({ type: Action.ValueCaptured, value });\n });\n }\n\n case Effect.WaitFrameBoundary: {\n return scheduler.executeAtFrameBoundary(\n () => {\n this.dispatch({ type: Action.TeardownComplete });\n },\n { skipIf: this.config.isFieldPipelineSettled },\n );\n }\n\n case Effect.CreateForm: {\n return scheduler.executeBlocking(() => {\n const state = untracked(() => this._state());\n\n let config: FormConfig<TFields> | undefined;\n if (state.type === LifecycleState.Initializing) {\n config = state.config;\n } else if (isTransitioningState(state) && state.phase === Phase.Applying) {\n config = state.pendingConfig;\n }\n\n if (!config) return;\n\n const formSetup = this.config.createFormSetup(config);\n this.config.onFormCreated?.(formSetup);\n\n if (state.type === LifecycleState.Initializing) {\n this.dispatch({ type: Action.SetupComplete, formSetup });\n } else if (isTransitioningState(state) && state.phase === Phase.Applying) {\n this.dispatch({ type: Action.ApplyComplete, formSetup });\n }\n });\n }\n\n case Effect.RestoreValues: {\n return scheduler.executeAfterRender(() => {\n const state = untracked(() => this._state());\n if (!isTransitioningState(state) || state.phase !== Phase.Restoring) return;\n\n if (!state.pendingFormSetup) {\n this.config.logger.warn('RestoreValues effect: pendingFormSetup was not set — falling back to recomputing.');\n }\n const formSetup = state.pendingFormSetup ?? this.config.createFormSetup(state.pendingConfig);\n const validKeys = new Set(formSetup.schemaFields.map((f) => f.key).filter((key): key is string => key !== undefined));\n\n this.config.restoreValue(effect.values, validKeys);\n this.dispatch({ type: Action.RestoreComplete });\n });\n }\n\n default:\n return assertNever(effect);\n }\n }\n}\n\n/** @internal */\nexport function createFormStateMachine<TFields extends RegisteredFieldTypes[]>(\n config: FormStateMachineConfig<TFields>,\n): FormStateMachine<TFields> {\n return new FormStateMachine(config);\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injectable,\n InjectionToken,\n Injector,\n linkedSignal,\n OnDestroy,\n runInInjectionContext,\n signal,\n Signal,\n untracked,\n WritableSignal,\n} from '@angular/core';\nimport { takeUntilDestroyed } from '@angular/core/rxjs-interop';\nimport { FieldTree, form, Schema } from '@angular/forms/signals';\nimport { EMPTY, filter, forkJoin, map, Observable, of, pipe, scan, switchMap, take } from 'rxjs';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\n\nimport { FieldDef } from '../definitions/base/field-def';\nimport { normalizeSimplifiedArrays } from '../utils/array-field/normalize-simplified-arrays';\nimport { DynamicFormError } from '../errors/dynamic-form-error';\nimport { isPageField, PageField } from '../definitions/default/page-field';\nimport { EventBus } from '../events/event.bus';\nimport { FormClearEvent } from '../events/constants/form-clear.event';\nimport { FormResetEvent } from '../events/constants/form-reset.event';\nimport { SubmitEvent } from '../events/constants/submit.event';\nimport { FieldSignalContext } from '../mappers/types';\nimport { FIELD_SIGNAL_CONTEXT } from '../models/field-signal-context.token';\nimport { FieldTypeDefinition } from '../models/field-type';\nimport { FormConfig, FormOptions } from '../models/form-config';\nimport { RegisteredFieldTypes } from '../models/registry/field-registry';\nimport { detectFormMode, FormMode } from '../models/types/form-mode';\nimport { InferFormValue } from '../models/types/form-value-inference';\nimport { DynamicFormLogger } from '../providers/features/logger/logger.token';\nimport { FunctionRegistryService } from '../core/registry/function-registry.service';\nimport { SchemaRegistryService } from '../core/registry/schema-registry.service';\nimport { createSchemaFromFields } from '../core/schema-builder';\nimport { createFormLevelSchema } from '../core/form-schema-merger';\nimport { collectCrossFieldEntries } from '../core/cross-field/cross-field-collector';\nimport { isEqual } from '../utils/object-utils';\nimport { CONTAINER_FIELD_PROCESSORS } from '../utils/container-utils/container-field-processors';\nimport { derivedFromDeferred } from '../utils/derived-from-deferred/derived-from-deferred';\nimport { reconcileFields, ResolvedField, resolveField, resolveFieldSync } from '../utils/resolve-field/resolve-field';\nimport { FormModeValidator } from '../utils/form-validation/form-mode-validator';\nimport { injectFieldRegistry } from '../utils/inject-field-registry/inject-field-registry';\nimport { validateFormConfig } from '../utils/config-validation/config-validator';\nimport { VALUE_EXCLUSION_DEFAULTS } from '../providers/features/value-exclusion/value-exclusion.token';\nimport { filterFormValue } from '../utils/value-filter/value-filter';\nimport { ValueExclusionConfig } from '../models/value-exclusion-config';\n\nimport { Action, FieldLoadingError, FormSetup, isReadyState, isTransitioningState, LifecycleState, Phase } from './state-types';\nimport { createSideEffectScheduler } from './side-effect-scheduler';\nimport { createFormStateMachine, FormStateMachine } from './form-state-machine';\n\n/**\n * Shared deps holder injected by both DynamicForm and FormStateManager.\n * DynamicForm assigns its input signals to the holder's properties via an IIFE\n * field initializer (runs before FormStateManager is injected in declaration order);\n * FormStateManager reads them.\n *\n * `any` is required for config/value because Angular DI is non-generic and\n * Signal/WritableSignal are invariant in TypeScript — Signal<FormConfig<TFields>>\n * is not assignable to Signal<FormConfig>. Safe because the same component\n * instance populates and consumes these properties.\n *\n * @internal\n */\nexport interface FormStateDeps {\n config: Signal<FormConfig<RegisteredFieldTypes[]>> | null;\n formOptions: Signal<FormOptions | undefined> | null;\n value: WritableSignal<Partial<unknown> | undefined> | null;\n}\n\n/** @internal */\nexport const FORM_STATE_DEPS = new InjectionToken<FormStateDeps>('FORM_STATE_DEPS');\n\n/**\n * Casts a FieldTree to a record of per-key sub-trees.\n *\n * FieldTree<TModel> is structurally a callable that exposes per-key child trees\n * via bracket access (e.g., `tree['fieldKey']`), but TypeScript's FieldTree type\n * doesn't surface this as an index signature. This helper makes the cast explicit\n * and centralizes it to a single location.\n */\nfunction asFieldTreeRecord(tree: FieldTree<unknown>): Record<string, FieldTree<unknown>> {\n return tree as unknown as Record<string, FieldTree<unknown>>;\n}\n\n/**\n * Central service that manages all form state and coordinates the form lifecycle.\n * Single source of truth for lifecycle state, field resolution, form signals, and events.\n *\n * @internal\n */\n@Injectable()\nexport class FormStateManager<\n TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[],\n TModel extends Record<string, unknown> = InferFormValue<TFields> & Record<string, unknown>,\n> implements OnDestroy {\n // ─────────────────────────────────────────────────────────────────────────────\n // Dependencies (injected)\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly injector = inject(Injector);\n private readonly destroyRef = inject(DestroyRef);\n private readonly logger = inject(DynamicFormLogger);\n private readonly eventBus = inject(EventBus);\n private readonly functionRegistry = inject(FunctionRegistryService);\n private readonly schemaRegistry = inject(SchemaRegistryService);\n\n /** Host component dependencies (config, formOptions, value). */\n private readonly deps = (() => {\n const raw = inject(FORM_STATE_DEPS);\n if (!raw.config || !raw.formOptions || !raw.value) {\n throw new DynamicFormError(\n 'FormStateDeps must be connected before FormStateManager is created. ' +\n 'Ensure DynamicForm assigns its input signals to FORM_STATE_DEPS.',\n );\n }\n // Safe cast: DynamicForm populates FormStateDeps with its concrete signals.\n return raw as {\n readonly config: Signal<FormConfig<TFields>>;\n readonly formOptions: Signal<FormOptions | undefined>;\n readonly value: WritableSignal<Partial<TModel> | undefined>;\n };\n })();\n\n /** Global value exclusion defaults. */\n private readonly valueExclusionDefaults = inject(VALUE_EXCLUSION_DEFAULTS);\n\n /** Field registry for loading components. */\n private readonly fieldRegistry = injectFieldRegistry();\n\n // ─────────────────────────────────────────────────────────────────────────────\n // State Machine\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly scheduler = createSideEffectScheduler(this.injector);\n private readonly machine: FormStateMachine<TFields>;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Memoized Functions\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly fieldProcessors = inject(CONTAINER_FIELD_PROCESSORS);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Internal State Signals\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Field loading errors accumulated during resolution.\n */\n readonly fieldLoadingErrors = signal<FieldLoadingError[]>([]);\n\n /**\n * Class-level form cache for the \"hold until settled\" pattern.\n * MUST be class-level — a local variable in the computed would reset on re-evaluation.\n * Mutable ref avoids a reactive cycle (form → isSettled → resolvedFields → form).\n */\n private readonly _formCache: { current: ReturnType<typeof form<TModel>> | undefined } = { current: undefined };\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Computed Signals - Derived from State Machine\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * The currently active config used for form rendering.\n * Teardown/Applying → old config, Restoring → new config.\n * Returns deps.config() in uninitialized state so the form schema is\n * available before the state machine dispatches 'initialize'.\n */\n readonly activeConfig = computed(() => {\n const state = this.machine.state();\n\n if (state.type === LifecycleState.Uninitialized) {\n return this.deps.config();\n }\n\n if (isReadyState(state)) return state.config;\n if (isTransitioningState(state)) {\n if (state.phase === Phase.Teardown || state.phase === Phase.Applying) return state.currentConfig;\n return state.pendingConfig;\n }\n if (state.type === LifecycleState.Initializing) return state.config;\n return undefined;\n });\n\n /**\n * Current render phase: 'render' = showing form, 'teardown' = hiding old components.\n */\n readonly renderPhase = computed(() => {\n const state = this.machine.state();\n if (isTransitioningState(state) && state.phase === Phase.Teardown) return Phase.Teardown;\n return 'render';\n });\n\n /** Whether to render the form template. */\n readonly shouldRender = computed(() => this.activeConfig() !== undefined);\n\n /**\n * Computed form mode detection with validation.\n */\n readonly formModeDetection = computed(() => {\n const config = this.activeConfig();\n if (!config) {\n return { mode: 'non-paged' as const, isValid: true, errors: [] };\n }\n\n return detectFormMode(config.fields || []);\n });\n\n /** Validation result for the current form configuration. */\n private readonly formConfigValidation = computed(() => {\n const config = this.activeConfig();\n if (!config) return { isValid: true, errors: [] as string[], warnings: [] as string[] };\n return FormModeValidator.validateFormConfiguration(config.fields || []);\n });\n\n /**\n * Effective form options (merged from config and input).\n */\n readonly effectiveFormOptions = computed(() => {\n const config = this.activeConfig();\n const configOptions = config?.options || {};\n const inputOptions = this.deps.formOptions() ?? undefined;\n return { ...configOptions, ...inputOptions };\n });\n\n /**\n * Page field definitions (for paged forms).\n */\n readonly pageFieldDefinitions = computed(() => {\n const config = this.activeConfig();\n const mode = this.formModeDetection().mode;\n\n if (mode === 'paged' && config?.fields) {\n return config.fields.filter(isPageField);\n }\n\n return [] as PageField[];\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Computed Signals - Form Setup\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly rawFieldRegistry = computed(() => this.fieldRegistry.raw);\n\n /** Computed form setup — reads from the state machine, computed from config on bootstrap. */\n readonly formSetup = computed(() => {\n const registry = this.rawFieldRegistry();\n const state = this.machine.state();\n\n if (isReadyState(state)) {\n return state.formSetup;\n }\n\n if (isTransitioningState(state)) {\n if (state.phase === Phase.Restoring && state.pendingFormSetup) {\n return state.pendingFormSetup;\n }\n return state.currentFormSetup;\n }\n\n // Bootstrap path: compute form setup before the state machine dispatches 'initialize'.\n // Register validators/schemas here so they are available before the first form is built.\n // This is a controlled side effect: registerValidatorsFromConfig is idempotent and only\n // mutates external registries (SchemaRegistry, FunctionRegistry), not reactive state.\n // The state machine's createFormSetup callback handles registration for subsequent configs.\n const config = this.activeConfig();\n if (config) {\n this.registerValidatorsFromConfig(config as FormConfig<TFields>);\n }\n if (!config) {\n return this.createEmptyFormSetup(registry);\n }\n\n if (config.fields && config.fields.length > 0) {\n const modeDetection = this.formModeDetection();\n return this.createFormSetupFromConfig(config.fields as FieldDef<unknown>[], modeDetection.mode, registry);\n }\n\n return this.createEmptyFormSetup(registry);\n });\n\n /**\n * Default values computed from field definitions.\n */\n readonly defaultValues = linkedSignal(() => this.formSetup().defaultValues as TModel);\n\n /** Valid field keys — memoized separately so the Set isn't rebuilt on every keystroke. */\n private readonly validKeys = computed(() => {\n const schemaFields = this.formSetup().schemaFields;\n if (!schemaFields || schemaFields.length === 0) return undefined;\n return new Set(schemaFields.map((f) => f.key).filter((key): key is string => key !== undefined));\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Computed Signals - Entity & Form\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Entity (form value merged with defaults).\n *\n * Bidirectional sync with `deps.value`:\n *\n * 1. **Inward** (deps.value → entity): When the host component sets `value` externally\n * (e.g. two-way binding), this `linkedSignal` source recomputes, merging the new\n * input with field defaults and filtering to valid keys.\n *\n * 2. **Outward** (entity → deps.value): An `explicitEffect` in `setupEffects()` watches\n * `entity` and writes changes back to `deps.value`, keeping the host's model signal\n * in sync with internal form state (e.g. after derivations or reset).\n *\n * The `isEqual` guard on the effect prevents infinite ping-pong: if entity already\n * matches deps.value, the write-back is skipped.\n */\n readonly entity = linkedSignal<TModel>(\n () => {\n const inputValue = this.deps.value();\n const defaults = this.defaultValues();\n const keys = this.validKeys();\n\n const combined = { ...defaults, ...inputValue };\n\n if (keys) {\n const filtered: Record<string, unknown> = {};\n for (const key of Object.keys(combined)) {\n if (keys.has(key)) {\n filtered[key] = (combined as Record<string, unknown>)[key];\n }\n }\n return filtered as TModel;\n }\n\n return combined as TModel;\n },\n {\n debugName: 'FormStateManager.entity',\n equal: isEqual,\n },\n );\n\n /**\n * Schema derived from the current form config and field setup.\n * Separated from `form` so schema construction is memoized independently.\n * Requires `runInInjectionContext` because `createSchemaFromFields` calls `inject()` internally.\n */\n private readonly formSchema = computed((): Schema<TModel> | undefined =>\n runInInjectionContext(this.injector, () => {\n const setup = this.formSetup();\n const config = this.activeConfig();\n\n if (!config) return undefined;\n\n if (setup.schemaFields?.length) {\n const crossFieldCollection = collectCrossFieldEntries(setup.schemaFields as FieldDef<unknown>[]);\n return createSchemaFromFields(setup.schemaFields, setup.registry, {\n crossFieldValidators: crossFieldCollection.validators,\n formLevelSchema: config.schema,\n }) as Schema<TModel>;\n }\n\n if (config.schema) {\n return createFormLevelSchema(config.schema) as Schema<TModel>;\n }\n\n return undefined;\n }),\n );\n\n /**\n * The Angular Signal Form instance.\n */\n readonly form = computed(() => {\n const schema = this.formSchema();\n const injector = this.injector;\n return untracked(() => (schema ? form(this.entity, schema, { injector }) : form(this.entity, { injector })));\n });\n\n /** Whether resolvedFields has caught up with fieldsSource (set in constructor). */\n private isFieldPipelineSettled: Signal<boolean>;\n\n /**\n * Field signal context injected into child components.\n * The `form` getter uses a \"hold until settled\" pattern: returns the cached\n * (old) form while resolvedFields != fieldsSource, preventing stale components\n * from accessing missing FieldTree references.\n */\n readonly fieldSignalContext: Signal<FieldSignalContext<TModel>> = computed(() => {\n const formSignal = this.form;\n const isSettled = () => this.isFieldPipelineSettled();\n const formCache = this._formCache;\n\n return {\n injector: this.injector,\n value: this.deps.value,\n defaultValues: this.defaultValues,\n get form() {\n const currentForm = formSignal();\n const settled = isSettled();\n\n if (!settled && formCache.current) {\n return formCache.current;\n }\n\n formCache.current = currentForm;\n return currentForm;\n },\n };\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Computed Signals - Form State\n // ─────────────────────────────────────────────────────────────────────────────\n\n /** Intermediate computed that unwraps the double-signal (form()()) once. */\n private readonly formInstance = computed(() => this.form()());\n\n /** Current form values (reactive). */\n readonly formValue = computed(() => this.formInstance().value());\n\n /**\n * Form values filtered by value exclusion rules.\n *\n * Excludes field values from the output based on their reactive state\n * (hidden, disabled, readonly) and the 3-tier exclusion config\n * (Field > Form > Global). Only affects submission output — internal\n * form state and two-way binding are unaffected.\n */\n readonly filteredFormValue = computed(() => {\n const rawValue = this.formValue();\n const setup = this.formSetup();\n const options = this.effectiveFormOptions();\n\n if (!setup.schemaFields || setup.schemaFields.length === 0) {\n return rawValue;\n }\n\n // form() returns the FieldTree<TModel> — a callable with per-key sub-trees.\n // formInstance() returns form()() — the FieldState. We need the FieldTree for\n // per-field state access (e.g., formTree[key]() gives FieldState with hidden/disabled/readonly).\n const formTree = this.form();\n\n const formOptions: ValueExclusionConfig = {\n excludeValueIfHidden: options.excludeValueIfHidden,\n excludeValueIfDisabled: options.excludeValueIfDisabled,\n excludeValueIfReadonly: options.excludeValueIfReadonly,\n };\n\n // FieldTree<TModel> is structurally a callable that also exposes per-key sub-trees\n // via bracket access (e.g., formTree['fieldKey']). TypeScript's nominal typing for\n // FieldTree doesn't expose this index signature, so we use a helper cast.\n const fieldTreeRecord = asFieldTreeRecord(formTree);\n\n return filterFormValue(\n rawValue as Record<string, unknown>,\n setup.schemaFields,\n fieldTreeRecord,\n setup.registry,\n this.valueExclusionDefaults,\n formOptions,\n );\n });\n\n /** Whether the form is currently valid. */\n readonly valid = computed(() => this.formInstance().valid());\n\n /** Whether the form is currently invalid. */\n readonly invalid = computed(() => this.formInstance().invalid());\n\n /** Whether any form field has been modified. */\n readonly dirty = computed(() => this.formInstance().dirty());\n\n /** Whether any form field has been touched (blurred). */\n readonly touched = computed(() => this.formInstance().touched());\n\n /** Current validation errors from all fields. */\n readonly errors = computed(() => this.formInstance().errors());\n\n /** Whether the form is disabled (from options or form state). */\n readonly disabled = computed(() => {\n const optionsDisabled = this.effectiveFormOptions().disabled;\n const formDisabled = this.formInstance().disabled();\n return optionsDisabled ?? formDisabled;\n });\n\n /** Whether the form is currently submitting. */\n readonly submitting = computed(() => this.formInstance().submitting());\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Field Resolution\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Phase-aware field source that coordinates component lifecycle with form updates.\n * Teardown/Applying → intersection of old/new fields; Restoring → all new fields.\n * Uses key+type equality to avoid spurious emissions during rapid transitions.\n */\n private readonly fieldsSource = computed(\n () => {\n const state = this.machine.state();\n\n if (isTransitioningState(state)) {\n const oldFields = state.currentConfig.fields ?? [];\n const newFields = state.pendingConfig.fields ?? [];\n const newKeys = new Set(newFields.map((f) => f.key));\n\n if (state.phase === Phase.Teardown || state.phase === Phase.Applying) {\n return oldFields.filter((f) => newKeys.has(f.key));\n }\n\n if (state.phase === Phase.Restoring) {\n return state.pendingFormSetup?.fields ?? this.formSetup().fields;\n }\n }\n\n return this.formSetup().fields;\n },\n {\n equal: (a, b) => {\n if (a === b) return true;\n if (a.length !== b.length) return false;\n return a.every((field, i) => field.key === b[i].key && field.type === b[i].type);\n },\n },\n );\n\n /**\n * Injector for field components with FIELD_SIGNAL_CONTEXT.\n *\n * Recreates the Injector on every `fieldSignalContext` change. This is intentional:\n * `reconcileFields()` compares the injector reference to detect context changes\n * (e.g. after a config transition). A new injector reference signals that\n * `NgComponentOutlet` should pick up the updated context, while an unchanged\n * reference preserves object identity to avoid unnecessary re-renders.\n */\n private readonly fieldInjector = computed(() =>\n Injector.create({\n parent: this.injector,\n providers: [{ provide: FIELD_SIGNAL_CONTEXT, useValue: this.fieldSignalContext() }],\n }),\n );\n\n /** Resolved fields ready for rendering. */\n readonly resolvedFields: Signal<ResolvedField[]>;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Event Streams (for outputs)\n // ─────────────────────────────────────────────────────────────────────────────\n\n /** Stream of submit events when form is valid. */\n readonly submitted$: Observable<Partial<TModel>>;\n\n /** Stream of reset events. */\n readonly reset$: Observable<void>;\n\n /** Stream of clear events. */\n readonly cleared$: Observable<void>;\n\n /** Emits once when the state machine reaches 'ready'. Useful for tests. */\n get ready$(): Observable<void> {\n return this.machine.state$.pipe(\n filter(isReadyState),\n take(1),\n map(() => undefined),\n );\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────────\n\n constructor() {\n this.resolvedFields = derivedFromDeferred(\n this.fieldsSource,\n pipe(\n switchMap((fields) => {\n if (!fields || fields.length === 0) {\n return of([] as (ResolvedField | undefined)[]);\n }\n\n const registry = this.rawFieldRegistry();\n const injector = this.fieldInjector();\n\n const syncContext = {\n getLoadedComponent: (type: string) => this.fieldRegistry.getLoadedComponent(type),\n registry,\n injector,\n };\n\n // Hybrid: resolve cached fields sync, only await uncached ones\n const results: (ResolvedField | undefined)[] = new Array(fields.length);\n const asyncIndexes: number[] = [];\n const asyncObs: Observable<ResolvedField | undefined>[] = [];\n\n const onError = (fieldDef: FieldDef<unknown>, error: unknown) => {\n const fieldKey = fieldDef.key || '<no key>';\n this.fieldLoadingErrors.update((errors) => [\n ...errors,\n {\n fieldType: fieldDef.type,\n fieldKey,\n error: error instanceof Error ? error : new Error(String(error)),\n },\n ]);\n this.logger.error(\n `Failed to load component for field type '${fieldDef.type}' (key: ${fieldKey}). ` +\n `Ensure the field type is registered in your field registry.`,\n error,\n );\n };\n\n for (let i = 0; i < fields.length; i++) {\n const f = fields[i];\n const def = this.fieldRegistry.getType(f.type);\n const isCached = !def?.loadComponent || this.fieldRegistry.getLoadedComponent(f.type);\n\n if (isCached) {\n results[i] = resolveFieldSync(f, syncContext);\n } else {\n asyncIndexes.push(i);\n asyncObs.push(\n resolveField(f, {\n loadTypeComponent: (type: string) => this.fieldRegistry.loadTypeComponent(type),\n registry,\n injector,\n destroyRef: this.destroyRef,\n onError,\n }),\n );\n }\n }\n\n if (asyncObs.length === 0) {\n return of(results);\n }\n\n return forkJoin(asyncObs).pipe(\n map((asyncResults) => {\n for (let j = 0; j < asyncResults.length; j++) {\n results[asyncIndexes[j]] = asyncResults[j];\n }\n return results;\n }),\n );\n }),\n map((fields) => fields.filter((f): f is ResolvedField => f !== undefined)),\n scan(reconcileFields, [] as ResolvedField[]),\n ),\n { initialValue: [] as ResolvedField[], injector: this.injector },\n ) as Signal<ResolvedField[]>;\n\n // Length comparison works because reconcileFields preserves ordering and\n // fieldsSource changes atomically during transitions (lengths won't match until settled).\n this.isFieldPipelineSettled = computed(() => {\n return this.fieldsSource().length === this.resolvedFields().length;\n });\n\n this.submitted$ = this.eventBus.on<SubmitEvent>('submit').pipe(\n filter(() => {\n if (!this.valid()) {\n this.logger.debug('Form submitted while invalid, not emitting to (submitted) output');\n return false;\n }\n return true;\n }),\n // switchMap is intentional here: mapping is synchronous (reads signals, no async Promise).\n // The exhaustMap concern in createSubmissionHandler does not apply to this path.\n switchMap(() => {\n const config = this.activeConfig();\n const submissionConfig = config?.submission;\n\n if (submissionConfig?.action) {\n this.logger.warn(\n 'Both `submission.action` and `(submitted)` output are configured. ' +\n 'When using `submission.action`, the `(submitted)` output will not emit. ' +\n 'Use either `submission.action` OR `(submitted)`, not both.',\n );\n return EMPTY;\n }\n\n return of(this.filteredFormValue() as TModel);\n }),\n takeUntilDestroyed(this.destroyRef),\n );\n\n this.reset$ = this.eventBus.on<FormResetEvent>('form-reset').pipe(\n map(() => undefined as void),\n takeUntilDestroyed(this.destroyRef),\n );\n\n this.cleared$ = this.eventBus.on<FormClearEvent>('form-clear').pipe(\n map(() => undefined as void),\n takeUntilDestroyed(this.destroyRef),\n );\n\n // Create the state machine eagerly\n this.machine = createFormStateMachine<TFields>({\n injector: this.injector,\n destroyRef: this.destroyRef,\n scheduler: this.scheduler,\n logger: this.logger,\n createFormSetup: (config) => {\n this.registerValidatorsFromConfig(config);\n return this.createFormSetupFromConfig(\n (config.fields as FieldDef<unknown>[]) ?? [],\n detectFormMode(config.fields ?? []).mode,\n this.rawFieldRegistry(),\n );\n },\n captureValue: () => this.formValue() as Record<string, unknown>,\n isSubmitting: this.submitting,\n isFieldPipelineSettled: () => this.isFieldPipelineSettled(),\n restoreValue: (values, validKeys) => {\n const filtered: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(values)) {\n if (validKeys.has(key)) {\n filtered[key] = val;\n }\n }\n if (Object.keys(filtered).length > 0) {\n this.deps.value.update((current) => ({ ...current, ...filtered }) as Partial<TModel>);\n }\n },\n onTransition: (transition) => {\n this.logger.debug('State transition:', transition.from.type, '→', transition.to.type, transition.action.type);\n },\n onError: (error, action) => {\n this.logger.error(`State machine error recovery triggered for action '${action.type}':`, error);\n },\n });\n\n runInInjectionContext(this.injector, () => {\n this.setupEffects();\n this.setupEventHandlers();\n });\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Public Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Updates the form value model.\n */\n updateValue(value: Partial<TModel>): void {\n this.deps.value.set(value);\n }\n\n /**\n * Resets the form to default values.\n */\n reset(): void {\n const defaults = this.defaultValues();\n (this.form()().value as WritableSignal<TModel>).set(defaults);\n this.deps.value.set(defaults as Partial<TModel>);\n }\n\n /**\n * Clears the form to empty state.\n */\n clear(): void {\n const emptyValue = {} as TModel;\n (this.form()().value as WritableSignal<TModel>).set(emptyValue);\n this.deps.value.set(emptyValue);\n }\n\n /**\n * Triggers form submission.\n */\n submit(): void {\n this.eventBus.dispatch(SubmitEvent);\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Methods - Setup\n // ─────────────────────────────────────────────────────────────────────────────\n\n private setupEffects(): void {\n explicitEffect([this.deps.config], ([config]) => {\n this.fieldLoadingErrors.set([]);\n\n const state = this.machine.currentState;\n if (state.type === LifecycleState.Uninitialized) {\n this.machine.dispatch({ type: Action.Initialize, config });\n } else {\n this.machine.dispatch({ type: Action.ConfigChange, config });\n }\n });\n\n // Outward sync: write entity changes back to deps.value (see entity JSDoc for full explanation).\n // The isEqual guard prevents infinite ping-pong between this effect and the linkedSignal source.\n explicitEffect([this.entity], ([currentEntity]) => {\n const currentValue = this.deps.value();\n if (!isEqual(currentEntity, currentValue)) {\n this.deps.value.set(currentEntity);\n }\n });\n\n explicitEffect([this.formConfigValidation], ([validation]) => {\n if (!validation.isValid) {\n this.logger.error('Invalid form configuration:', validation.errors);\n }\n if (validation.warnings.length > 0) {\n this.logger.warn('Form configuration warnings:', validation.warnings);\n }\n });\n }\n\n private setupEventHandlers(): void {\n this.eventBus\n .on<FormResetEvent>('form-reset')\n .pipe(takeUntilDestroyed(this.destroyRef))\n .subscribe(() => this.reset());\n\n this.eventBus\n .on<FormClearEvent>('form-clear')\n .pipe(takeUntilDestroyed(this.destroyRef))\n .subscribe(() => this.clear());\n }\n\n private registerValidatorsFromConfig({ customFnConfig, schemas }: FormConfig<TFields>): void {\n if (schemas) {\n schemas.forEach((schema) => {\n this.schemaRegistry.registerSchema(schema);\n });\n }\n\n if (!customFnConfig) {\n return;\n }\n\n if (customFnConfig.customFunctions) {\n Object.entries(customFnConfig.customFunctions).forEach(([name, fn]) => {\n this.functionRegistry.registerCustomFunction(name, fn);\n });\n }\n\n if (customFnConfig.derivations) {\n this.functionRegistry.setDerivationFunctions(customFnConfig.derivations);\n }\n\n if (customFnConfig.asyncDerivations) {\n this.functionRegistry.setAsyncDerivationFunctions(customFnConfig.asyncDerivations);\n }\n if (customFnConfig.asyncConditions) {\n this.functionRegistry.setAsyncConditionFunctions(customFnConfig.asyncConditions);\n }\n\n this.functionRegistry.setValidators(customFnConfig.validators);\n this.functionRegistry.setAsyncValidators(customFnConfig.asyncValidators);\n this.functionRegistry.setHttpValidators(customFnConfig.httpValidators);\n }\n\n private createFormSetupFromConfig(fields: FieldDef<unknown>[], mode: FormMode, registry: Map<string, FieldTypeDefinition>): FormSetup {\n const normalizedFields = normalizeSimplifiedArrays(fields);\n // Validate after normalization so simplified array templates are already expanded\n // into full ArrayField.fields and are reachable during traversal.\n validateFormConfig(normalizedFields, registry, this.logger);\n const flattenedFields = this.fieldProcessors.memoizedFlattenFields(normalizedFields, registry);\n const flattenedFieldsForRendering = this.fieldProcessors.memoizedFlattenFieldsForRendering(normalizedFields, registry);\n const fieldsById = this.fieldProcessors.memoizedKeyBy(flattenedFields);\n const defaultValues = this.fieldProcessors.memoizedDefaultValues(fieldsById, registry);\n const fieldsToRender = mode === 'paged' ? [] : flattenedFieldsForRendering;\n\n return {\n fields: fieldsToRender,\n schemaFields: flattenedFields,\n originalFields: fields,\n defaultValues,\n mode,\n registry,\n };\n }\n\n private createEmptyFormSetup(registry: Map<string, FieldTypeDefinition>): FormSetup {\n return {\n fields: [],\n schemaFields: [],\n defaultValues: {} as Record<string, unknown>,\n mode: 'non-paged' as const,\n registry,\n };\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Lifecycle\n // ─────────────────────────────────────────────────────────────────────────────\n\n ngOnDestroy(): void {\n this.machine.dispatch({ type: Action.Destroy });\n }\n}\n","import { Logger } from '../../providers/features/logger/logger.interface';\nimport { DerivationLogConfig, createDefaultDerivationLogConfig, shouldLog } from '../../models/logic/logic-config';\nimport { DerivationProcessingResult } from './derivation-types';\nimport { DerivationLogEntry } from './derivation-logger';\n\n/**\n * Service interface for derivation logging.\n *\n * Provides methods to log derivation processing events at different verbosity levels.\n * Use `createDerivationLogger` factory to create an instance.\n *\n * @public\n */\nexport interface DerivationLogger {\n /**\n * Logs the start of a derivation processing cycle.\n * Only logs when config level is 'verbose'.\n */\n cycleStart(trigger: 'onChange' | 'debounced', entryCount: number): void;\n\n /**\n * Logs the start of a derivation iteration within a cycle.\n * Only logs when config level is 'verbose'.\n */\n iteration(iterationNumber: number): void;\n\n /**\n * Logs a single derivation evaluation result.\n * Only logs when config level is 'verbose'.\n */\n evaluation(entry: DerivationLogEntry): void;\n\n /**\n * Logs a summary of derivation processing results.\n * Logs when config level is 'summary' or 'verbose' and something interesting happened.\n */\n summary(result: DerivationProcessingResult, trigger: 'onChange' | 'debounced'): void;\n\n /**\n * Logs when max iterations are reached (always logged as warning).\n */\n maxIterationsReached(result: DerivationProcessingResult, trigger: 'onChange' | 'debounced'): void;\n}\n\n/**\n * Active implementation of DerivationLogger that performs actual logging.\n *\n * @internal\n */\nclass ActiveDerivationLogger implements DerivationLogger {\n logger!: Logger;\n private config: DerivationLogConfig = createDefaultDerivationLogConfig();\n\n /**\n * Updates the log configuration.\n */\n setConfig(config: DerivationLogConfig): void {\n this.config = config;\n }\n\n cycleStart(trigger: 'onChange' | 'debounced', entryCount: number): void {\n if (!shouldLog(this.config, 'verbose')) return;\n this.logger.debug(`Derivation - Starting cycle (${trigger}) with ${entryCount} derivation(s)`);\n }\n\n iteration(iterationNumber: number): void {\n if (!shouldLog(this.config, 'verbose')) return;\n this.logger.debug(`Derivation - Iteration ${iterationNumber}`);\n }\n\n evaluation(entry: DerivationLogEntry): void {\n if (!shouldLog(this.config, 'verbose')) return;\n\n const name = entry.debugName ? `\"${entry.debugName}\"` : entry.fieldKey;\n\n switch (entry.result) {\n case 'applied':\n this.logger.debug(`Derivation - Applied ${name}`, {\n field: entry.fieldKey,\n previousValue: entry.previousValue,\n newValue: entry.newValue,\n ...(entry.durationMs !== undefined && { durationMs: entry.durationMs }),\n });\n break;\n\n case 'skipped':\n this.logger.debug(`Derivation - Skipped ${name} (${this.formatSkipReason(entry.skipReason)})`, {\n field: entry.fieldKey,\n reason: entry.skipReason,\n });\n break;\n\n case 'error':\n this.logger.debug(`Derivation - Error ${name}`, {\n field: entry.fieldKey,\n error: entry.error,\n });\n break;\n }\n }\n\n summary(result: DerivationProcessingResult, trigger: 'onChange' | 'debounced'): void {\n if (!shouldLog(this.config, 'summary')) return;\n\n // Only log if something interesting happened\n if (result.appliedCount === 0 && result.errorCount === 0) return;\n\n this.logger.debug(`Derivation - Cycle complete (${trigger})`, {\n applied: result.appliedCount,\n skipped: result.skippedCount,\n errors: result.errorCount,\n iterations: result.iterations,\n });\n }\n\n maxIterationsReached(result: DerivationProcessingResult, trigger: 'onChange' | 'debounced'): void {\n this.logger.warn(\n `Derivation - Max iterations reached (${trigger}). ` +\n `This may indicate a loop in derivation logic. ` +\n `Applied: ${result.appliedCount}, Skipped: ${result.skippedCount}, Errors: ${result.errorCount}`,\n );\n }\n\n private formatSkipReason(reason?: string): string {\n switch (reason) {\n case 'condition-false':\n return 'condition not met';\n case 'value-unchanged':\n return 'value unchanged';\n case 'already-applied':\n return 'already applied this cycle';\n case 'user-override':\n return 'user override active';\n case 'target-not-found':\n return 'target not found';\n default:\n return 'unknown';\n }\n }\n}\n\n/**\n * No-op implementation of DerivationLogger.\n * All methods are empty - no logging overhead when disabled.\n *\n * @internal\n */\nclass NoopDerivationLogger implements DerivationLogger {\n cycleStart(): void {\n /* no-op */\n }\n iteration(): void {\n /* no-op */\n }\n evaluation(): void {\n /* no-op */\n }\n summary(): void {\n /* no-op */\n }\n maxIterationsReached(): void {\n /* no-op */\n }\n}\n\n/** Singleton no-op instance to avoid creating new objects */\nconst NOOP_INSTANCE = new NoopDerivationLogger();\n\n/**\n * Factory function to create a DerivationLogger.\n *\n * Returns a no-op implementation if config level is 'none',\n * otherwise returns an active logger with the given config.\n *\n * @param config - The derivation log configuration\n * @param logger - The underlying logger instance\n * @returns A DerivationLogger instance\n *\n * @public\n */\nexport function createDerivationLogger(config: DerivationLogConfig | undefined, logger: Logger): DerivationLogger {\n const effectiveConfig = config ?? createDefaultDerivationLogConfig();\n\n // Return no-op if logging is completely disabled\n if (effectiveConfig.level === 'none') {\n return NOOP_INSTANCE;\n }\n\n // Create active logger with config\n const service = new ActiveDerivationLogger();\n service.logger = logger;\n service.setConfig(effectiveConfig);\n\n return service;\n}\n","import { Provider } from '@angular/core';\n\n/**\n * Base interface for dynamic form features.\n * Features are configuration options that can be passed to provideDynamicForm\n * alongside field type definitions.\n *\n * Uses Angular-style internal marker (ɵkind) to distinguish from field types.\n */\nexport interface DynamicFormFeature<TKind extends string = string> {\n /** Internal marker to identify this as a feature, not a field type */\n ɵkind: TKind;\n /** Providers to register for this feature */\n ɵproviders: Provider[];\n}\n\n/**\n * Known feature kinds for type safety\n */\nexport type DynamicFormFeatureKind = 'logger' | 'event-form-value' | 'value-exclusion';\n\n/**\n * Type guard to check if a value is a DynamicFormFeature\n */\nexport function isDynamicFormFeature(value: unknown): value is DynamicFormFeature {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'ɵkind' in value &&\n typeof (value as DynamicFormFeature).ɵkind === 'string' &&\n 'ɵproviders' in value &&\n Array.isArray((value as DynamicFormFeature).ɵproviders)\n );\n}\n\n/**\n * Helper to create a feature with proper typing\n */\nexport function createFeature<TKind extends DynamicFormFeatureKind>(kind: TKind, providers: Provider[]): DynamicFormFeature<TKind> {\n return {\n ɵkind: kind,\n ɵproviders: providers,\n };\n}\n","import type { Logger } from './logger.interface';\n\n/**\n * Console-based logger implementation.\n */\nexport class ConsoleLogger implements Logger {\n private readonly prefix = '[Dynamic Forms]';\n\n debug(message: string, ...args: unknown[]): void {\n console.debug(this.prefix, message, ...args);\n }\n\n info(message: string, ...args: unknown[]): void {\n console.info(this.prefix, message, ...args);\n }\n\n warn(message: string, ...args: unknown[]): void {\n console.warn(this.prefix, message, ...args);\n }\n\n error(message: string, ...args: unknown[]): void {\n console.error(this.prefix, message, ...args);\n }\n}\n","import { InjectionToken } from '@angular/core';\nimport { createFeature, DynamicFormFeature } from '../dynamic-form-feature';\nimport { DynamicFormLogger } from './logger.token';\nimport { ConsoleLogger } from './console-logger';\nimport { NoopLogger } from './noop-logger';\nimport { DerivationLogConfig, DerivationLogLevel, createDefaultDerivationLogConfig } from '../../../models/logic/logic-config';\n\n/**\n * Injection token for derivation logging configuration.\n *\n * @internal\n */\nexport const DERIVATION_LOG_CONFIG = new InjectionToken<DerivationLogConfig>('DERIVATION_LOG_CONFIG', {\n providedIn: 'root',\n factory: createDefaultDerivationLogConfig,\n});\n\n/**\n * Configuration options for the logger feature.\n *\n * @public\n */\nexport interface LoggerConfigOptions {\n /**\n * Whether general logging is enabled.\n *\n * @default true\n */\n enabled?: boolean;\n\n /**\n * Derivation logging level.\n *\n * - `'none'`: No derivation debug logging (default)\n * - `'summary'`: Log cycle completion with counts\n * - `'verbose'`: Log individual derivation evaluations with details\n *\n * @default 'none'\n */\n derivations?: DerivationLogLevel;\n}\n\n/**\n * Configure logging for dynamic forms.\n *\n * By default, general logging is enabled (ConsoleLogger) and derivation\n * logging is disabled ('none'). Use this feature to enable derivation debugging.\n *\n * @example\n * ```typescript\n * // Disable all logging\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withLoggerConfig(false)\n * )\n *\n * // Enable verbose derivation logging\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withLoggerConfig({ derivations: 'verbose' })\n * )\n *\n * // Disable derivation logging but keep general logging\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withLoggerConfig({ derivations: 'none' })\n * )\n *\n * // Conditional logging (e.g., only in dev mode)\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withLoggerConfig(() => isDevMode())\n * )\n * ```\n *\n * @param config - Boolean to enable/disable logging, a function returning boolean, or a config object\n * @returns A DynamicFormFeature that configures logging\n *\n * @public\n */\nexport function withLoggerConfig(config: boolean | (() => boolean) | LoggerConfigOptions = true): DynamicFormFeature<'logger'> {\n // Handle boolean or function\n if (typeof config === 'boolean' || typeof config === 'function') {\n const isEnabled = typeof config === 'function' ? config() : config;\n const logger = isEnabled ? new ConsoleLogger() : new NoopLogger();\n return createFeature('logger', [{ provide: DynamicFormLogger, useValue: logger }]);\n }\n\n // Handle config object\n const isEnabled = config.enabled !== false;\n const logger = isEnabled ? new ConsoleLogger() : new NoopLogger();\n\n const providers: { provide: InjectionToken<unknown>; useValue: unknown }[] = [{ provide: DynamicFormLogger, useValue: logger }];\n\n // Add derivation log config if specified\n if (config.derivations !== undefined) {\n providers.push({\n provide: DERIVATION_LOG_CONFIG,\n useValue: { level: config.derivations },\n });\n }\n\n return createFeature('logger', providers);\n}\n","import { computed, Provider, Signal } from '@angular/core';\nimport { FieldTree } from '@angular/forms/signals';\nimport { EventBus } from '../events/event.bus';\nimport { FieldContextRegistryService } from '../core/registry/field-context-registry.service';\nimport { FunctionRegistryService } from '../core/registry/function-registry.service';\nimport { RootFormRegistryService } from '../core/registry/root-form-registry.service';\nimport { SchemaRegistryService } from '../core/registry/schema-registry.service';\nimport { FormStateManager, FORM_STATE_DEPS, FormStateDeps } from '../state/form-state-manager';\nimport {\n DEFAULT_PROPS,\n DEFAULT_VALIDATION_MESSAGES,\n DEFAULT_WRAPPERS,\n EXTERNAL_DATA,\n FORM_OPTIONS,\n} from '../models/field-signal-context.token';\nimport { DERIVATION_WARNING_TRACKER, createDerivationWarningTracker } from '../core/derivation/derivation-warning-tracker';\nimport { DEPRECATION_WARNING_TRACKER, createDeprecationWarningTracker } from '../utils/deprecation-warning-tracker';\nimport {\n DERIVATION_ORCHESTRATOR,\n createDerivationOrchestrator,\n DerivationOrchestratorConfig,\n} from '../core/derivation/derivation-orchestrator';\nimport { createDerivationLogger } from '../core/derivation/derivation-logger.service';\nimport { DynamicFormLogger } from './features/logger/logger.token';\nimport { Logger } from './features/logger/logger.interface';\nimport { DERIVATION_LOG_CONFIG } from './features/logger/with-logger-config';\nimport { DerivationLogConfig } from '../models/logic/logic-config';\nimport { FieldDef } from '../definitions/base/field-def';\nimport { CONTAINER_FIELD_PROCESSORS, createContainerFieldProcessors } from '../utils/container-utils/container-field-processors';\nimport {\n createPropertyOverrideStore,\n PROPERTY_OVERRIDE_STORE,\n PropertyOverrideStore,\n} from '../core/property-derivation/property-override-store';\nimport { HTTP_CONDITION_CACHE, HttpConditionCache } from '../core/http/http-condition-cache';\nimport { LogicFunctionCacheService } from '../core/expressions/logic-function-cache.service';\nimport { HttpConditionFunctionCacheService } from '../core/expressions/http-condition-function-cache.service';\nimport { AsyncConditionFunctionCacheService } from '../core/expressions/async-condition-function-cache.service';\nimport { DynamicValueFunctionCacheService } from '../core/values/dynamic-value-function-cache.service';\nimport {\n createPropertyDerivationOrchestrator,\n PROPERTY_DERIVATION_ORCHESTRATOR,\n PropertyDerivationOrchestratorConfig,\n} from '../core/property-derivation/property-derivation-orchestrator';\n\n/** @internal */\nexport function provideDynamicFormDI(): Provider[] {\n return [\n EventBus,\n { provide: CONTAINER_FIELD_PROCESSORS, useFactory: createContainerFieldProcessors },\n SchemaRegistryService,\n FunctionRegistryService,\n {\n provide: FORM_STATE_DEPS,\n useFactory: (): FormStateDeps => ({ config: null, formOptions: null, value: null }),\n },\n FormStateManager,\n {\n provide: RootFormRegistryService,\n useFactory: (stateManager: FormStateManager) =>\n new RootFormRegistryService(\n stateManager.formValue as Signal<Record<string, unknown>>,\n computed(() => stateManager.form()),\n ),\n deps: [FormStateManager],\n },\n FieldContextRegistryService,\n {\n provide: DEFAULT_PROPS,\n useFactory: (stateManager: FormStateManager) => computed(() => stateManager.activeConfig()?.defaultProps),\n deps: [FormStateManager],\n },\n {\n provide: DEFAULT_WRAPPERS,\n useFactory: (stateManager: FormStateManager) => computed(() => stateManager.activeConfig()?.defaultWrappers),\n deps: [FormStateManager],\n },\n {\n provide: DEFAULT_VALIDATION_MESSAGES,\n useFactory: (stateManager: FormStateManager) => computed(() => stateManager.activeConfig()?.defaultValidationMessages),\n deps: [FormStateManager],\n },\n {\n provide: FORM_OPTIONS,\n useFactory: (stateManager: FormStateManager) => stateManager.effectiveFormOptions,\n deps: [FormStateManager],\n },\n {\n provide: EXTERNAL_DATA,\n useFactory: (stateManager: FormStateManager) => computed(() => stateManager.activeConfig()?.externalData),\n deps: [FormStateManager],\n },\n { provide: DERIVATION_WARNING_TRACKER, useFactory: createDerivationWarningTracker },\n { provide: DEPRECATION_WARNING_TRACKER, useFactory: createDeprecationWarningTracker },\n {\n provide: DERIVATION_ORCHESTRATOR,\n useFactory: (\n stateManager: FormStateManager,\n logger: Logger,\n logConfig: DerivationLogConfig,\n externalData: Signal<Record<string, Signal<unknown>> | undefined>,\n ) => {\n // FormStateManager is injected without type parameters, so its generic defaults\n // to Record<string, unknown>. The casts widen the type to match DerivationOrchestratorConfig\n // which uses unknown — safe because the orchestrator only reads values.\n const config: DerivationOrchestratorConfig = {\n schemaFields: computed(() => stateManager.formSetup()?.schemaFields as FieldDef<unknown>[] | undefined),\n formValue: stateManager.formValue as Signal<Record<string, unknown>>,\n form: computed(() => stateManager.form() as unknown as FieldTree<unknown>),\n derivationLogger: computed(() => createDerivationLogger(logConfig, logger)),\n externalData,\n };\n return createDerivationOrchestrator(config);\n },\n deps: [FormStateManager, DynamicFormLogger, DERIVATION_LOG_CONFIG, EXTERNAL_DATA],\n },\n { provide: HTTP_CONDITION_CACHE, useFactory: () => new HttpConditionCache(100) },\n LogicFunctionCacheService,\n HttpConditionFunctionCacheService,\n AsyncConditionFunctionCacheService,\n DynamicValueFunctionCacheService,\n { provide: PROPERTY_OVERRIDE_STORE, useFactory: createPropertyOverrideStore },\n {\n provide: PROPERTY_DERIVATION_ORCHESTRATOR,\n useFactory: (\n stateManager: FormStateManager,\n externalData: Signal<Record<string, Signal<unknown>> | undefined>,\n store: PropertyOverrideStore,\n ) => {\n const config: PropertyDerivationOrchestratorConfig = {\n schemaFields: computed(() => stateManager.formSetup()?.schemaFields as FieldDef<unknown>[] | undefined),\n formValue: stateManager.formValue as Signal<Record<string, unknown>>,\n store,\n externalData,\n };\n return createPropertyDerivationOrchestrator(config);\n },\n deps: [FormStateManager, EXTERNAL_DATA, PROPERTY_OVERRIDE_STORE],\n },\n ];\n}\n","import { Injectable } from '@angular/core';\nimport { EventBus } from '../events/event.bus';\nimport { FormEvent } from '../events/interfaces/form-event';\n\n/**\n * Injectable service for dispatching events into a DynamicForm from outside the form.\n *\n * ## When to use\n *\n * Use `EventDispatcher` when you need to drive form behaviour **from the host component** —\n * for example, appending array items in response to a field value change, triggering a form\n * reset from a toolbar button, or reacting to external application state.\n *\n * This is the recommended alternative to accessing the form's internals via `viewChild`.\n *\n * ## Setup\n *\n * Provide `EventDispatcher` at the **host component** level (not root). DynamicForm\n * automatically detects it and connects its internal event bus to the dispatcher.\n *\n * ```typescript\n * @Component({\n * providers: [EventDispatcher],\n * template: `<form [dynamic-form]=\"config\" [(value)]=\"formValue\"></form>`\n * })\n * export class MyComponent {\n * readonly dispatcher = inject(EventDispatcher);\n * readonly formValue = signal<Record<string, unknown>>({});\n *\n * constructor() {\n * effect(() => {\n * const category = this.formValue()?.['category'] as string | undefined;\n * if (category) {\n * this.dispatcher.dispatch(\n * arrayEvent('tasks').append([{ key: 'name', type: 'input', label: 'Task', value: category }])\n * );\n * }\n * });\n * }\n * }\n * ```\n *\n * ## Multi-form note\n *\n * If multiple `DynamicForm` instances exist under the same provider scope, **all forms**\n * will receive dispatched events. To target a specific form, scope the provider to a\n * wrapper component that contains only that form.\n *\n * ## What events can be dispatched\n *\n * Any `FormEvent` instance is accepted — array events, reset/clear events, custom events, etc.\n * The `arrayEvent()` builder is the recommended way to construct array manipulation events:\n *\n * ```typescript\n * dispatcher.dispatch(arrayEvent('tasks').append(template));\n * dispatcher.dispatch(arrayEvent('tasks').removeAt(0));\n * dispatcher.dispatch(new FormResetEvent());\n * ```\n */\n@Injectable()\nexport class EventDispatcher {\n private bus: EventBus | undefined;\n\n /**\n * Dispatches a form event into the connected DynamicForm's event bus.\n * No-op if no form is currently connected.\n *\n * @param event - A FormEvent instance. Use the `arrayEvent()` builder for array operations.\n */\n dispatch(event: FormEvent): void {\n this.bus?.emitInstance(event);\n }\n\n /** @internal - Called by DynamicForm on init */\n connect(bus: EventBus): void {\n this.bus = bus;\n }\n\n /** @internal - Called by DynamicForm on destroy */\n disconnect(): void {\n this.bus = undefined;\n }\n}\n","import {\n afterNextRender,\n ChangeDetectionStrategy,\n Component,\n computed,\n DestroyRef,\n EnvironmentInjector,\n inject,\n Injector,\n input,\n model,\n Signal,\n WritableSignal,\n} from '@angular/core';\nimport { FieldDef } from './definitions/base/field-def';\nimport { DfFieldOutlet } from './directives/df-field-outlet.directive';\nimport { FieldTree } from '@angular/forms/signals';\nimport { outputFromObservable, takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';\nimport { createSubmissionHandler } from './utils/submission-handler/submission-handler';\nimport { FormConfig, FormOptions } from './models/form-config';\nimport { RegisteredFieldTypes } from './models/registry/field-registry';\nimport { EventBus } from './events/event.bus';\nimport { SubmitEvent } from './events/constants/submit.event';\nimport { ComponentInitializedEvent } from './events/constants/component-initialized.event';\nimport { setupInitializationTracking } from './utils/initialization-tracker/initialization-tracker';\nimport { InferFormValue } from './models/types/form-value-inference';\nimport { hasChildFields, isContainerField } from './models/types/type-guards';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { DERIVATION_ORCHESTRATOR } from './core/derivation/derivation-orchestrator';\nimport { PROPERTY_DERIVATION_ORCHESTRATOR } from './core/property-derivation/property-derivation-orchestrator';\nimport { PageOrchestratorComponent } from './core/page-orchestrator/page-orchestrator.component';\nimport { FormClearEvent } from './events/constants/form-clear.event';\nimport { FormResetEvent } from './events/constants/form-reset.event';\nimport { PageChangeEvent } from './events/constants/page-change.event';\nimport { PageNavigationStateChangeEvent } from './events/constants/page-navigation-state-change.event';\nimport { DynamicFormLogger } from './providers/features/logger/logger.token';\nimport { FormStateManager, FORM_STATE_DEPS } from './state/form-state-manager';\nimport { provideDynamicFormDI } from './providers/dynamic-form-di';\nimport { EventDispatcher } from './events/event-dispatcher';\n\n/**\n * Dynamic form component — renders a form based on configuration.\n * Delegates state management to `FormStateManager`.\n *\n * @example\n *```html\n * <form [dynamic-form]=\"formConfig\" [(value)]=\"formData\" (submitted)=\"handleSubmit($event)\"></form>\n * ```\n */\n@Component({\n selector: 'form[dynamic-form]',\n imports: [DfFieldOutlet, PageOrchestratorComponent],\n template: `\n @if (shouldRender()) {\n @switch (formModeDetection().mode) {\n @case ('paged') {\n <div page-orchestrator [pageFields]=\"pageFieldDefinitions()\" [form]=\"form()\" [fieldSignalContext]=\"fieldSignalContext()\"></div>\n }\n @case ('non-paged') {\n @for (field of resolvedFields(); track field.key) {\n <ng-container *dfFieldOutlet=\"field; environmentInjector: environmentInjector\" />\n }\n }\n @default {\n never;\n }\n }\n }\n `,\n styleUrl: './dynamic-form.component.scss',\n providers: [provideDynamicFormDI()],\n host: {\n class: 'df-dynamic-form df-form',\n novalidate: '', // Disable browser validation - Angular Signal Forms handles validation\n '[class.disabled]': 'disabled()',\n '[class.df-form-paged]': 'formModeDetection().mode === \"paged\"',\n '[class.df-form-non-paged]': 'formModeDetection().mode === \"non-paged\"',\n '[attr.data-form-mode]': 'formModeDetection().mode',\n '(submit)': 'onNativeSubmit($event)',\n },\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport class DynamicForm<\n TFields extends RegisteredFieldTypes[] = RegisteredFieldTypes[],\n TModel extends Record<string, unknown> = InferFormValue<TFields> & Record<string, unknown>,\n> {\n // ─────────────────────────────────────────────────────────────────────────────\n // Inputs (must be declared BEFORE deps connection and stateManager injection)\n // ─────────────────────────────────────────────────────────────────────────────\n\n /** Form configuration defining the structure, validation, and behavior. */\n config = input.required<FormConfig<TFields>>({ alias: 'dynamic-form' });\n\n /** Runtime form options that override config options when provided. */\n formOptions = input<FormOptions | undefined>(undefined);\n\n /** Form values for two-way data binding. */\n value = model<Partial<TModel> | undefined>(undefined);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Dependencies\n // ─────────────────────────────────────────────────────────────────────────────\n\n private destroyRef = inject(DestroyRef);\n private injector = inject(Injector);\n protected environmentInjector = inject(EnvironmentInjector);\n private eventBus = inject(EventBus);\n private logger = inject(DynamicFormLogger);\n private dispatcher = inject(EventDispatcher, { optional: true });\n\n /** State manager that owns all form state. Initialized via connectDeps() to guarantee\n * FORM_STATE_DEPS is populated before FormStateManager is injected. */\n private readonly stateManager = this.connectDeps();\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private State\n // ─────────────────────────────────────────────────────────────────────────────\n\n private componentId = 'dynamic-form';\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Signals - Direct pass-through from state manager\n // ─────────────────────────────────────────────────────────────────────────────\n\n /** The currently active config used for form rendering */\n activeConfig = this.stateManager.activeConfig;\n\n /** Current render phase: 'render' = showing form, 'teardown' = hiding old components */\n renderPhase = this.stateManager.renderPhase;\n\n /** Computed form mode detection with validation */\n formModeDetection = this.stateManager.formModeDetection;\n\n /** Page field definitions for paged forms */\n pageFieldDefinitions = this.stateManager.pageFieldDefinitions;\n\n /** Effective form options (merged from config and input) */\n effectiveFormOptions = this.stateManager.effectiveFormOptions;\n\n /** Field signal context for injection into child components */\n fieldSignalContext = this.stateManager.fieldSignalContext;\n\n /** Default values computed from field definitions */\n defaultValues = this.stateManager.defaultValues;\n\n /** The Angular Signal Form instance */\n form = this.stateManager.form;\n\n /** Current form values (reactive) */\n formValue = this.stateManager.formValue;\n\n /** Whether the form is currently valid */\n valid = this.stateManager.valid;\n\n /** Whether the form is currently invalid */\n invalid = this.stateManager.invalid;\n\n /** Whether any form field has been modified */\n dirty = this.stateManager.dirty;\n\n /** Whether any form field has been touched (blurred) */\n touched = this.stateManager.touched;\n\n /** Current validation errors from all fields */\n errors = this.stateManager.errors;\n\n /** Whether the form is disabled (from options or form state) */\n disabled = this.stateManager.disabled;\n\n /** Whether the form is currently submitting */\n submitting = this.stateManager.submitting;\n\n /** Collects errors from async field component loading for error boundary patterns */\n fieldLoadingErrors = this.stateManager.fieldLoadingErrors;\n\n /** Whether to render the form template */\n shouldRender = this.stateManager.shouldRender;\n\n /** Resolved fields ready for rendering */\n protected resolvedFields = this.stateManager.resolvedFields;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Computed Signals - Internal\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Recursively counts container components that will emit ComponentInitializedEvent.\n * Includes the dynamic-form component itself (+1).\n *\n * Recurses into all container children, including those nested inside array\n * item templates, to avoid a premature (initialized) emission.\n */\n private totalComponentsCount = computed(() => {\n const fields = this.stateManager.formSetup()?.fields ?? [];\n return countContainersRecursive(fields) + 1;\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Initialization\n // ─────────────────────────────────────────────────────────────────────────────\n\n initialized$ = setupInitializationTracking({\n eventBus: this.eventBus,\n totalComponentsCount: this.totalComponentsCount,\n injector: this.injector,\n componentId: this.componentId,\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Outputs\n // ─────────────────────────────────────────────────────────────────────────────\n\n /** Emits when form validity changes. */\n validityChange = outputFromObservable(toObservable(this.valid));\n\n /** Emits when form dirty state changes. */\n dirtyChange = outputFromObservable(toObservable(this.dirty));\n\n /**\n * Emits form values when submitted (via SubmitEvent) and form is valid.\n *\n * **Important:** This output only emits when the form is valid. If you need to\n * handle submit events regardless of validity, use the `(events)` output and\n * filter for `'submit'` events.\n *\n * Note: Does not emit when `submission.action` is configured - use one or the other.\n */\n submitted = outputFromObservable(this.stateManager.submitted$);\n\n /** Emits when form is reset to default values. */\n reset = outputFromObservable(this.eventBus.on<FormResetEvent>('form-reset'));\n\n /** Emits when form is cleared to empty state. */\n cleared = outputFromObservable(this.eventBus.on<FormClearEvent>('form-clear'));\n\n /** Emits all form events for custom event handling. */\n events = outputFromObservable(this.eventBus.events$);\n\n /**\n * Emits when all form components are initialized and ready for interaction.\n * Useful for E2E testing to ensure the form is fully rendered before interaction.\n */\n initialized = outputFromObservable(this.initialized$);\n\n /** Emits when the current page changes in paged forms. */\n onPageChange = outputFromObservable(this.eventBus.on<PageChangeEvent>('page-change'));\n\n /** Emits when page navigation state changes (canGoNext, canGoPrevious, etc.). */\n onPageNavigationStateChange = outputFromObservable(this.eventBus.on<PageNavigationStateChangeEvent>('page-navigation-state-change'));\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────────\n\n constructor() {\n this.dispatcher?.connect(this.eventBus);\n this.destroyRef.onDestroy(() => this.dispatcher?.disconnect());\n\n // Inject orchestrators eagerly so derivation streams are set up before the first\n // render cycle. Previously afterNextRender() deferred injection, causing\n // (initialized) to fire before derivations ran. The circular dependency that\n // originally motivated the deferral is resolved via dynamic-form-di.ts.\n this.injector.get(DERIVATION_ORCHESTRATOR);\n this.injector.get(PROPERTY_DERIVATION_ORCHESTRATOR);\n\n this.setupEffects();\n this.setupEventHandlers();\n }\n\n /**\n * Handles native form submission triggered by:\n * - Pressing Enter in an input field\n * - Clicking a button with type=\"submit\"\n * - Programmatic form.submit() calls\n *\n * This method prevents the default form submission behavior (page reload)\n * and dispatches a SubmitEvent through the EventBus for processing.\n *\n * @param event - The native submit event from the form element\n */\n protected onNativeSubmit(event: Event): void {\n event.preventDefault();\n this.eventBus.dispatch(SubmitEvent);\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n private setupEffects(): void {\n // Emit initialization event for paged forms\n explicitEffect([this.formModeDetection, this.pageFieldDefinitions], ([{ mode }, pages]) => {\n if (mode === 'paged' && pages.length > 0) {\n this.eventBus.dispatch(ComponentInitializedEvent, 'dynamic-form', this.componentId);\n }\n });\n\n // Emit initialization event for non-paged forms\n explicitEffect([this.resolvedFields, this.formModeDetection], ([fields, { mode }]) => {\n if (mode === 'non-paged' && fields.length > 0) {\n afterNextRender(\n () => {\n this.eventBus.dispatch(ComponentInitializedEvent, 'dynamic-form', this.componentId);\n },\n { injector: this.injector },\n );\n }\n });\n }\n\n /**\n * Populates FORM_STATE_DEPS with this component's input signals, then injects\n * FormStateManager. Must be called as a field initializer (after the input signals\n * are declared) so that FormStateManager reads populated deps when it is constructed.\n * inject() is valid here because field initializers run inside the injection context.\n */\n private connectDeps(): FormStateManager<TFields, TModel> {\n const deps = inject(FORM_STATE_DEPS);\n deps.config = this.config as Signal<FormConfig<RegisteredFieldTypes[]>>;\n deps.formOptions = this.formOptions;\n deps.value = this.value as WritableSignal<Partial<unknown> | undefined>;\n return inject(FormStateManager<TFields, TModel>);\n }\n\n private setupEventHandlers(): void {\n createSubmissionHandler<TFields, TModel>({\n eventBus: this.eventBus,\n configSignal: this.config,\n formSignal: this.form as Signal<FieldTree<TModel>>,\n validSignal: this.valid,\n logger: this.logger,\n })\n .pipe(takeUntilDestroyed(this.destroyRef))\n .subscribe({\n error: (err) => this.logger.error('Submission handler error', err),\n });\n }\n}\n\n/**\n * Recursively counts container fields (page, row, group, array, wrapper) in a field tree.\n * Descends into container children including array item templates to ensure\n * nested containers are counted for accurate initialization tracking.\n */\nfunction countContainersRecursive(fields: FieldDef<unknown>[]): number {\n let count = 0;\n for (const field of fields) {\n if (isContainerField(field)) {\n count += 1;\n if (hasChildFields(field)) {\n const children = field.fields;\n if (Array.isArray(children)) {\n for (const child of children) {\n if (Array.isArray(child)) {\n // Array item template: FieldDef[] (object items)\n count += countContainersRecursive(child as FieldDef<unknown>[]);\n } else if (child != null && isContainerField(child as FieldDef<unknown>)) {\n count += countContainersRecursive([child as FieldDef<unknown>]);\n }\n }\n }\n }\n }\n }\n return count;\n}\n","import { computed, Signal } from '@angular/core';\nimport { FieldTree } from '@angular/forms/signals';\nimport { FormOptions, NextButtonOptions, SubmitButtonOptions } from '../../models/form-config';\nimport { LogicConfig, FormStateCondition, isFormStateCondition } from '../../models/logic';\nimport { ConditionalExpression } from '../../models/expressions';\nimport { evaluateCondition } from '../expressions';\nimport type { Logger } from '../../providers/features/logger/logger.interface';\n\n/**\n * No-op logger for when no logger is provided.\n * Used as fallback in button logic evaluation to avoid breaking downstream packages.\n */\nconst noOpLogger: Logger = {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n debug: () => {},\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n info: () => {},\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n warn: () => {},\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n error: () => {},\n};\n\n/**\n * Context for resolving button disabled state.\n *\n * @public\n */\nexport interface ButtonLogicContext {\n /** The form's FieldTree instance (supports both string and number keys for array indices) */\n form: FieldTree<unknown, string | number>;\n\n /** Form-level options */\n formOptions?: FormOptions;\n\n /** Field-level logic array (if provided) */\n fieldLogic?: LogicConfig[];\n\n /** Explicit disabled state from field definition */\n explicitlyDisabled?: boolean;\n\n /** Current page validity signal (for paged forms) */\n currentPageValid?: Signal<boolean>;\n\n /** Current form value for evaluating conditional expressions */\n formValue?: unknown;\n\n /** Optional logger for diagnostic output. Falls back to no-op logger if not provided. */\n logger?: Logger;\n}\n\n/**\n * Allowed logic types for non-form-bound elements (buttons, text fields, etc.).\n * These elements only support hidden and disabled states - not readonly or required\n * since they don't participate in form validation.\n *\n * @public\n */\nexport type NonFieldLogicType = 'hidden' | 'disabled';\n\n/**\n * Logic config restricted to types valid for non-form-bound elements.\n * This is a subset of LogicConfig that only includes hidden and disabled types.\n *\n * @public\n */\nexport type NonFieldLogicConfig = LogicConfig & { type: NonFieldLogicType };\n\n/**\n * Context for resolving state (hidden/disabled) for non-form-bound elements.\n *\n * This is a generalized context that can be used by any field mapper (buttons, text fields,\n * or any non-form-bound elements) to evaluate logic from a `logic` array.\n *\n * Note: While this context accepts the full `LogicConfig[]` for flexibility, the resolver\n * functions only process hidden and disabled types. Other logic types (readonly, required,\n * derivation) are ignored for non-form-bound elements.\n *\n * @public\n */\nexport interface NonFieldLogicContext {\n /** The form's FieldTree instance (supports both string and number keys for array indices) */\n form: FieldTree<unknown, string | number>;\n\n /**\n * Field-level logic array containing conditions.\n * Accepts full LogicConfig[] for compatibility, but only hidden and disabled types are processed.\n */\n fieldLogic?: LogicConfig[];\n\n /** Explicit state from field definition (e.g., `hidden: true` or `disabled: true`) */\n explicitValue?: boolean;\n\n /** Current form value for evaluating conditional expressions */\n formValue?: unknown;\n\n /** Optional logger for diagnostic output. Falls back to no-op logger if not provided. */\n logger?: Logger;\n}\n\n/**\n * Default options for submit button disabled behavior.\n */\nconst DEFAULT_SUBMIT_BUTTON_OPTIONS: Required<SubmitButtonOptions> = {\n disableWhenInvalid: true,\n disableWhileSubmitting: true,\n};\n\n/**\n * Default options for next button disabled behavior.\n */\nconst DEFAULT_NEXT_BUTTON_OPTIONS: Required<NextButtonOptions> = {\n disableWhenPageInvalid: true,\n disableWhileSubmitting: true,\n};\n\n/**\n * Evaluates a FormStateCondition against the current form/page state.\n *\n * @param condition - The form state condition to evaluate\n * @param ctx - The button logic context\n * @returns true if the condition is met (button should be disabled)\n */\nfunction evaluateFormStateCondition(condition: FormStateCondition, ctx: ButtonLogicContext): boolean {\n const form = ctx.form();\n\n switch (condition) {\n case 'formInvalid':\n return !form.valid();\n\n case 'formSubmitting':\n return form.submitting();\n\n case 'pageInvalid':\n return ctx.currentPageValid ? !ctx.currentPageValid() : false;\n\n default:\n return false;\n }\n}\n\n/**\n * Evaluates a single logic condition (boolean, FormStateCondition, or ConditionalExpression).\n *\n * @param condition - The condition to evaluate\n * @param ctx - The button logic context\n * @returns true if the condition is met\n */\nfunction evaluateLogicCondition(condition: LogicConfig['condition'], ctx: ButtonLogicContext): boolean {\n // Boolean condition\n if (typeof condition === 'boolean') {\n return condition;\n }\n\n // FormStateCondition (string)\n if (isFormStateCondition(condition)) {\n return evaluateFormStateCondition(condition, ctx);\n }\n\n // ConditionalExpression\n const formValue = (ctx.formValue ?? ctx.form().value()) as Record<string, unknown>;\n const evaluationContext = {\n fieldValue: undefined,\n formValue,\n fieldPath: '',\n logger: ctx.logger ?? noOpLogger,\n };\n\n return evaluateCondition(condition as ConditionalExpression, evaluationContext);\n}\n\n/**\n * Checks if any disabled logic condition is met in the field's logic array.\n *\n * @param fieldLogic - Array of logic configurations\n * @param ctx - The button logic context\n * @returns true if any disabled condition is met\n */\nfunction hasFieldLevelDisabledCondition(fieldLogic: LogicConfig[] | undefined, ctx: ButtonLogicContext): boolean {\n if (!fieldLogic || fieldLogic.length === 0) {\n return false;\n }\n\n return fieldLogic.filter((logic) => logic.type === 'disabled').some((logic) => evaluateLogicCondition(logic.condition, ctx));\n}\n\n/**\n * Checks if the field has custom logic of a specific type.\n *\n * @param fieldLogic - Array of logic configurations\n * @param logicType - The type of logic to check for ('hidden', 'disabled', 'readonly', 'required')\n * @returns true if field has logic of the specified type\n */\nfunction hasCustomLogicOfType(fieldLogic: LogicConfig[] | undefined, logicType: LogicConfig['type']): boolean {\n if (!fieldLogic || fieldLogic.length === 0) {\n return false;\n }\n\n return fieldLogic.some((logic) => logic.type === logicType);\n}\n\n/**\n * Evaluates all logic conditions of a specific type and returns true if any condition is met.\n *\n * @param fieldLogic - Array of logic configurations\n * @param logicType - The type of logic to evaluate ('hidden', 'disabled', 'readonly', 'required')\n * @param ctx - Context containing form and formValue for evaluation\n * @returns true if any condition of the specified type is met\n */\nfunction evaluateLogicOfType(\n fieldLogic: LogicConfig[] | undefined,\n logicType: LogicConfig['type'],\n ctx: { form: FieldTree<unknown, string | number>; formValue?: unknown; logger?: Logger },\n): boolean {\n if (!fieldLogic || fieldLogic.length === 0) {\n return false;\n }\n\n const buttonCtx: ButtonLogicContext = {\n form: ctx.form,\n formValue: ctx.formValue,\n logger: ctx.logger,\n };\n\n return fieldLogic.filter((logic) => logic.type === logicType).some((logic) => evaluateLogicCondition(logic.condition, buttonCtx));\n}\n\n/**\n * Resolves the disabled state for a submit button.\n *\n * The disabled state is determined by (in order of precedence):\n * 1. Explicit `disabled: true` on the field definition\n * 2. Field-level `logic` array (if present, overrides form-level defaults)\n * 3. Form-level `options.submitButton` defaults\n *\n * @param ctx - The button logic context\n * @returns A computed signal that returns true when the button should be disabled\n *\n * @example\n * ```typescript\n * const disabled = resolveSubmitButtonDisabled({\n * form: formInstance,\n * formOptions: config.options,\n * fieldLogic: buttonField.logic,\n * explicitlyDisabled: buttonField.disabled,\n * });\n *\n * // Use in template\n * <button [disabled]=\"disabled()\">Submit</button>\n * ```\n *\n * @public\n */\nexport function resolveSubmitButtonDisabled(ctx: ButtonLogicContext): Signal<boolean> {\n return computed(() => {\n // 1. Explicit disabled always wins\n if (ctx.explicitlyDisabled) {\n return true;\n }\n\n // 2. If field has custom disabled logic, use it exclusively\n if (hasCustomLogicOfType(ctx.fieldLogic, 'disabled')) {\n return hasFieldLevelDisabledCondition(ctx.fieldLogic, ctx);\n }\n\n // 3. Apply form-level defaults\n const options = {\n ...DEFAULT_SUBMIT_BUTTON_OPTIONS,\n ...ctx.formOptions?.submitButton,\n };\n\n const form = ctx.form();\n\n if (options.disableWhenInvalid && !form.valid()) {\n return true;\n }\n\n if (options.disableWhileSubmitting && form.submitting()) {\n return true;\n }\n\n return false;\n });\n}\n\n/**\n * Resolves the disabled state for a next page button.\n *\n * The disabled state is determined by (in order of precedence):\n * 1. Explicit `disabled: true` on the field definition\n * 2. Field-level `logic` array (if present, overrides form-level defaults)\n * 3. Form-level `options.nextButton` defaults\n *\n * @param ctx - The button logic context\n * @returns A computed signal that returns true when the button should be disabled\n *\n * @example\n * ```typescript\n * const disabled = resolveNextButtonDisabled({\n * form: formInstance,\n * formOptions: config.options,\n * fieldLogic: buttonField.logic,\n * explicitlyDisabled: buttonField.disabled,\n * currentPageValid: pageOrchestrator.currentPageValid,\n * });\n * ```\n *\n * @public\n */\nexport function resolveNextButtonDisabled(ctx: ButtonLogicContext): Signal<boolean> {\n return computed(() => {\n // 1. Explicit disabled always wins\n if (ctx.explicitlyDisabled) {\n return true;\n }\n\n // 2. If field has custom disabled logic, use it exclusively\n if (hasCustomLogicOfType(ctx.fieldLogic, 'disabled')) {\n return hasFieldLevelDisabledCondition(ctx.fieldLogic, ctx);\n }\n\n // 3. Apply form-level defaults\n const options = {\n ...DEFAULT_NEXT_BUTTON_OPTIONS,\n ...ctx.formOptions?.nextButton,\n };\n\n const form = ctx.form();\n\n if (options.disableWhenPageInvalid && ctx.currentPageValid && !ctx.currentPageValid()) {\n return true;\n }\n\n if (options.disableWhileSubmitting && form.submitting()) {\n return true;\n }\n\n return false;\n });\n}\n\n/**\n * Evaluates the hidden state for non-form-bound elements synchronously.\n *\n * This is a pure function (no signal allocation) that can be called directly inside\n * an existing `computed()` block without creating ephemeral signal allocations.\n *\n * The hidden state is determined by (in order of precedence):\n * 1. Explicit `hidden: true` on the field definition\n * 2. Field-level `logic` array with `type: 'hidden'` conditions\n *\n * @param ctx - The context containing form, logic array, and explicit hidden state\n * @returns true when the element should be hidden\n *\n * @public\n */\nexport function evaluateNonFieldHidden(ctx: NonFieldLogicContext): boolean {\n // 1. Explicit hidden always wins\n if (ctx.explicitValue) {\n return true;\n }\n\n // 2. Evaluate hidden logic conditions\n if (hasCustomLogicOfType(ctx.fieldLogic, 'hidden')) {\n return evaluateLogicOfType(ctx.fieldLogic, 'hidden', {\n form: ctx.form,\n formValue: ctx.formValue,\n logger: ctx.logger,\n });\n }\n\n // 3. No hidden conditions - element is visible\n return false;\n}\n\n/**\n * Resolves the hidden state for non-form-bound elements as a reactive signal.\n *\n * Wraps {@link evaluateNonFieldHidden} in a `computed()` for use cases where a standalone\n * signal is needed. When calling from inside an existing `computed()`, prefer\n * {@link evaluateNonFieldHidden} directly to avoid ephemeral signal allocation.\n *\n * @param ctx - The context containing form, logic array, and explicit hidden state\n * @returns A computed signal that returns true when the element should be hidden\n *\n * @public\n */\nexport function resolveNonFieldHidden(ctx: NonFieldLogicContext): Signal<boolean> {\n return computed(() => evaluateNonFieldHidden(ctx));\n}\n\n/**\n * Evaluates the disabled state for non-form-bound elements synchronously.\n *\n * This is a pure function (no signal allocation) that can be called directly inside\n * an existing `computed()` block without creating ephemeral signal allocations.\n *\n * The disabled state is determined by (in order of precedence):\n * 1. Explicit `disabled: true` on the field definition\n * 2. Field-level `logic` array with `type: 'disabled'` conditions\n *\n * @param ctx - The context containing form, logic array, and explicit disabled state\n * @returns true when the element should be disabled\n *\n * @public\n */\nexport function evaluateNonFieldDisabled(ctx: NonFieldLogicContext): boolean {\n // 1. Explicit disabled always wins\n if (ctx.explicitValue) {\n return true;\n }\n\n // 2. Evaluate disabled logic conditions\n if (hasCustomLogicOfType(ctx.fieldLogic, 'disabled')) {\n return evaluateLogicOfType(ctx.fieldLogic, 'disabled', {\n form: ctx.form,\n formValue: ctx.formValue,\n logger: ctx.logger,\n });\n }\n\n // 3. No disabled conditions - element is enabled\n return false;\n}\n\n/**\n * Resolves the disabled state for non-form-bound elements as a reactive signal.\n *\n * Wraps {@link evaluateNonFieldDisabled} in a `computed()` for use cases where a standalone\n * signal is needed. When calling from inside an existing `computed()`, prefer\n * {@link evaluateNonFieldDisabled} directly to avoid ephemeral signal allocation.\n *\n * @param ctx - The context containing form, logic array, and explicit disabled state\n * @returns A computed signal that returns true when the element should be disabled\n *\n * @public\n */\nexport function resolveNonFieldDisabled(ctx: NonFieldLogicContext): Signal<boolean> {\n return computed(() => evaluateNonFieldDisabled(ctx));\n}\n","import { RootFormRegistryService } from '../core/registry/root-form-registry.service';\nimport { evaluateNonFieldHidden } from '../core/logic/non-field-logic-resolver';\nimport { ContainerLogicConfig } from '../definitions/base/container-logic-config';\nimport { LogicConfig } from '../models/logic';\n\ninterface FieldWithHiddenLogic {\n hidden?: boolean;\n logic?: readonly (ContainerLogicConfig | LogicConfig)[];\n}\n\n/**\n * Applies hidden logic to a mapper's input record.\n *\n * Evaluates the field's `hidden` property and `logic` array to determine\n * if the component should be hidden. Only runs evaluation when there's\n * actually something to evaluate (explicit `hidden: true` or logic with type 'hidden').\n *\n * @param inputs The mutable input record to potentially add `hidden` to\n * @param fieldDef The field definition containing `hidden` and `logic`\n * @param rootFormRegistry The root form registry for accessing form state\n */\nexport function applyHiddenLogic(\n inputs: Record<string, unknown>,\n fieldDef: FieldWithHiddenLogic,\n rootFormRegistry: RootFormRegistryService,\n): void {\n const rootForm = rootFormRegistry.rootForm();\n if (rootForm && (fieldDef.hidden === true || fieldDef.logic?.some((l) => l.type === 'hidden'))) {\n // Cast is safe: evaluateNonFieldHidden only reads the array, never mutates it.\n // The readonly + union type from container/leaf field definitions is compatible at runtime.\n inputs['hidden'] = evaluateNonFieldHidden({\n form: rootForm,\n fieldLogic: fieldDef.logic as LogicConfig[] | undefined,\n explicitValue: fieldDef.hidden,\n formValue: rootFormRegistry.formValue(),\n });\n }\n}\n","import { computed, inject, Signal } from '@angular/core';\nimport { ArrayField } from '../../definitions/default/array-field';\nimport { buildClassName } from '../../utils/grid-classes/grid-classes';\nimport { RootFormRegistryService } from '../../core/registry/root-form-registry.service';\nimport { applyHiddenLogic } from '../apply-hidden-logic';\n\n/**\n * Maps an array field definition to component inputs.\n *\n * Array components create nested form structures under the array's key.\n * The array component will inject the parent FIELD_SIGNAL_CONTEXT and create\n * a scoped child injector for its array item fields.\n *\n * Supports hidden state resolution via `logic` array or static `hidden` property.\n *\n * @param fieldDef The array field definition\n * @returns Signal containing Record of input names to values for ngComponentOutlet\n */\nexport function arrayFieldMapper(fieldDef: ArrayField): Signal<Record<string, unknown>> {\n const rootFormRegistry = inject(RootFormRegistryService);\n const className = buildClassName(fieldDef);\n\n return computed(() => {\n const inputs: Record<string, unknown> = {\n key: fieldDef.key,\n field: fieldDef,\n ...(className !== undefined && { className }),\n };\n\n applyHiddenLogic(inputs, fieldDef, rootFormRegistry);\n\n return inputs;\n });\n}\n","import { computed, inject, Signal } from '@angular/core';\nimport { GroupField } from '../../definitions/default/group-field';\nimport { buildClassName } from '../../utils/grid-classes/grid-classes';\nimport { RootFormRegistryService } from '../../core/registry/root-form-registry.service';\nimport { applyHiddenLogic } from '../apply-hidden-logic';\n\n/**\n * Maps a group field definition to component inputs.\n *\n * Group components create nested form structures under the group's key.\n * The group component will inject the parent FIELD_SIGNAL_CONTEXT and create\n * a scoped child injector for its nested fields.\n *\n * Supports hidden state resolution via `logic` array or static `hidden` property.\n *\n * @param fieldDef The group field definition\n * @returns Signal containing Record of input names to values for ngComponentOutlet\n */\nexport function groupFieldMapper(fieldDef: GroupField): Signal<Record<string, unknown>> {\n const rootFormRegistry = inject(RootFormRegistryService);\n const className = buildClassName(fieldDef);\n\n return computed(() => {\n const inputs: Record<string, unknown> = {\n key: fieldDef.key,\n field: fieldDef,\n ...(className !== undefined && { className }),\n };\n\n applyHiddenLogic(inputs, fieldDef, rootFormRegistry);\n\n return inputs;\n });\n}\n","import { computed, inject, Signal } from '@angular/core';\nimport { RowField } from '../../definitions/default/row-field';\nimport { buildClassName } from '../../utils/grid-classes/grid-classes';\nimport { RootFormRegistryService } from '../../core/registry/root-form-registry.service';\nimport { applyHiddenLogic } from '../apply-hidden-logic';\n\nconst ROW_WRAPPERS = [{ type: 'row' }] as const;\n\n/**\n * Maps a row field definition to container component inputs.\n *\n * `row` is a virtual field type: it resolves to `ContainerFieldComponent` with a\n * synthesized `{ type: 'row' }` wrapper, so the user-facing config stays\n * `{ type: 'row', fields: [...] }` while the runtime uses the container +\n * wrapper pipeline.\n *\n * Supports hidden state resolution via `logic` array or static `hidden` property.\n */\nexport function rowFieldMapper(fieldDef: RowField): Signal<Record<string, unknown>> {\n const rootFormRegistry = inject(RootFormRegistryService);\n const className = buildClassName(fieldDef);\n\n return computed(() => {\n // Rebuilt each emission so logic-driven updates to fieldDef (e.g. `disabled`)\n // flow through. Shallow spread is safe while RowField has no nested\n // mutable props; add a deep-clone if that stops being true.\n const containerField = { ...fieldDef, wrappers: ROW_WRAPPERS };\n\n const inputs: Record<string, unknown> = {\n key: fieldDef.key,\n field: containerField,\n ...(className !== undefined && { className }),\n };\n\n applyHiddenLogic(inputs, fieldDef, rootFormRegistry);\n\n return inputs;\n });\n}\n","import { computed, Signal } from '@angular/core';\nimport { PageField } from '../../definitions/default/page-field';\nimport { buildClassName } from '../../utils/grid-classes/grid-classes';\n\n/**\n * Maps a page field definition to component inputs.\n *\n * Page fields are layout containers that don't modify the form context.\n * The page component will inject FIELD_SIGNAL_CONTEXT directly.\n *\n * Note: Unlike other container mappers (group, row, array), the page mapper does NOT\n * resolve hidden logic here. Page visibility is managed by the {@link PageOrchestratorComponent}\n * which evaluates `ContainerLogicConfig` conditions and controls the `isVisible` input.\n *\n * @param fieldDef The page field definition\n * @returns Signal containing Record of input names to values for ngComponentOutlet\n */\nexport function pageFieldMapper(fieldDef: PageField): Signal<Record<string, unknown>> {\n const className = buildClassName(fieldDef);\n\n // Page inputs are static (no reactive dependencies)\n return computed(() => ({\n key: fieldDef.key,\n field: fieldDef,\n ...(className !== undefined && { className }),\n }));\n}\n","import { computed, inject, Signal } from '@angular/core';\nimport { TextField } from '../../definitions/default/text-field';\nimport { buildBaseInputs } from '../base/base-field-mapper';\nimport { DEFAULT_PROPS } from '../../models/field-signal-context.token';\nimport { RootFormRegistryService } from '../../core/registry/root-form-registry.service';\nimport { applyHiddenLogic } from '../apply-hidden-logic';\n\n/**\n * Maps a text field definition to component inputs.\n *\n * Text fields are display-only fields that don't participate in the form schema.\n * This mapper handles the `logic` configuration by using the non-field-hidden resolver\n * to evaluate conditions against the form value from RootFormRegistryService.\n *\n * Hidden state is resolved using the non-field-hidden resolver which considers:\n * 1. Explicit `hidden: true` on the field definition\n * 2. Field-level `logic` array with `type: 'hidden'` conditions\n *\n * Note: Text fields don't support disabled logic since they are display-only.\n *\n * @param fieldDef The text field definition\n * @returns Signal containing Record of input names to values for ngComponentOutlet\n */\nexport function textFieldMapper(fieldDef: TextField): Signal<Record<string, unknown>> {\n const rootFormRegistry = inject(RootFormRegistryService);\n const defaultProps = inject(DEFAULT_PROPS);\n\n // Return computed signal for reactive updates\n return computed(() => {\n const baseInputs = buildBaseInputs(fieldDef, defaultProps());\n const inputs: Record<string, unknown> = { ...baseInputs };\n\n applyHiddenLogic(inputs, fieldDef, rootFormRegistry);\n\n return inputs;\n });\n}\n","import { computed, inject, Signal } from '@angular/core';\nimport { ContainerField } from '../../definitions/default/container-field';\nimport { buildClassName } from '../../utils/grid-classes/grid-classes';\nimport { RootFormRegistryService } from '../../core/registry/root-form-registry.service';\nimport { applyHiddenLogic } from '../apply-hidden-logic';\n\n/**\n * Maps a container field definition to component inputs.\n *\n * Container components are layout containers that don't change the form shape.\n * The container component will inject FIELD_SIGNAL_CONTEXT directly.\n *\n * Supports hidden state resolution via `logic` array or static `hidden` property.\n *\n * @param fieldDef The container field definition\n * @returns Signal containing Record of input names to values for ngComponentOutlet\n */\nexport function containerFieldMapper(fieldDef: ContainerField): Signal<Record<string, unknown>> {\n const rootFormRegistry = inject(RootFormRegistryService);\n const className = buildClassName(fieldDef);\n\n return computed(() => {\n // Nullify wrapper-related props on the field passed to the container\n // component — DfFieldOutlet handles field-level wrappers at the outlet\n // level. Passing them here would cause double-wrapping since the\n // container's internal wrapper chain also resolves from `this.field()`.\n // We set wrappers to undefined (not stripped) so the object identity\n // stays close to the original fieldDef shape.\n const containerField = { ...fieldDef, wrappers: undefined, skipAutoWrappers: undefined, skipDefaultWrappers: undefined };\n\n const inputs: Record<string, unknown> = {\n key: fieldDef.key,\n field: containerField,\n ...(className !== undefined && { className }),\n };\n\n applyHiddenLogic(inputs, fieldDef, rootFormRegistry);\n\n return inputs;\n });\n}\n","import { FieldTypeDefinition } from '../models/field-type';\nimport { arrayFieldMapper } from '../mappers/array/array-field-mapper';\nimport { groupFieldMapper } from '../mappers/group/group-field-mapper';\nimport { rowFieldMapper } from '../mappers/row/row-field-mapper';\nimport { pageFieldMapper } from '../mappers/page/page-field-mapper';\nimport { textFieldMapper } from '../mappers/text/text-field-mapper';\nimport { containerFieldMapper } from '../mappers/container/container-field-mapper';\nimport { RowField } from '../definitions/default/row-field';\nimport { GroupField } from '../definitions/default/group-field';\nimport { HiddenField } from '../definitions/default/hidden-field';\nimport { ArrayField } from '../definitions/default/array-field';\nimport { PageField } from '../definitions/default/page-field';\nimport { TextField } from '../definitions/default/text-field';\nimport { ContainerField } from '../definitions/default/container-field';\nimport { WrapperTypeDefinition } from '../models';\nimport { CssWrapper, RowWrapper } from '../definitions/default';\n\n/**\n * Built-in field types provided by the dynamic form library.\n *\n * These core field types handle form structure and layout. They are automatically\n * registered when using provideDynamicForm() and form the foundation for building\n * complex form layouts with nested fields and multi-step flows.\n *\n * @example\n * ```typescript\n * // Row field for horizontal layout\n * { type: 'row', fields: [\n * { type: 'input', key: 'firstName' },\n * { type: 'input', key: 'lastName' }\n * ]}\n *\n * // Group field for nested form sections\n * { type: 'group', key: 'address', fields: [\n * { type: 'input', key: 'street' },\n * { type: 'input', key: 'city' }\n * ]}\n *\n * // Array field for array-based form sections\n * { type: 'array', key: 'items', fields: [\n * { type: 'input', key: 'name' },\n * { type: 'input', key: 'quantity' }\n * ]}\n *\n * // Page field for multi-step forms\n * { type: 'page', key: 'step1', fields: [...] }\n * ```\n */\n/**\n * Base field type definitions for fields that don't use the `field` input.\n * Used by display-only fields like `text` that render immediately without\n * waiting for form value integration.\n */\nconst DISPLAY_FIELD_TYPES_BASE = {\n renderReadyWhen: [] as string[],\n};\n\n/**\n * Built-in field types provided by the dynamic form library.\n *\n * Each field type is validated at compile time using satisfies, ensuring\n * type safety of the mapper function while allowing the array to be typed\n * as FieldTypeDefinition[] for consumer flexibility.\n */\nexport const BUILT_IN_FIELDS: FieldTypeDefinition[] = [\n {\n name: 'row',\n // `row` is a virtual field type: it maps to ContainerFieldComponent, and\n // the rowFieldMapper injects a `{ type: 'row' }` wrapper so the container\n // renders the flex/grid layout via RowWrapperComponent.\n loadComponent: () => import('../fields/container/container-field.component'),\n mapper: rowFieldMapper,\n valueHandling: 'flatten',\n } satisfies FieldTypeDefinition<RowField>,\n {\n name: 'group',\n loadComponent: () => import('../fields/group/group-field.component'),\n mapper: groupFieldMapper,\n valueHandling: 'include',\n } satisfies FieldTypeDefinition<GroupField>,\n {\n name: 'array',\n loadComponent: () => import('../fields/array/array-field.component'),\n mapper: arrayFieldMapper,\n valueHandling: 'include',\n } satisfies FieldTypeDefinition<ArrayField>,\n {\n name: 'page',\n loadComponent: () => import('../fields/page/page-field.component'),\n mapper: pageFieldMapper,\n valueHandling: 'flatten',\n } satisfies FieldTypeDefinition<PageField>,\n {\n name: 'text',\n loadComponent: () => import('../fields/text/text-field.component'),\n mapper: textFieldMapper,\n valueHandling: 'exclude',\n ...DISPLAY_FIELD_TYPES_BASE,\n } satisfies FieldTypeDefinition<TextField>,\n {\n name: 'hidden',\n // Componentless field - no loadComponent or mapper needed\n valueHandling: 'include',\n } satisfies FieldTypeDefinition<HiddenField>,\n {\n name: 'container',\n loadComponent: () => import('../fields/container/container-field.component'),\n mapper: containerFieldMapper,\n valueHandling: 'flatten',\n } satisfies FieldTypeDefinition<ContainerField>,\n];\n\nexport const BUILT_IN_WRAPPERS: WrapperTypeDefinition[] = [\n {\n wrapperName: 'css',\n loadComponent: () => import('../wrappers/css/css-wrapper.component'),\n } satisfies WrapperTypeDefinition<CssWrapper>,\n {\n wrapperName: 'row',\n loadComponent: () => import('../wrappers/row/row-wrapper.component'),\n } satisfies WrapperTypeDefinition<RowWrapper>,\n];\n","import { LazyComponentLoader, WrapperTypeDefinition } from '../models/wrapper-type';\n\n/**\n * User-facing wrapper registration shape used with `createWrappers(...)`.\n *\n * Extends `WrapperTypeDefinition` with an optional `props` field that\n * carries the wrapper's config type (via `wrapperProps`) for later\n * inference by `InferWrapperRegistry`.\n */\nexport interface WrapperRegistration<TName extends string = string, TConfig = unknown> {\n /** Unique identifier for the wrapper type */\n readonly wrapperName: TName;\n /** Lazy-loader for the wrapper component */\n readonly loadComponent: LazyComponentLoader;\n /** Field types this wrapper auto-applies to (merged lowest-priority during wrapper resolution) */\n readonly types?: readonly string[];\n /**\n * Type carrier only — runtime value is always `undefined`.\n * Use `wrapperProps<YourConfig>()` to thread the config type.\n */\n readonly props?: TConfig;\n}\n\n/**\n * Branded bundle returned by `createWrappers(...)`.\n *\n * Carries:\n * - `ɵkind: 'wrappers'` — discriminant recognised by `provideDynamicForm(...)`\n * - `ɵregistrations` — the original registrations (type-level use for `InferWrapperRegistry`)\n * - `ɵdefinitions` — the `WrapperTypeDefinition[]` extracted for `WRAPPER_REGISTRY`\n */\nexport interface WrappersBundle<T extends readonly WrapperRegistration[] = readonly WrapperRegistration[]> {\n readonly ɵkind: 'wrappers';\n readonly ɵregistrations: T;\n readonly ɵdefinitions: readonly WrapperTypeDefinition[];\n}\n\n/**\n * Bundle wrapper registrations into a single object that can be passed to\n * `provideDynamicForm(...)`.\n *\n * @example\n * ```typescript\n * const appWrappers = createWrappers(\n * {\n * wrapperName: 'section',\n * loadComponent: () => import('./section-wrapper'),\n * props: wrapperProps<SectionWrapper>(),\n * },\n * {\n * wrapperName: 'highlight',\n * loadComponent: () => import('./highlight-wrapper'),\n * types: ['input', 'select'],\n * props: wrapperProps<HighlightWrapper>(),\n * },\n * );\n *\n * declare module '@ng-forge/dynamic-forms' {\n * interface FieldRegistryWrappers extends InferWrapperRegistry<typeof appWrappers> {}\n * }\n *\n * bootstrapApplication(AppComponent, {\n * providers: [provideDynamicForm(appWrappers)],\n * });\n * ```\n */\nexport function createWrappers<const T extends readonly WrapperRegistration[]>(...registrations: T): WrappersBundle<T> {\n return {\n ɵkind: 'wrappers',\n ɵregistrations: registrations,\n ɵdefinitions: registrations.map(({ wrapperName, loadComponent, types }) => ({\n wrapperName,\n loadComponent,\n types,\n })),\n };\n}\n\n/** Type guard for a `WrappersBundle`. */\nexport function isWrappersBundle(value: unknown): value is WrappersBundle {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'ɵkind' in value &&\n (value as { ɵkind: unknown }).ɵkind === 'wrappers' &&\n 'ɵdefinitions' in value &&\n Array.isArray((value as { ɵdefinitions: unknown }).ɵdefinitions)\n );\n}\n\n/**\n * Derive the `FieldRegistryWrappers` augmentation shape from a wrapper bundle.\n *\n * Maps each registration's `wrapperName` to its `props` type (the config carried\n * by `wrapperProps<T>()`). If a registration has no `props`, falls back to the\n * minimal discriminant shape `{ readonly type: wrapperName }`.\n *\n * @example\n * ```typescript\n * declare module '@ng-forge/dynamic-forms' {\n * interface FieldRegistryWrappers extends InferWrapperRegistry<typeof appWrappers> {}\n * }\n * ```\n */\nexport type InferWrapperRegistry<T> =\n T extends WrappersBundle<infer R>\n ? {\n [Reg in R[number] as Reg['wrapperName']]: Reg extends { props: infer P }\n ? Exclude<P, undefined>\n : { readonly type: Reg['wrapperName'] };\n }\n : never;\n","import { EnvironmentProviders, inject, makeEnvironmentProviders, Provider } from '@angular/core';\nimport { provideSignalFormsConfig } from '@angular/forms/signals';\nimport { NG_STATUS_CLASSES } from '@angular/forms/signals/compat';\nimport { FIELD_REGISTRY, FieldTypeDefinition } from '../models/field-type';\nimport { BUILT_IN_FIELDS, BUILT_IN_WRAPPERS } from './built-in-fields';\nimport { FieldDef } from '../definitions/base/field-def';\nimport { DynamicFormFeature, isDynamicFormFeature } from './features/dynamic-form-feature';\nimport { DynamicFormLogger } from './features/logger/logger.token';\nimport { ConsoleLogger } from './features/logger/console-logger';\nimport type { InferFormValue as RealInferFormValue } from '../models/types/form-value-inference';\nimport { isWrapperTypeDefinition, WrapperTypeDefinition, WRAPPER_AUTO_ASSOCIATIONS, WRAPPER_REGISTRY, WrapperConfig } from '../models';\nimport { isWrappersBundle, WrappersBundle } from '../wrappers/create-wrappers';\n\n// Re-export global types for module augmentation\nexport type { DynamicFormFieldRegistry, AvailableFieldTypes } from '../models/registry';\nexport type { RegisteredFieldTypes } from '../models/types';\n\n/**\n * Extract FieldDef type from FieldTypeDefinition\n */\ntype ExtractFieldDef<T> = T extends FieldTypeDefinition<infer F> ? F : never;\n\n/**\n * Union of all FieldDef types from provided field types\n */\ntype FieldDefUnion<T extends FieldTypeDefinition[]> = ExtractFieldDef<T[number]>;\n\n/**\n * Infer form value type from field definitions using the real inference type.\n */\ntype InferFormValue<TFieldDefs extends FieldDef<unknown>[]> = RealInferFormValue<TFieldDefs>;\n\n/**\n * Provider result with type inference\n */\ntype ProvideDynamicFormResult<T extends FieldTypeDefinition[]> = EnvironmentProviders & {\n __fieldDefs?: FieldDefUnion<T>;\n __formValue?: InferFormValue<FieldDefUnion<T>[]>;\n};\n\n/**\n * Union type for items that can be passed to provideDynamicForm\n */\ntype FieldTypeOrFeature = FieldTypeDefinition | WrapperTypeDefinition | WrappersBundle | DynamicFormFeature;\n\n/**\n * Extract only FieldTypeDefinition items from a tuple type\n */\ntype ExtractFieldTypes<T extends FieldTypeOrFeature[]> = {\n [K in keyof T]: T[K] extends FieldTypeDefinition ? T[K] : never;\n}[number] extends infer U\n ? U extends FieldTypeDefinition\n ? U[]\n : never\n : never;\n\n/**\n * Provider function to configure the dynamic form system with field types and options.\n *\n * This function creates environment providers that can be used at application or route level\n * to register field types. It provides type-safe field registration with automatic type inference.\n *\n * @param items - Field type definitions and/or features (like withLoggerConfig)\n * @returns Environment providers for dependency injection with type inference\n *\n * @example\n * ```typescript\n * // Application-level setup\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideDynamicForm(...withMaterialFields())\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Disable logging\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withLoggerConfig(false)\n * )\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Custom field types with type inference\n * import { CustomFieldType, AnotherFieldType } from './custom-fields';\n *\n * export const appConfig: ApplicationConfig = {\n * providers: [\n * provideDynamicForm(CustomFieldType, AnotherFieldType)\n * ]\n * };\n * ```\n *\n * @typeParam T - Array of field type definitions for type inference\n *\n * @public\n */\nexport function provideDynamicForm<const T extends FieldTypeOrFeature[]>(\n ...items: T\n): ProvideDynamicFormResult<ExtractFieldTypes<T> extends FieldTypeDefinition[] ? ExtractFieldTypes<T> : FieldTypeDefinition[]> {\n // Separate field types, wrapper types, wrapper bundles, and features\n const fieldTypes = items.filter(\n (item): item is FieldTypeDefinition => !isDynamicFormFeature(item) && !isWrapperTypeDefinition(item) && !isWrappersBundle(item),\n );\n const wrapperTypes = items.filter(isWrapperTypeDefinition);\n const wrapperBundles = items.filter(isWrappersBundle);\n const features = items.filter(isDynamicFormFeature);\n\n const fields = [...BUILT_IN_FIELDS, ...fieldTypes];\n const wrappers = [...BUILT_IN_WRAPPERS, ...wrapperTypes, ...wrapperBundles.flatMap((bundle) => bundle.ɵdefinitions)];\n\n // Extract providers from features (includes config features like material-config, bootstrap-config, etc.)\n const featureProviders: Provider[] = [];\n const hasLoggerFeature = features.some((feature) => feature.ɵkind === 'logger');\n features.forEach((feature) => {\n featureProviders.push(...feature.ɵproviders);\n });\n\n // Default logger provider (ConsoleLogger) if no logger feature was provided\n const defaultLoggerProvider: Provider[] = hasLoggerFeature ? [] : [{ provide: DynamicFormLogger, useValue: new ConsoleLogger() }];\n\n return makeEnvironmentProviders([\n ...defaultLoggerProvider,\n // Always provide default Signal Forms classes (ng-touched, ng-invalid, etc.)\n provideSignalFormsConfig({ classes: NG_STATUS_CLASSES }),\n {\n provide: FIELD_REGISTRY,\n useFactory: () => {\n const logger = inject(DynamicFormLogger);\n const registry = new Map();\n // Add custom field types\n fields.forEach((fieldType) => {\n if (registry.has(fieldType.name)) {\n logger.warn(`Field type \"${fieldType.name}\" is already registered. Overwriting.`);\n }\n registry.set(fieldType.name, fieldType);\n });\n return registry;\n },\n },\n // Always provide default Wrapper classes\n {\n provide: WRAPPER_REGISTRY,\n useFactory: () => {\n const logger = inject(DynamicFormLogger);\n const registry = new Map();\n // Add custom wrapper types\n wrappers.forEach((wrapperType) => {\n if (registry.has(wrapperType.wrapperName)) {\n logger.warn(`Wrapper type \"${wrapperType.wrapperName}\" is already registered. Overwriting.`);\n }\n registry.set(wrapperType.wrapperName, wrapperType);\n });\n return registry;\n },\n },\n // Pre-computed reverse index for auto-association lookup — built once so\n // resolveWrappers is O(1) per field render instead of scanning every\n // registered wrapper.\n {\n provide: WRAPPER_AUTO_ASSOCIATIONS,\n useFactory: () => {\n const autoMap = new Map<string, WrapperConfig[]>();\n for (const wrapperType of wrappers) {\n if (!wrapperType.types) continue;\n for (const fieldType of wrapperType.types) {\n const existing = autoMap.get(fieldType) ?? [];\n existing.push({ type: wrapperType.wrapperName } as WrapperConfig);\n autoMap.set(fieldType, existing);\n }\n }\n return autoMap;\n },\n },\n ...featureProviders,\n ]) as ProvideDynamicFormResult<ExtractFieldTypes<T> extends FieldTypeDefinition[] ? ExtractFieldTypes<T> : FieldTypeDefinition[]>;\n}\n\n/**\n * Extract FieldDef types from provider result\n */\nexport type ExtractFieldDefs<T> = T extends { __fieldDefs?: infer F } ? F : never;\n\n/**\n * Extract form value type from provider result\n */\nexport type ExtractFormValue<T> = T extends { __formValue?: infer V } ? V : never;\n","import { createFeature, DynamicFormFeature } from '../dynamic-form-feature';\nimport { EMIT_FORM_VALUE_ON_EVENTS } from './emit-form-value.token';\n\n/**\n * Enables automatic form value attachment to all events dispatched through the EventBus.\n *\n * When this feature is enabled, events dispatched via `eventBus.dispatch()` will include\n * the current form value in the `formValue` property. This is useful for event handlers\n * that need access to the complete form state at the time of the event.\n *\n * @example Global opt-in\n * ```typescript\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withEventFormValue()\n * )\n * ```\n *\n * @example Consumer usage\n * ```typescript\n * eventBus.on<SubmitEvent>('submit').subscribe(event => {\n * if (hasFormValue(event)) {\n * console.log('Form value:', event.formValue);\n * }\n * });\n * ```\n *\n * @example Per-form disable (when globally enabled)\n * ```typescript\n * const config: FormConfig = {\n * fields: [...],\n * options: { emitFormValueOnEvents: false }\n * };\n * ```\n *\n * @remarks\n * **Precedence rules:**\n * 1. Per-form `false` - Disables for this form, regardless of global setting\n * 2. Per-form `true` - Enables for this form, regardless of global setting\n * 3. Per-form `undefined` - Uses global setting\n * 4. Global `withEventFormValue()` - Enables globally\n * 5. No global feature - Disabled globally (default)\n *\n * @returns A DynamicFormFeature that enables form value attachment to events\n *\n * @public\n */\nexport function withEventFormValue(): DynamicFormFeature<'event-form-value'> {\n return createFeature('event-form-value', [{ provide: EMIT_FORM_VALUE_ON_EVENTS, useValue: true }]);\n}\n","/**\n * Base interface for all form events in the dynamic form system.\n *\n * All form events must implement this interface to be compatible with\n * the event bus system. The type property is used for event filtering\n * and type-safe subscriptions.\n *\n * @example\n * ```typescript\n * export class SubmitEvent implements FormEvent {\n * readonly type = 'submit';\n * }\n *\n * export class ValidationErrorEvent implements FormEvent {\n * readonly type = 'validation-error';\n * constructor(public errors: ValidationErrors) {}\n * }\n * ```\n */\nexport interface FormEvent {\n /** Unique identifier for the event type used for filtering and subscriptions */\n readonly type: string;\n /**\n * Optional form value attached to the event when `withEventFormValue()` is enabled\n * or `options.emitFormValueOnEvents` is set to `true` in the form config.\n *\n * Use the `hasFormValue()` type guard to check if this property is present.\n */\n readonly formValue?: unknown;\n}\n\n/**\n * Type guard to check if a form event has a form value attached.\n *\n * Use this to safely access the `formValue` property on events when\n * `withEventFormValue()` is enabled globally or `options.emitFormValueOnEvents`\n * is set to `true` in the form config.\n *\n * @example\n * ```typescript\n * eventBus.on<SubmitEvent>('submit').subscribe(event => {\n * if (hasFormValue(event)) {\n * console.log('Form value:', event.formValue);\n * }\n * });\n * ```\n *\n * @param event - The form event to check\n * @returns `true` if the event has a form value attached, narrowing the type\n *\n * @public\n */\nexport function hasFormValue<T extends FormEvent>(event: T): event is T & { formValue: unknown } {\n return 'formValue' in event && event.formValue !== undefined;\n}\n\n/**\n * Constructor type for form event classes.\n *\n * Defines the shape of event class constructors that can be used with\n * the event bus dispatch system. Supports both parameterless and\n * parameterized event constructors.\n *\n * @typeParam T - The form event type being constructed\n *\n * @example\n * ```typescript\n * // Parameterless event constructor\n * const SubmitEventCtor: FormEventConstructor<SubmitEvent> = SubmitEvent;\n *\n * // Parameterized event constructor\n * const ErrorEventCtor: FormEventConstructor<ErrorEvent> = ErrorEvent;\n * eventBus.dispatch(ErrorEventCtor);\n * ```\n */\n// TypeScript limitation: Constructor types with varying parameter signatures require `any[]`\n// because `unknown[]` cannot be assigned from more specific parameter types (contravariance).\n// Using a generic TArgs parameter here would require changes throughout the event system.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type FormEventConstructor<T extends FormEvent = FormEvent> = new (...args: any[]) => T;\n","import { ValueExclusionConfig } from '../../../models/value-exclusion-config';\nimport { createFeature, DynamicFormFeature } from '../dynamic-form-feature';\nimport { VALUE_EXCLUSION_DEFAULTS } from './value-exclusion.token';\n\n/**\n * Configures global value exclusion defaults for form submission output.\n *\n * Value exclusion is **enabled by default** — field values are excluded from the\n * `(submitted)` output based on their reactive state. Use this feature to\n * override those defaults. This does NOT affect two-way binding (`value` model /\n * `entity`) — fields retain their values internally.\n *\n * @example Default behavior (all exclusions enabled)\n * ```typescript\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withValueExclusionDefaults()\n * )\n * ```\n *\n * @example Disable specific exclusions\n * ```typescript\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withValueExclusionDefaults({ excludeValueIfReadonly: false })\n * )\n * ```\n *\n * @example Disable all exclusions (restore pre-v1 behavior)\n * ```typescript\n * provideDynamicForm(\n * ...withMaterialFields(),\n * withValueExclusionDefaults({\n * excludeValueIfHidden: false,\n * excludeValueIfDisabled: false,\n * excludeValueIfReadonly: false,\n * })\n * )\n * ```\n *\n * @remarks\n * **Precedence rules:**\n * 1. Per-field `excludeValueIf*` on `FieldDef` — wins for that field\n * 2. Per-form `excludeValueIf*` on `FormOptions` — wins for all fields in that form\n * 3. Global `withValueExclusionDefaults()` — baseline default\n * 4. No global feature — uses token default (all enabled)\n *\n * @param config - Partial override of exclusion rules. Unspecified properties default to `true`.\n * @returns A DynamicFormFeature that configures value exclusion defaults\n *\n * @public\n */\nexport function withValueExclusionDefaults(config?: Partial<ValueExclusionConfig>): DynamicFormFeature<'value-exclusion'> {\n const resolved = {\n excludeValueIfHidden: config?.excludeValueIfHidden ?? true,\n excludeValueIfDisabled: config?.excludeValueIfDisabled ?? true,\n excludeValueIfReadonly: config?.excludeValueIfReadonly ?? true,\n };\n\n return createFeature('value-exclusion', [{ provide: VALUE_EXCLUSION_DEFAULTS, useValue: resolved }]);\n}\n","/**\n * Zero-cost type carrier used in wrapper registrations.\n *\n * Returns `undefined` at runtime but is typed as `T`, so TypeScript can\n * thread a wrapper's config type through `createWrappers(...)` into the\n * `InferWrapperRegistry<typeof ...>` utility without requiring users to\n * hand-write the augmentation shape.\n *\n * @example\n * ```typescript\n * const wrappers = createWrappers(\n * {\n * wrapperName: 'section',\n * loadComponent: () => import('./section-wrapper'),\n * props: wrapperProps<SectionWrapper>(),\n * },\n * );\n *\n * declare module '@ng-forge/dynamic-forms' {\n * interface FieldRegistryWrappers extends InferWrapperRegistry<typeof wrappers> {}\n * }\n * ```\n */\nexport function wrapperProps<T>(): T {\n return undefined as unknown as T;\n}\n","import { FieldDef } from './field-def';\nimport { FieldMeta } from './field-meta';\nimport { FieldWithValidation } from './field-with-validation';\nimport { WithInputSignals } from '../../models/component-type';\nimport { Prettify } from '../../models/prettify';\nimport { DynamicText } from '../../models/types/dynamic-text';\n\n/**\n * Supported primitive value types for form fields.\n * This type represents all possible value types that can be used in form fields.\n */\nexport type ValueType = string | number | boolean | Date | object | unknown[];\n\nexport interface BaseValueField<TProps, TValue, TMeta extends FieldMeta = FieldMeta, TNullable extends boolean = false>\n extends FieldDef<TProps, TMeta>, FieldWithValidation {\n value?: TNullable extends true ? TValue | null : TValue;\n\n /**\n * Placeholder text displayed when the field is empty.\n * Supports static strings, Observables, and Signals for dynamic content.\n *\n * Note: placeholder lives at the field level, NOT inside `props`. The integration-layer\n * `props` interfaces (InputProps, TextareaProps, SelectProps, DatepickerProps) intentionally\n * omit `placeholder` — TypeScript's excess property check rejects `props: { placeholder: ... }`\n * for any `props` literal typed against those interfaces.\n */\n placeholder?: DynamicText;\n\n required?: boolean;\n\n /**\n * Whether the field accepts `null` as a valid value.\n *\n * When `true`, `value` may be `null` and an omitted `value` resolves to `null`\n * (rather than the type-specific empty default). Orthogonal to `required`.\n *\n * Read-side caveat: a user clearing a text input reads back as `\"\"`, not `null`\n * — this matches classic Reactive Forms and is enforced by the Web IDL contract.\n * `nullable` is a contract for accepted values, not a guarantee of emitted ones.\n *\n * @default false\n */\n nullable?: TNullable;\n}\n\nexport function isValueField<TProps, TMeta extends FieldMeta = FieldMeta>(\n field: FieldDef<TProps, TMeta>,\n): field is BaseValueField<TProps, ValueType, TMeta, boolean> {\n // `nullable: true` without an explicit `value` is still a value-bearing declaration:\n // the field resolves to `null` at runtime. Treating it as a value field keeps\n // downstream narrowing consistent with getFieldDefaultValue's behavior.\n return 'value' in field || 'nullable' in field;\n}\n\ntype ExcludedKeys =\n | 'type'\n | 'conditionals'\n | 'value'\n | 'valueType'\n | 'nullable'\n | 'disabled'\n | 'readonly'\n | 'hidden'\n | 'col'\n | 'minValue'\n | 'maxValue'\n | 'step'\n // Exclude validation config, but keep validationMessages for component use\n | 'required'\n | 'email'\n | 'min'\n | 'max'\n | 'minLength'\n | 'maxLength'\n | 'pattern'\n | 'validators'\n | 'logic'\n | 'derivation'\n | 'schemas'\n // Value exclusion config (submission-only, not component inputs)\n | 'excludeValueIfHidden'\n | 'excludeValueIfDisabled'\n | 'excludeValueIfReadonly'\n // Wrappers are consumed by DfFieldOutlet / ContainerFieldComponent, not individual fields\n | 'wrappers'\n | 'skipAutoWrappers'\n | 'skipDefaultWrappers';\n// Note: 'meta' is NOT excluded - components must handle meta attributes\n\nexport type ValueFieldComponent<T extends BaseValueField<Record<string, unknown> | unknown, unknown, FieldMeta, boolean>> = Prettify<\n WithInputSignals<Omit<T, ExcludedKeys>>\n>;\n","import { FieldDef } from './field-def';\nimport { FieldMeta } from './field-meta';\nimport { FieldWithValidation } from './field-with-validation';\nimport { WithInputSignals } from '../../models/component-type';\nimport { Prettify } from '../../models/prettify';\nimport { DynamicText } from '../../models/types/dynamic-text';\n\nexport interface BaseCheckedField<TProps, TMeta extends FieldMeta = FieldMeta> extends FieldDef<TProps, TMeta>, FieldWithValidation {\n value?: boolean;\n\n /**\n * Placeholder text displayed when the field is empty.\n * Supports static strings, Observables, and Signals for dynamic content.\n */\n placeholder?: DynamicText;\n\n required?: boolean;\n}\n\nexport function isCheckedField<TProps, TMeta extends FieldMeta = FieldMeta>(\n field: FieldDef<TProps, TMeta>,\n): field is BaseCheckedField<TProps, TMeta> {\n return field.type === 'checkbox';\n}\n\n// Note: 'meta' is NOT excluded - components must handle meta attributes\ntype ExcludedKeys =\n | 'type'\n | 'conditionals'\n | 'value'\n | 'disabled'\n | 'readonly'\n | 'hidden'\n | 'col'\n | keyof FieldWithValidation\n // Value exclusion config (submission-only, not component inputs)\n | 'excludeValueIfHidden'\n | 'excludeValueIfDisabled'\n | 'excludeValueIfReadonly'\n // Wrappers are consumed by DfFieldOutlet / ContainerFieldComponent, not individual fields\n | 'wrappers'\n | 'skipAutoWrappers'\n | 'skipDefaultWrappers';\n\nexport type CheckedFieldComponent<T extends BaseCheckedField<Record<string, unknown> | unknown>> = Prettify<\n WithInputSignals<Omit<T, ExcludedKeys>>\n>;\n","import { AppendArrayItemEvent, ArrayItemDefinitionTemplate } from './constants/append-array-item.event';\nimport { PrependArrayItemEvent } from './constants/prepend-array-item.event';\nimport { InsertArrayItemEvent } from './constants/insert-array-item.event';\nimport { MoveArrayItemEvent } from './constants/move-array-item.event';\nimport { PopArrayItemEvent } from './constants/pop-array-item.event';\nimport { ShiftArrayItemEvent } from './constants/shift-array-item.event';\nimport { RemoveAtIndexEvent } from './constants/remove-at-index.event';\n\n/**\n * Builder for array manipulation events.\n *\n * Provides a fluent, discoverable API for array operations.\n * Type `arrayEvent('key').` in your IDE to see all available operations.\n *\n * **BREAKING CHANGE**: Template is now required for add operations.\n *\n * Supports both primitive and object array items:\n * - Primitive: Pass a single field definition → extracts field value directly\n * - Object: Pass an array of field definitions → merges fields into object\n *\n * @example\n * ```typescript\n * import { arrayEvent } from '@ng-forge/dynamic-forms';\n *\n * // Object item: append { name, email } object\n * eventBus.dispatch(arrayEvent('contacts').append([\n * { key: 'name', type: 'input', label: 'Name' },\n * { key: 'email', type: 'input', label: 'Email' }\n * ]));\n *\n * // Primitive item: append single value\n * eventBus.dispatch(arrayEvent('tags').append(\n * { key: 'tag', type: 'input', label: 'Tag' }\n * ));\n *\n * // Removing items (no template needed)\n * eventBus.dispatch(arrayEvent('contacts').pop()); // Remove last\n * eventBus.dispatch(arrayEvent('contacts').shift()); // Remove first\n * eventBus.dispatch(arrayEvent('contacts').removeAt(2)); // Remove at index\n *\n * // Reordering items (no template needed, preserves item identity)\n * eventBus.dispatch(arrayEvent('contacts').move(0, 2)); // Move first to third\n * ```\n *\n * @param arrayKey - The key of the array field to operate on\n * @returns An object with methods for all 7 array operations\n */\nexport function arrayEvent(arrayKey: string) {\n return {\n /**\n * Append a new item at the END of the array.\n * This is the most common operation for adding items.\n *\n * @param template - Template for the new item (REQUIRED)\n * - Single field: Creates a primitive item (field's value is extracted directly)\n * - Array of fields: Creates an object item (fields merged into object)\n * @returns An AppendArrayItemEvent to dispatch\n *\n * @example\n * ```typescript\n * // Object item\n * eventBus.dispatch(arrayEvent('contacts').append([\n * { key: 'name', type: 'input', label: 'Name' }\n * ]));\n *\n * // Primitive item\n * eventBus.dispatch(arrayEvent('tags').append(\n * { key: 'tag', type: 'input', label: 'Tag' }\n * ));\n * ```\n */\n append: <T extends ArrayItemDefinitionTemplate>(template: T) => new AppendArrayItemEvent(arrayKey, template),\n\n /**\n * Prepend a new item at the BEGINNING of the array.\n * Use when new items should appear at the start.\n *\n * @param template - Template for the new item (REQUIRED)\n * - Single field: Creates a primitive item (field's value is extracted directly)\n * - Array of fields: Creates an object item (fields merged into object)\n * @returns A PrependArrayItemEvent to dispatch\n *\n * @example\n * ```typescript\n * // Object item\n * eventBus.dispatch(arrayEvent('contacts').prepend([\n * { key: 'name', type: 'input', label: 'Name' }\n * ]));\n *\n * // Primitive item\n * eventBus.dispatch(arrayEvent('tags').prepend(\n * { key: 'tag', type: 'input', label: 'Tag' }\n * ));\n * ```\n */\n prepend: <T extends ArrayItemDefinitionTemplate>(template: T) => new PrependArrayItemEvent(arrayKey, template),\n\n /**\n * Insert a new item at a SPECIFIC INDEX in the array.\n * Use when you need precise control over item placement.\n *\n * @param index - The position at which to insert the new item\n * @param template - Template for the new item (REQUIRED)\n * - Single field: Creates a primitive item (field's value is extracted directly)\n * - Array of fields: Creates an object item (fields merged into object)\n * @returns An InsertArrayItemEvent to dispatch\n *\n * @example\n * ```typescript\n * // Object item at index 2\n * eventBus.dispatch(arrayEvent('contacts').insertAt(2, [\n * { key: 'name', type: 'input', label: 'Name' }\n * ]));\n *\n * // Primitive item at index 2\n * eventBus.dispatch(arrayEvent('tags').insertAt(2,\n * { key: 'tag', type: 'input', label: 'Tag' }\n * ));\n * ```\n */\n insertAt: <T extends ArrayItemDefinitionTemplate>(index: number, template: T) => new InsertArrayItemEvent(arrayKey, index, template),\n\n /**\n * Remove the LAST item from the array.\n * Equivalent to JavaScript's `Array.pop()`.\n *\n * @returns A PopArrayItemEvent to dispatch\n *\n * @example\n * ```typescript\n * eventBus.dispatch(arrayEvent('contacts').pop());\n * ```\n */\n pop: () => new PopArrayItemEvent(arrayKey),\n\n /**\n * Remove the FIRST item from the array.\n * Equivalent to JavaScript's `Array.shift()`.\n *\n * @returns A ShiftArrayItemEvent to dispatch\n *\n * @example\n * ```typescript\n * eventBus.dispatch(arrayEvent('contacts').shift());\n * ```\n */\n shift: () => new ShiftArrayItemEvent(arrayKey),\n\n /**\n * Remove an item at a SPECIFIC INDEX from the array.\n * Use when you need to remove a specific item by position.\n *\n * @param index - The position of the item to remove\n * @returns A RemoveAtIndexEvent to dispatch\n *\n * @example\n * ```typescript\n * eventBus.dispatch(arrayEvent('contacts').removeAt(2));\n * ```\n */\n removeAt: (index: number) => new RemoveAtIndexEvent(arrayKey, index),\n\n /**\n * Move an existing item from one position to another within the array.\n * This is an atomic reorder — the item is NOT destroyed and recreated.\n * The resolved component, form value, and stored template are preserved.\n *\n * @param from - The current index of the item to move\n * @param to - The target index to move the item to\n * @returns A MoveArrayItemEvent to dispatch\n *\n * @example\n * ```typescript\n * // Move item from index 0 to index 2\n * eventBus.dispatch(arrayEvent('contacts').move(0, 2));\n * ```\n */\n move: (from: number, to: number) => new MoveArrayItemEvent(arrayKey, from, to),\n };\n}\n","/**\n * Context for token resolution in event args\n */\nexport interface TokenContext {\n /** Current field key */\n key?: string;\n /** Array index if field is inside an array */\n index?: number;\n /** Parent array field key if field is inside an array */\n arrayKey?: string;\n /** Current form value for complex indexing */\n formValue?: unknown;\n /** Template for array item creation */\n template?: unknown;\n}\n\n/**\n * Resolves special tokens in event arguments to their actual values\n *\n * Supported tokens:\n * - $key: The current field key\n * - $index: The array index (if inside an array field)\n * - $arrayKey: The parent array field key (if inside an array field)\n * - $template: The template for array item creation\n * - formValue: Reference to the current form value for indexing\n *\n * @param args - Array of arguments that may contain tokens\n * @param context - Context object containing token values\n * @returns Array with resolved values\n *\n * @example\n * resolveTokens(['$arrayKey', '$index'], { arrayKey: 'contacts', index: 2 })\n * // Returns: ['contacts', 2]\n *\n * @example\n * resolveTokens(['$key', 'static'], { key: 'myField' })\n * // Returns: ['myField', 'static']\n *\n * @example\n * resolveTokens(['$arrayKey', '$template'], { arrayKey: 'contacts', template: [{ key: 'name', type: 'input' }] })\n * // Returns: ['contacts', [{ key: 'name', type: 'input' }]]\n */\nexport function resolveTokens(\n args: readonly (string | number | boolean | null | undefined)[],\n context: TokenContext,\n): (string | number | boolean | null | undefined | unknown)[] {\n return args.map((arg) => {\n // Only process string tokens\n if (typeof arg !== 'string') {\n return arg;\n }\n\n // Check for token patterns\n switch (arg) {\n case '$key':\n return context.key;\n case '$index':\n return context.index;\n case '$arrayKey':\n return context.arrayKey;\n case '$template':\n return context.template;\n case 'formValue':\n return context.formValue;\n default:\n // Return as-is if not a recognized token\n return arg;\n }\n });\n}\n","// Event classes (from constants)\nexport {\n AppendArrayItemEvent,\n FormClearEvent,\n FormResetEvent,\n InsertArrayItemEvent,\n MoveArrayItemEvent,\n NextPageEvent,\n PageChangeEvent,\n PopArrayItemEvent,\n PrependArrayItemEvent,\n PreviousPageEvent,\n RemoveAtIndexEvent,\n ShiftArrayItemEvent,\n SubmitEvent,\n} from './constants';\nexport type { ArrayItemTemplate, ArrayItemDefinitionTemplate } from './constants';\n\n// Array event builder (public API)\nexport { arrayEvent } from './array-event';\n\n// Interfaces\nexport type { FormEvent, FormEventConstructor } from './interfaces/form-event';\nexport { hasFormValue } from './interfaces/form-event';\n\n// Utilities\nexport { EventBus } from './event.bus';\nexport type { TokenContext } from './utils/token-resolver';\nexport { resolveTokens } from './utils/token-resolver';\nexport type { ArrayItemContext } from './interfaces/array-item-context';\n","import type { FormConfig } from '../models/form-config';\nimport type { NarrowFields } from '../models/registry/field-registry';\nimport type { InferFormValue } from '../models/types/form-value-inference';\nimport type { FormSchema } from '@ng-forge/dynamic-forms/schema';\n\n/**\n * Type-safe form config builder that ensures schema matches field structure.\n *\n * This helper function provides type safety when using form-level schemas by\n * automatically inferring the form value type from fields and constraining\n * the schema type parameter accordingly.\n *\n * **When to use:**\n * - When you have a form-level `schema` and want type safety between fields and schema\n * - When you prefer function syntax over `as const satisfies FormConfig`\n *\n * **Note:** This is optional. Users who don't need schema type safety can\n * continue using `as const satisfies FormConfig` directly.\n *\n * @typeParam TFields - The field definitions array (narrowed via `as const`)\n * @typeParam TProps - Optional form-level default props type\n *\n * @param config - The form configuration object\n * @returns The same configuration with proper type inference\n *\n * @example Basic usage with Zod schema\n * ```typescript\n * import { z } from 'zod';\n * import { formConfig } from '@ng-forge/dynamic-forms';\n * import { standardSchema } from '@ng-forge/dynamic-forms/schema';\n *\n * const passwordSchema = z.object({\n * password: z.string().min(8),\n * confirmPassword: z.string(),\n * }).refine(\n * (data) => data.password === data.confirmPassword,\n * { message: 'Passwords must match', path: ['confirmPassword'] }\n * );\n *\n * const config = formConfig({\n * schema: standardSchema(passwordSchema),\n * fields: [\n * { key: 'password', type: 'input', label: 'Password', required: true, props: { type: 'password' } },\n * { key: 'confirmPassword', type: 'input', label: 'Confirm', required: true, props: { type: 'password' } },\n * { key: 'submit', type: 'submit', label: 'Register' },\n * ] as const,\n * });\n * ```\n *\n * @example Equivalent without helper\n * ```typescript\n * const config = {\n * schema: standardSchema(passwordSchema),\n * fields: [...],\n * } as const satisfies FormConfig;\n * ```\n */\nexport function formConfig<const TFields extends NarrowFields, TProps extends object = Record<string, unknown>>(\n config: Omit<FormConfig<TFields, InferFormValue<TFields>, TProps>, 'schema'> & {\n schema?: FormSchema<InferFormValue<TFields>>;\n },\n): FormConfig<TFields, InferFormValue<TFields>, TProps> {\n return config as FormConfig<TFields, InferFormValue<TFields>, TProps>;\n}\n","import { DynamicFormError } from '../errors/dynamic-form-error';\nimport { AvailableFieldTypes, ExtractField } from '../models';\n\n/**\n * Container field types that do NOT support labels\n */\nconst CONTAINER_TYPES = ['group', 'row', 'array', 'container'] as const;\n\n/**\n * Container and page field types that only support 'hidden' logic\n */\nconst HIDDEN_ONLY_LOGIC_TYPES = ['group', 'row', 'array', 'container', 'page'] as const;\n\n/**\n * Field types that support options at the field level\n */\nconst OPTION_FIELD_TYPES = ['select', 'radio', 'multi-checkbox'] as const;\n\n/**\n * Field type that uses minValue/maxValue instead of min/max in props\n */\nconst SLIDER_TYPE = 'slider' as const;\n\n/**\n * Hidden field type - no logic, no validators, no label\n */\nconst HIDDEN_TYPE = 'hidden' as const;\n\n/**\n * Creates a typed field configuration with helpful error messages for common mistakes.\n *\n * This helper function provides early validation and clear error messages\n * for common configuration pitfalls that would otherwise cause runtime errors.\n *\n * @example\n * ```typescript\n * // Basic usage\n * const nameField = createField('input', {\n * key: 'name',\n * label: 'Name',\n * value: ''\n * });\n *\n * // With validation\n * const emailField = createField('input', {\n * key: 'email',\n * label: 'Email',\n * required: true,\n * email: true,\n * props: { type: 'email' }\n * });\n *\n * // Select with options (at field level)\n * const countryField = createField('select', {\n * key: 'country',\n * label: 'Country',\n * options: [{ label: 'USA', value: 'us' }]\n * });\n *\n * // Slider with minValue/maxValue (at field level)\n * const ratingField = createField('slider', {\n * key: 'rating',\n * label: 'Rating',\n * minValue: 1,\n * maxValue: 10,\n * step: 1,\n * value: 5\n * });\n * ```\n *\n * @param type - The field type (e.g., 'input', 'select', 'group')\n * @param config - The field configuration (excluding the 'type' property)\n * @returns A properly typed field configuration\n * @throws DynamicFormError if the configuration contains common mistakes\n */\nexport function createField<T extends AvailableFieldTypes>(type: T, config: Omit<ExtractField<T>, 'type'>): ExtractField<T> {\n const configWithProps = config as Record<string, unknown>;\n\n // Validate key is present\n if (!configWithProps['key']) {\n throw new DynamicFormError(`createField('${type}'): 'key' property is required`);\n }\n\n // Container validation: no label allowed\n if (CONTAINER_TYPES.includes(type as (typeof CONTAINER_TYPES)[number])) {\n if ('label' in configWithProps && configWithProps['label'] !== undefined) {\n throw new DynamicFormError(\n `createField('${type}'): Container fields (${CONTAINER_TYPES.join(', ')}) do NOT support 'label'. ` +\n `Labels go on the child fields inside the container.`,\n );\n }\n }\n\n // Container + page validation: only hidden logic allowed\n if (HIDDEN_ONLY_LOGIC_TYPES.includes(type as (typeof HIDDEN_ONLY_LOGIC_TYPES)[number])) {\n if ('logic' in configWithProps && configWithProps['logic'] !== undefined) {\n const logic = configWithProps['logic'] as Array<{ type: string }>;\n if (Array.isArray(logic)) {\n const nonHiddenLogic = logic.filter((l) => l.type !== 'hidden');\n if (nonHiddenLogic.length > 0) {\n throw new DynamicFormError(\n `createField('${type}'): Only 'hidden' logic type is supported. ` +\n `Found unsupported logic types: ${nonHiddenLogic.map((l) => l.type).join(', ')}. ` +\n `For other logic types, apply them to child fields instead.`,\n );\n }\n }\n }\n }\n\n // Options placement validation\n if (OPTION_FIELD_TYPES.includes(type as (typeof OPTION_FIELD_TYPES)[number])) {\n const props = configWithProps['props'] as Record<string, unknown> | undefined;\n if (props && 'options' in props) {\n throw new DynamicFormError(\n `createField('${type}'): 'options' must be at FIELD level, NOT inside 'props'. ` +\n `Move 'options' from props to the field root: { type: '${type}', key: '...', options: [...] }`,\n );\n }\n }\n\n // Slider props validation\n if ((type as string) === SLIDER_TYPE) {\n const props = configWithProps['props'] as Record<string, unknown> | undefined;\n if (props) {\n if ('min' in props || 'max' in props) {\n throw new DynamicFormError(\n `createField('slider'): Use 'minValue' and 'maxValue' at FIELD level, NOT 'min'/'max' in props. ` +\n `Example: { type: 'slider', key: '...', minValue: 0, maxValue: 100, step: 1 }`,\n );\n }\n if ('step' in props) {\n throw new DynamicFormError(\n `createField('slider'): Use 'step' at FIELD level, NOT in props. ` +\n `Example: { type: 'slider', key: '...', minValue: 0, maxValue: 100, step: 1 }`,\n );\n }\n }\n }\n\n // Hidden field validation\n if ((type as string) === HIDDEN_TYPE) {\n if ('logic' in configWithProps && configWithProps['logic'] !== undefined) {\n throw new DynamicFormError(\n `createField('hidden'): Hidden fields do NOT support 'logic'. ` + `Hidden fields are purely for passing values through the form.`,\n );\n }\n if ('validators' in configWithProps && configWithProps['validators'] !== undefined) {\n throw new DynamicFormError(\n `createField('hidden'): Hidden fields do NOT support 'validators'. ` +\n `Hidden fields are purely for passing values through the form.`,\n );\n }\n if ('required' in configWithProps && configWithProps['required']) {\n throw new DynamicFormError(\n `createField('hidden'): Hidden fields do NOT support 'required' validation. ` +\n `Hidden fields are purely for passing values through the form.`,\n );\n }\n if ('label' in configWithProps && configWithProps['label'] !== undefined) {\n throw new DynamicFormError(\n `createField('hidden'): Hidden fields do NOT support 'label'. ` +\n `Hidden fields are not rendered and have no visual representation.`,\n );\n }\n }\n\n // Array field validation\n if ((type as string) === 'array') {\n if ('template' in configWithProps) {\n throw new DynamicFormError(\n `createField('array'): Use 'fields' (NOT 'template') to define the array item structure. ` +\n `Example: { type: 'array', key: '...', fields: [{ type: 'group', key: 'item', fields: [...] }] }`,\n );\n }\n }\n\n // Generic button validation\n if ((type as string) === 'button') {\n if (!('event' in configWithProps) || configWithProps['event'] === undefined) {\n throw new DynamicFormError(\n `createField('button'): Generic buttons REQUIRE the 'event' property with a FormEventConstructor. ` +\n `For common actions, use 'submit', 'next', or 'previous' instead which don't require event configuration. ` +\n `Example: { type: 'submit', key: 'submit', label: 'Submit' }`,\n );\n }\n }\n\n return { type, ...config } as ExtractField<T>;\n}\n\n/**\n * Shorthand alias for createField\n *\n * @example\n * ```typescript\n * const nameField = field('input', { key: 'name', label: 'Name', value: '' });\n * ```\n */\nexport const field = createField;\n","import { isSignal, Injector } from '@angular/core';\nimport { toObservable } from '@angular/core/rxjs-interop';\nimport { isObservable, Observable, of } from 'rxjs';\nimport { DynamicText } from '../models/types/dynamic-text';\n\n/**\n * Converts DynamicText (string | Observable | Signal) to Observable<string>\n * Unifies all three types into a consistent Observable stream\n *\n * @param value - The dynamic text value to convert\n * @param injector - Optional injector for signal conversion\n * @returns Observable<string> - The value as an observable stream\n */\nexport function dynamicTextToObservable(value: DynamicText | undefined, injector?: Injector): Observable<string> {\n if (value === undefined) {\n return of('');\n }\n\n if (isObservable(value)) {\n return value;\n }\n\n if (isSignal(value)) {\n return toObservable(value, { injector });\n }\n\n return of(String(value));\n}\n","import { FieldMeta } from '../definitions/base/field-meta';\n\n/**\n * Applies meta attributes to a DOM element and tracks which attributes were applied.\n *\n * This utility handles:\n * - Removing previously applied attributes that are no longer in meta\n * - Setting new attributes from meta\n * - Converting all values to strings via String()\n *\n * @param element - The DOM element to apply attributes to\n * @param meta - The meta object containing attributes to apply\n * @param previouslyApplied - Set of attribute names that were previously applied\n * @returns A new Set containing the attribute names that were applied\n *\n * @example\n * ```typescript\n * private appliedAttrs = new Set<string>();\n *\n * explicitEffect([this.meta], ([meta]) => {\n * const input = this.el.nativeElement.querySelector('input');\n * if (input) {\n * this.appliedAttrs = applyMetaToElement(input, meta, this.appliedAttrs);\n * }\n * });\n * ```\n */\nexport function applyMetaToElement(element: Element, meta: FieldMeta | undefined, previouslyApplied: Set<string>): Set<string> {\n const newApplied = new Set<string>();\n\n // Remove old attributes no longer in meta\n for (const attr of previouslyApplied) {\n if (!meta || !(attr in meta) || meta[attr] === undefined) {\n element.removeAttribute(attr);\n }\n }\n\n if (!meta) return newApplied;\n\n // Apply new attributes\n for (const [key, value] of Object.entries(meta)) {\n if (value === undefined || value === null) continue;\n\n element.setAttribute(key, String(value));\n newApplied.add(key);\n }\n\n return newApplied;\n}\n","import { inject, Injector, isSignal, Pipe, PipeTransform } from '@angular/core';\nimport { toObservable } from '@angular/core/rxjs-interop';\nimport { isObservable, Observable, of } from 'rxjs';\nimport { DynamicText } from '../../models/types/dynamic-text';\n\n/**\n * Pipe that handles dynamic text resolution with support for static strings,\n * Observables, and Signals.\n *\n * Supports:\n * - Static strings (pass-through)\n * - Observables (subscribed internally)\n * - Signals (converted to Observable using toObservable for reactivity)\n *\n * @example\n * ```html\n * <!-- Static string -->\n * {{ 'Hello World' | dynamicText | async }}\n *\n * <!-- Observable -->\n * {{ transloco.selectTranslate('key') | dynamicText | async }}\n *\n * <!-- Signal -->\n * {{ myTextSignal | dynamicText | async }}\n * ```\n *\n * @public\n */\n@Pipe({\n name: 'dynamicText',\n})\nexport class DynamicTextPipe implements PipeTransform {\n private readonly injector = inject(Injector);\n\n /**\n * Transforms dynamic text input into a resolved string value\n *\n * @param value - The dynamic text value to resolve\n * @returns The resolved string value as an Observable\n */\n transform(value: DynamicText | undefined): Observable<string> {\n if (isObservable(value)) {\n return value;\n }\n\n if (isSignal(value)) {\n return toObservable(value, { injector: this.injector });\n }\n\n return of(value || '');\n }\n}\n","import { afterNextRender, Injector } from '@angular/core';\nimport { EventBus } from '../../events/event.bus';\nimport { ComponentInitializedEvent } from '../../events/constants/component-initialized.event';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\n\n/**\n * Component type for initialization events.\n */\nexport type InitializationComponentType = 'dynamic-form' | 'group' | 'row' | 'page' | 'array' | 'container';\n\n/**\n * Emits a component initialization event after the next render cycle.\n *\n * This utility is used by container components (group, row, page, array) to signal\n * that their child fields have been resolved and rendered. The event is dispatched\n * through the EventBus and is used by the initialization tracking system.\n *\n * @param eventBus - The EventBus instance to dispatch the event on\n * @param componentType - The type of component being initialized\n * @param componentKey - The unique key/id of the component\n * @param injector - The injector to use for afterNextRender scheduling\n */\nexport function emitComponentInitialized(\n eventBus: EventBus,\n componentType: InitializationComponentType,\n componentKey: string,\n injector: Injector,\n): void {\n const logger = injector.get(DynamicFormLogger);\n\n afterNextRender(\n () => {\n try {\n eventBus.dispatch(ComponentInitializedEvent, componentType, componentKey);\n } catch (error: unknown) {\n logger.error(`Failed to emit initialization event for ${componentType} '${componentKey}'`, error);\n }\n },\n { injector },\n );\n}\n","import { computed, Injector, Signal } from '@angular/core';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { EventBus } from '../../events/event.bus';\nimport { emitComponentInitialized, InitializationComponentType } from '../emit-initialization/emit-initialization';\nimport { ResolvedField } from '../resolve-field/resolve-field';\n\n/**\n * Computes the host class string for a container component.\n *\n * All containers follow the pattern: `df-field df-{type}` + optional custom class.\n *\n * @param containerType - The CSS class suffix (e.g., 'group', 'row', 'page-field')\n * @param className - Optional custom class name to append\n * @returns The computed host class string\n */\nexport function computeContainerHostClasses(containerType: string, className: string | undefined): string {\n const base = `df-field df-${containerType}`;\n return className ? `${base} ${className}` : base;\n}\n\n/**\n * Sets up the initialization effect common to all container components.\n *\n * When resolved fields become non-empty, emits a ComponentInitializedEvent\n * via afterNextRender to signal the container is ready.\n *\n * `componentType` may be a static value or a lazy getter — the latter lets\n * virtual field types (e.g. `row`, which renders via ContainerFieldComponent)\n * preserve their original type on the emitted event instead of collapsing to\n * the host component's type.\n *\n * @param resolvedFields - Signal of resolved fields\n * @param eventBus - EventBus for dispatching initialization events\n * @param componentType - Static type, or a getter evaluated at emission time\n * @param fieldKeyFn - Function returning the field's key\n * @param injector - Injector for afterNextRender scheduling\n */\nexport function setupContainerInitEffect(\n resolvedFields: Signal<ResolvedField[]>,\n eventBus: EventBus,\n componentType: InitializationComponentType | (() => InitializationComponentType),\n fieldKeyFn: () => string,\n injector: Injector,\n): void {\n const allReady = computed(() => {\n const fields = resolvedFields();\n return fields.length > 0 && fields.every((field) => field.renderReady());\n });\n\n explicitEffect([allReady], ([ready]) => {\n if (ready) {\n const type = typeof componentType === 'function' ? componentType() : componentType;\n emitComponentInitialized(eventBus, type, fieldKeyFn(), injector);\n }\n });\n}\n","import {\n ChangeDetectionStrategy,\n Component,\n computed,\n DestroyRef,\n EnvironmentInjector,\n inject,\n Injector,\n input,\n linkedSignal,\n runInInjectionContext,\n untracked,\n} from '@angular/core';\nimport { DfFieldOutlet } from '../../directives/df-field-outlet.directive';\nimport { outputFromObservable, toObservable } from '@angular/core/rxjs-interop';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { derivedFromDeferred } from '../../utils/derived-from-deferred/derived-from-deferred';\nimport { createFieldResolutionPipe, ResolvedField } from '../../utils/resolve-field/resolve-field';\nimport { computeContainerHostClasses, setupContainerInitEffect } from '../../utils/container-utils/container-utils';\nimport { CONTAINER_FIELD_PROCESSORS } from '../../utils/container-utils/container-field-processors';\nimport { isEqual } from '../../utils/object-utils';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { GroupField } from '../../definitions/default/group-field';\nimport { injectFieldRegistry } from '../../utils/inject-field-registry/inject-field-registry';\nimport { FieldTree, form } from '@angular/forms/signals';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { FieldSignalContext } from '../../mappers/types';\nimport { FIELD_SIGNAL_CONTEXT } from '../../models/field-signal-context.token';\nimport { createSchemaFromFields } from '../../core/schema-builder';\nimport { EventBus } from '../../events/event.bus';\nimport { SubmitEvent } from '../../events/constants/submit.event';\n\n/**\n * Container component for rendering nested form groups.\n *\n * Creates a scoped form context with its own validation state.\n * Child fields receive a FIELD_SIGNAL_CONTEXT scoped to this group's form instance.\n * Group values are nested under the group's key in the parent form.\n */\n@Component({\n selector: 'fieldset[group-field]',\n imports: [DfFieldOutlet],\n template: `\n @for (field of resolvedFields(); track field.key) {\n <ng-container *dfFieldOutlet=\"field; environmentInjector: environmentInjector\" />\n }\n `,\n styleUrl: './group-field.component.scss',\n host: {\n '[class]': 'hostClasses()',\n role: 'group',\n '[class.disabled]': 'disabled()',\n '[class.df-container-hidden]': 'hidden()',\n '[attr.aria-hidden]': 'hidden() || null',\n '[id]': '`${key()}`',\n '[attr.data-testid]': 'key()',\n },\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport default class GroupFieldComponent<TModel extends Record<string, unknown> = Record<string, unknown>> {\n // ─────────────────────────────────────────────────────────────────────────────\n // Dependencies\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly destroyRef = inject(DestroyRef);\n private readonly fieldRegistry = injectFieldRegistry();\n private readonly parentFieldSignalContext = inject(FIELD_SIGNAL_CONTEXT) as FieldSignalContext<TModel>;\n private readonly injector = inject(Injector);\n protected readonly environmentInjector = inject(EnvironmentInjector);\n private readonly eventBus = inject(EventBus);\n private readonly logger = inject(DynamicFormLogger);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Memoized Functions\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly fieldProcessors = inject(CONTAINER_FIELD_PROCESSORS);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Inputs\n // ─────────────────────────────────────────────────────────────────────────────\n\n field = input.required<GroupField>();\n key = input.required<string>();\n className = input<string>();\n hidden = input(false);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Computed Signals\n // ─────────────────────────────────────────────────────────────────────────────\n\n readonly hostClasses = computed(() => computeContainerHostClasses('group', this.className()));\n\n private readonly rawFieldRegistry = computed(() => this.fieldRegistry.raw);\n\n private readonly formSetup = computed(() => {\n const groupField = this.field();\n const registry = this.rawFieldRegistry();\n\n if (groupField.fields && groupField.fields.length > 0) {\n const flattenedFields = this.fieldProcessors.memoizedFlattenFields(groupField.fields, registry);\n const flattenedFieldsForRendering = this.fieldProcessors.memoizedFlattenFieldsForRendering(groupField.fields, registry);\n const fieldsById = this.fieldProcessors.memoizedKeyBy(flattenedFields);\n const defaultValues = this.fieldProcessors.memoizedDefaultValues(fieldsById, registry);\n\n return {\n fields: flattenedFieldsForRendering,\n schemaFields: flattenedFields,\n originalFields: groupField.fields,\n defaultValues,\n registry,\n };\n }\n\n return {\n fields: [],\n schemaFields: [],\n originalFields: [],\n defaultValues: {},\n registry,\n };\n });\n\n readonly defaultValues = linkedSignal(() => this.formSetup().defaultValues);\n\n /**\n * Entity computed from parent value, group key, and defaults.\n * Uses deep equality check to prevent unnecessary updates when\n * object spread creates new references with identical values.\n */\n private readonly entity = linkedSignal(\n () => {\n const parentValue = this.parentFieldSignalContext.value();\n const groupKey = this.field().key;\n const defaults = this.defaultValues();\n const groupValue = (parentValue as Record<string, unknown>)?.[groupKey] || {};\n return { ...defaults, ...groupValue };\n },\n {\n debugName: 'GroupFieldComponent.entity',\n equal: isEqual,\n },\n );\n\n private readonly form = computed(() => {\n return runInInjectionContext(this.injector, () => {\n const setup = this.formSetup();\n\n if (setup.schemaFields.length > 0) {\n const schema = createSchemaFromFields(setup.schemaFields, setup.registry);\n return untracked(() => form(this.entity, schema));\n }\n\n return untracked(() => form(this.entity));\n });\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Public State Signals\n // ─────────────────────────────────────────────────────────────────────────────\n\n readonly formValue = computed(() => this.entity());\n readonly valid = computed(() => this.form()().valid());\n readonly invalid = computed(() => this.form()().invalid());\n readonly dirty = computed(() => this.form()().dirty());\n readonly touched = computed(() => this.form()().touched());\n readonly errors = computed(() => this.form()().errors());\n readonly disabled = computed(() => this.form()().disabled());\n\n private readonly nestedFieldTree = computed((): FieldTree<Record<string, unknown>> | undefined => {\n const parentForm = this.parentFieldSignalContext.form as Record<string, FieldTree<Record<string, unknown>>>;\n const groupKey = this.field().key;\n return parentForm[groupKey];\n });\n\n private readonly groupFieldSignalContext: FieldSignalContext<Record<string, unknown>> = (() => {\n const nestedFieldTree = this.nestedFieldTree;\n return {\n injector: this.injector,\n value: this.parentFieldSignalContext.value,\n defaultValues: this.defaultValues,\n get form() {\n return nestedFieldTree() ?? ({} as FieldTree<Record<string, unknown>>);\n },\n };\n })();\n\n private readonly groupInjector = Injector.create({\n parent: this.injector,\n providers: [{ provide: FIELD_SIGNAL_CONTEXT, useValue: this.groupFieldSignalContext }],\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Outputs\n // ─────────────────────────────────────────────────────────────────────────────\n\n readonly validityChange = outputFromObservable(toObservable(this.valid));\n readonly dirtyChange = outputFromObservable(toObservable(this.dirty));\n readonly submitted = outputFromObservable(this.eventBus.on<SubmitEvent>('submit'));\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Field Resolution\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly fieldsSource = computed(() => this.formSetup().fields);\n\n protected readonly resolvedFields = derivedFromDeferred(\n this.fieldsSource,\n createFieldResolutionPipe(() => ({\n loadTypeComponent: (type: string) => this.fieldRegistry.loadTypeComponent(type),\n registry: this.rawFieldRegistry(),\n injector: this.groupInjector,\n destroyRef: this.destroyRef,\n onError: (fieldDef: FieldDef<unknown>, error: unknown) => {\n const fieldKey = fieldDef.key || '<no key>';\n this.logger.error(\n `Failed to load component for field type '${fieldDef.type}' (key: ${fieldKey}) ` +\n `within group '${this.field().key}'. Ensure the field type is registered in your field registry.`,\n error,\n );\n },\n })),\n { initialValue: [] as ResolvedField[], injector: this.injector },\n );\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────────\n\n constructor() {\n this.setupEffects();\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n private setupEffects(): void {\n setupContainerInitEffect(this.resolvedFields, this.eventBus, 'group', () => this.field().key, this.injector);\n\n explicitEffect(\n [this.nestedFieldTree, this.field],\n ([tree, field]) => {\n if (!tree) {\n this.logger.warn(\n `Group field \"${field.key}\" not found in parent form. ` + `Ensure the parent form schema includes this group field.`,\n );\n }\n },\n { defer: true },\n );\n }\n}\n\nexport { GroupFieldComponent };\n","import { Injector, Signal, type Type } from '@angular/core';\nimport type { FieldDef } from '../../definitions/base/field-def';\n\n/**\n * A single field within a resolved array item.\n *\n * Structurally compatible with `ResolvedField` so the same DfFieldOutlet\n * directive can render both top-level and array-item fields.\n */\nexport interface ResolvedArrayItemField {\n /** Field key (used for tracking and test IDs). */\n key: string;\n /** Original field definition — used by DfFieldOutlet to resolve wrappers. */\n fieldDef: FieldDef<unknown>;\n /** The loaded component type. */\n component: Type<unknown>;\n /** Injector providing ARRAY_CONTEXT and FIELD_SIGNAL_CONTEXT. */\n injector: Injector;\n /** Inputs signal for DfFieldOutlet — evaluated in template for reactivity. */\n inputs: Signal<Record<string, unknown>>;\n /** Whether required mapped inputs are available for safe component instantiation. */\n renderReady: Signal<boolean>;\n}\n\n/**\n * Resolved array item ready for declarative rendering with ngComponentOutlet.\n * Each item has a stable unique ID and a linkedSignal-based index that\n * automatically updates when items are added/removed.\n * Supports multiple fields per array item (e.g., name + email without a wrapper).\n */\nexport interface ResolvedArrayItem {\n /** Unique identifier for this item (stable across position changes). */\n id: string;\n /** All fields to render for this array item. */\n fields: ResolvedArrayItemField[];\n}\n\n/**\n * Safely extracts an array value from a model object.\n * Returns empty array if the key doesn't exist or value isn't an array.\n */\nexport function getArrayValue<TModel>(value: Partial<TModel> | undefined, key: string): unknown[] {\n const arrayValue = (value as Record<string, unknown>)?.[key];\n return Array.isArray(arrayValue) ? arrayValue : [];\n}\n\n/**\n * Discriminated union of possible differential update operations.\n * Enables optimized array updates without full recreation when possible.\n */\nexport type DifferentialUpdateOperation =\n | { type: 'clear' }\n | { type: 'initial'; fieldTreesLength: number }\n | { type: 'append'; startIndex: number; endIndex: number }\n | { type: 'recreate' }\n | { type: 'none' };\n\n/**\n * Determines the optimal differential update operation based on current and new state.\n *\n * Operations:\n * - Clear all (empty array)\n * - Initial render (no existing items)\n * - Append only (items added at end)\n * - Recreate (items removed - we can't know which items, so recreate all)\n * - None (same length - items update via linkedSignal)\n *\n * Note: We always use 'recreate' for removals because we can't determine which\n * specific items were removed. Operations like shift, removeAtIndex remove from\n * the middle, not just the end. Each array item has its own local form that\n * doesn't reactively track parent changes, so we must recreate to get correct values.\n */\nexport function determineDifferentialOperation(currentItems: ResolvedArrayItem[], newLength: number): DifferentialUpdateOperation {\n const currentLength = currentItems.length;\n\n if (newLength === 0) {\n return { type: 'clear' };\n }\n\n if (currentLength === 0) {\n return { type: 'initial', fieldTreesLength: newLength };\n }\n\n // For all length changes, we optimize by assuming existing items stay in place.\n // Items handle their own value updates via linkedSignal - no need to compare snapshots.\n // Snapshot comparison was causing false \"recreate\" when existing items had been edited.\n\n if (newLength > currentLength) {\n // Items added - append new ones, existing items stay\n return { type: 'append', startIndex: currentLength, endIndex: newLength };\n }\n\n if (newLength < currentLength) {\n // Items removed - must recreate because we don't know which items were removed.\n // shift() removes from index 0, removeAtIndex() removes from any position.\n // Each item's local form is initialized with its value at creation time and\n // doesn't reactively track parent array changes.\n return { type: 'recreate' };\n }\n\n // Same length - no structural change, items update via linkedSignal\n return { type: 'none' };\n}\n","import { computed, Injector, runInInjectionContext, Signal } from '@angular/core';\nimport { FieldTree } from '@angular/forms/signals';\nimport { ArrayField } from '../../definitions/default/array-field';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { ArrayContext, FieldSignalContext } from '../../mappers/types';\nimport { ARRAY_CONTEXT, FIELD_SIGNAL_CONTEXT } from '../../models/field-signal-context.token';\nimport { FieldTypeDefinition } from '../../models/field-type';\nimport { mapFieldToInputs } from '../field-mapper/field-mapper';\nimport { RootFormRegistryService } from '../../core/registry/root-form-registry.service';\nimport { isEqual } from '../object-utils';\n\n/**\n * Options for creating an array item injector.\n */\nexport interface CreateArrayItemInjectorOptions<TModel extends Record<string, unknown>> {\n /** The field template defining the array item structure. */\n template: FieldDef<unknown>;\n /** Signal containing the current index (uses linkedSignal for auto-updates). */\n indexSignal: Signal<number>;\n /** Parent context for accessing form state and values. */\n parentFieldSignalContext: FieldSignalContext<TModel>;\n /** Parent injector for creating scoped child injector. */\n parentInjector: Injector;\n /** Field registry for looking up field type definitions. */\n registry: Map<string, FieldTypeDefinition>;\n /** The array field definition containing this item. */\n arrayField: ArrayField;\n /**\n * For primitive array items, the key of the value field in the template (e.g., 'value').\n * When set, the form getter wraps the raw FormControl in `{ [primitiveFieldKey]: FormControl }`\n * so that `getFieldTree(key)` can navigate to the control by key.\n *\n * Primitive items store flat values (e.g., `['angular']` not `[{value: 'angular'}]`),\n * so the FieldTree at `rootForm['arrayKey'][index]` is a FormControl, not a FormGroup.\n * Without wrapping, `getFieldTree('value')` would access the FormControl's `.value`\n * property (a WritableSignal) instead of a child FieldTree.\n */\n primitiveFieldKey?: string;\n}\n\n/**\n * Result of creating an array item injector.\n */\nexport interface ArrayItemInjectorResult {\n /** Scoped injector providing ARRAY_CONTEXT and FIELD_SIGNAL_CONTEXT. */\n injector: Injector;\n /** Inputs signal for ngComponentOutlet, mapped from the field template. Undefined for componentless fields. */\n inputs: Signal<Record<string, unknown>> | undefined;\n}\n\n/**\n * Creates an injector and inputs for an array item.\n *\n * Uses direct root form binding - components bind directly to the root form's\n * FieldTree for array items (rootForm['arrayKey'][index]). This architecture:\n *\n * - Eliminates the need for local forms and bidirectional sync\n * - Allows Zod/StandardSchema validation errors to flow naturally to components\n * - Reduces complexity by having a single source of truth (the root form)\n *\n * The FieldSignalContext.form property uses a getter that evaluates a computed\n * signal, making form access reactive to index changes (when items reorder,\n * the component points to the correct array position).\n */\nexport function createArrayItemInjectorAndInputs<TModel extends Record<string, unknown>>(\n options: CreateArrayItemInjectorOptions<TModel>,\n): ArrayItemInjectorResult {\n const { template, indexSignal, parentFieldSignalContext, parentInjector, registry, arrayField, primitiveFieldKey } = options;\n\n // Get root form registry - it's guaranteed to be available since root form\n // is registered before resolvedFields computes (dependency chain ensures this)\n const rootFormRegistry = parentInjector.get(RootFormRegistryService);\n\n // Create a computed that derives the array item's FieldTree from root form.\n // Uses isEqual to prevent unnecessary re-computation when index changes but value is same.\n const itemFormAccessor = computed(\n () => {\n const rootForm = rootFormRegistry.rootForm();\n if (!rootForm) {\n return undefined;\n }\n\n const index = indexSignal();\n // Navigate: rootForm['arrayKey'][index]\n const arrayFieldTree = (rootForm as Record<string, unknown>)[arrayField.key];\n if (!arrayFieldTree) {\n return undefined;\n }\n\n return (arrayFieldTree as unknown[])[index] as FieldTree<unknown> | undefined;\n },\n { equal: isEqual },\n );\n\n const injector = createItemInjector({\n itemFormAccessor,\n indexSignal,\n parentFieldSignalContext,\n parentInjector,\n arrayField,\n primitiveFieldKey,\n });\n\n // mapFieldToInputs automatically reads ARRAY_CONTEXT from the injector\n // and applies the index suffix to keys for unique DOM IDs\n const inputs = runInInjectionContext(injector, () => {\n return mapFieldToInputs(template, registry);\n });\n\n return { injector, inputs };\n}\n\ninterface CreateItemInjectorOptions<TModel extends Record<string, unknown>> {\n itemFormAccessor: Signal<FieldTree<unknown> | undefined>;\n indexSignal: Signal<number>;\n parentFieldSignalContext: FieldSignalContext<TModel>;\n parentInjector: Injector;\n arrayField: ArrayField;\n primitiveFieldKey?: string;\n}\n\n/**\n * Creates a scoped injector for an array item.\n * Provides both FIELD_SIGNAL_CONTEXT (for form access) and ARRAY_CONTEXT (for position awareness).\n *\n * The FIELD_SIGNAL_CONTEXT.form uses a getter that evaluates itemFormAccessor() on access.\n * This makes form access reactive - when mappers access context.form['fieldKey'], the getter runs,\n * evaluating the computed which tracks indexSignal as a dependency. This ensures components\n * automatically update when array items reorder.\n *\n * Uses `useFactory` with `deps: [Injector]` to provide FIELD_SIGNAL_CONTEXT. Angular resolves\n * the `Injector` dep as the child injector being created, eliminating any temporal gap.\n */\nfunction createItemInjector<TModel extends Record<string, unknown>>(options: CreateItemInjectorOptions<TModel>): Injector {\n const { itemFormAccessor, indexSignal, parentFieldSignalContext, parentInjector, arrayField, primitiveFieldKey } = options;\n\n // Use getter for formValue to ensure it's always current, not a stale snapshot.\n // Components accessing arrayContext.formValue will get the current value.\n const arrayContext: ArrayContext = {\n arrayKey: arrayField.key,\n index: indexSignal,\n get formValue() {\n return parentFieldSignalContext.value();\n },\n field: arrayField,\n };\n\n // Cache for the primitive wrapper object — avoids creating a new { [primitiveFieldKey]: raw }\n // on every form getter access, which would defeat reference-equality checks downstream.\n let cachedPrimitiveRaw: FieldTree<unknown> | undefined;\n let cachedPrimitiveWrapped: FieldTree<Record<string, unknown>> | undefined;\n\n return Injector.create({\n parent: parentInjector,\n providers: [\n {\n provide: FIELD_SIGNAL_CONTEXT,\n // Angular resolves `Injector` in deps as the child injector being created,\n // so no temporal gap exists — the injector reference is immediately available.\n useFactory: (injector: Injector): FieldSignalContext<Record<string, unknown>> => ({\n injector,\n value: parentFieldSignalContext.value,\n // Array items don't propagate parent default values because each item's defaults\n // are determined by its template fields at creation time (via getFieldDefaultValue).\n // The parent's defaultValues contain top-level form defaults, not per-item defaults.\n defaultValues: () => ({}),\n get form(): FieldTree<Record<string, unknown>> {\n const raw = itemFormAccessor();\n if (!raw) {\n // During initialization or transitions, the FieldTree may not be available yet.\n // This occurs in the window between item creation and Angular's form tree construction.\n // Return an empty object so that downstream getFieldTree(key) calls return undefined\n // rather than causing a runtime error on a truly undefined value.\n return {} as FieldTree<Record<string, unknown>>;\n }\n\n // For primitive array items, the FieldTree is a FormControl (the item IS the control).\n // Wrap it in an object so getFieldTree(primitiveFieldKey) returns the FormControl itself.\n // Without this, getFieldTree('value') would access FormControl['value'] (the WritableSignal),\n // not a child FieldTree, causing NG0950 errors.\n if (primitiveFieldKey) {\n // Cache the wrapper to preserve reference identity when raw hasn't changed\n if (raw !== cachedPrimitiveRaw) {\n cachedPrimitiveRaw = raw;\n cachedPrimitiveWrapped = { [primitiveFieldKey]: raw } as FieldTree<Record<string, unknown>>;\n }\n return cachedPrimitiveWrapped!;\n }\n\n return raw as FieldTree<Record<string, unknown>>;\n },\n }),\n deps: [Injector],\n },\n { provide: ARRAY_CONTEXT, useValue: arrayContext },\n ],\n });\n}\n","import { DestroyRef, Injector, linkedSignal, Signal, Type } from '@angular/core';\nimport { catchError, forkJoin, from, map, Observable, of } from 'rxjs';\nimport { ArrayField } from '../../definitions/default/array-field';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { FieldSignalContext } from '../../mappers/types';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { FieldTypeDefinition } from '../../models/field-type';\nimport { ResolvedArrayItem, ResolvedArrayItemField } from './array-field.types';\nimport { createArrayItemInjectorAndInputs } from './create-array-item-injector';\nimport { createRenderReadySignal } from '../resolve-field/resolve-field';\n\n/**\n * Options for resolving an array item.\n */\nexport interface ResolveArrayItemOptions<TModel extends Record<string, unknown>> {\n /** The initial index of this item in the array. */\n index: number;\n /** The field templates defining the array item structure (supports multiple sibling fields). */\n templates: FieldDef<unknown>[];\n /** The array field definition containing this item. */\n arrayField: ArrayField;\n /** Map signal for O(1) position lookup. Keys are item IDs, values are indices. */\n itemPositionMap: Signal<Map<string, number>>;\n /** Parent context for accessing form state and values. */\n parentFieldSignalContext: FieldSignalContext<TModel>;\n /** Parent injector for creating scoped child injector. */\n parentInjector: Injector;\n /** Field registry for looking up field type definitions. */\n registry: Map<string, FieldTypeDefinition>;\n /** DestroyRef to abort resolution if component is destroyed. */\n destroyRef: DestroyRef;\n /**\n * Function to async load the component for the field type.\n * Returns undefined for componentless fields (e.g., hidden fields).\n */\n loadTypeComponent: (type: string) => Promise<Type<unknown> | undefined>;\n /**\n * Function to generate unique item IDs. Scoped to the array component instance\n * to ensure SSR hydration compatibility (server and client generate same IDs).\n */\n generateItemId: () => string;\n /**\n * For primitive array items, the key of the value field in the template.\n * Passed through to createArrayItemInjectorAndInputs for form context wrapping.\n */\n primitiveFieldKey?: string;\n}\n\n/**\n * Resolves a single array item with all its fields for declarative rendering.\n *\n * Uses linkedSignal for the index, which automatically updates when itemOrderSignal changes.\n * This enables position-aware updates without recreating components when items are reordered.\n * Supports multiple sibling templates (e.g., name + email without a wrapper).\n */\nexport function resolveArrayItem<TModel extends Record<string, unknown>>(\n options: ResolveArrayItemOptions<TModel>,\n): Observable<ResolvedArrayItem | undefined> {\n const {\n index,\n templates,\n arrayField,\n itemPositionMap,\n parentFieldSignalContext,\n parentInjector,\n registry,\n destroyRef,\n loadTypeComponent,\n generateItemId,\n primitiveFieldKey,\n } = options;\n\n if (templates.length === 0) {\n return of(undefined);\n }\n\n // Generate ONE id for this array item (shared by all fields for tracking)\n const itemId = generateItemId();\n\n // O(1) position lookup via Map instead of O(n) indexOf()\n const indexSignal = linkedSignal(() => {\n const positionMap = itemPositionMap();\n return positionMap.get(itemId) ?? index;\n });\n\n // Resolve all templates in parallel\n const fieldObservables = templates.map((template) =>\n from(loadTypeComponent(template.type)).pipe(\n map((component): ResolvedArrayItemField | undefined => {\n if (destroyRef.destroyed) {\n return undefined;\n }\n\n // Componentless fields (e.g., hidden) return undefined - nothing to render\n if (!component) {\n return undefined;\n }\n\n const { injector, inputs } = createArrayItemInjectorAndInputs({\n template,\n indexSignal,\n parentFieldSignalContext,\n parentInjector,\n registry,\n arrayField,\n primitiveFieldKey,\n });\n\n // Array item templates should always have inputs (componentless fields are handled above)\n if (!inputs) {\n return undefined;\n }\n\n return {\n key: template.key,\n fieldDef: template,\n component,\n injector,\n inputs,\n renderReady: createRenderReadySignal(inputs, registry.get(template.type)),\n };\n }),\n catchError((error) => {\n if (!destroyRef.destroyed) {\n const logger = parentInjector.get(DynamicFormLogger);\n logger.error(\n `Failed to load component for field type '${template.type}' at index ${index} ` +\n `within array '${arrayField.key}'. Ensure the field type is registered in your field registry.`,\n error,\n );\n }\n return of(undefined);\n }),\n ),\n );\n\n return forkJoin(fieldObservables).pipe(\n map((fields) => {\n const validFields = fields.filter((f): f is ResolvedArrayItemField => f !== undefined);\n\n // If no fields resolved, return undefined\n if (validFields.length === 0) {\n return undefined;\n }\n\n return {\n id: itemId,\n fields: validFields,\n };\n }),\n );\n}\n","import { filter, map, Observable } from 'rxjs';\nimport { AppendArrayItemEvent } from '../../events/constants/append-array-item.event';\nimport { PrependArrayItemEvent } from '../../events/constants/prepend-array-item.event';\nimport { InsertArrayItemEvent } from '../../events/constants/insert-array-item.event';\nimport { MoveArrayItemEvent } from '../../events/constants/move-array-item.event';\nimport { PopArrayItemEvent } from '../../events/constants/pop-array-item.event';\nimport { ShiftArrayItemEvent } from '../../events/constants/shift-array-item.event';\nimport { RemoveAtIndexEvent } from '../../events/constants/remove-at-index.event';\nimport { EventBus } from '../../events/event.bus';\nimport { FieldDef } from '../../definitions/base/field-def';\n\n/**\n * Union type of all array manipulation events.\n */\nexport type ArrayEvent =\n | AppendArrayItemEvent\n | PrependArrayItemEvent\n | InsertArrayItemEvent\n | MoveArrayItemEvent\n | PopArrayItemEvent\n | ShiftArrayItemEvent\n | RemoveAtIndexEvent;\n\n/**\n * All array event type discriminants.\n */\nconst ARRAY_EVENT_TYPES: ArrayEvent['type'][] = [\n 'append-array-item',\n 'prepend-array-item',\n 'insert-array-item',\n 'move-array-item',\n 'pop-array-item',\n 'shift-array-item',\n 'remove-at-index',\n];\n\n/**\n * Normalized action representing an array manipulation.\n * Template can be:\n * - Single FieldDef for primitive items (field's value is extracted directly)\n * - Array of FieldDefs for object items (fields merged into object)\n */\nexport type ArrayAction =\n | { action: 'add'; template: FieldDef<unknown> | readonly FieldDef<unknown>[]; index?: number }\n | { action: 'remove'; index?: number }\n | { action: 'move'; fromIndex: number; toIndex: number };\n\n/**\n * Converts an array event to a normalized action.\n * Uses a switch for full type safety with discriminated union narrowing.\n */\nfunction toArrayAction(event: ArrayEvent): ArrayAction {\n switch (event.type) {\n case 'append-array-item':\n return { action: 'add', template: event.template };\n case 'prepend-array-item':\n return { action: 'add', template: event.template, index: 0 };\n case 'insert-array-item':\n return { action: 'add', template: event.template, index: event.index };\n case 'move-array-item':\n return { action: 'move', fromIndex: event.fromIndex, toIndex: event.toIndex };\n case 'pop-array-item':\n return { action: 'remove' };\n case 'shift-array-item':\n return { action: 'remove', index: 0 };\n case 'remove-at-index':\n return { action: 'remove', index: event.index };\n }\n}\n\n/**\n * Creates an observable stream of normalized array actions for a specific array key.\n *\n * @param eventBus - The event bus to subscribe to\n * @param arrayKey - Function returning the array key to filter events for\n * @returns Observable of normalized ArrayAction objects\n *\n * @example\n * ```typescript\n * observeArrayActions(this.eventBus, () => this.key())\n * .pipe(takeUntilDestroyed())\n * .subscribe(action => {\n * if (action.action === 'add') {\n * this.addItem(action.template, action.index);\n * } else {\n * this.removeItem(action.index);\n * }\n * });\n * ```\n */\nexport function observeArrayActions(eventBus: EventBus, arrayKey: () => string): Observable<ArrayAction> {\n return eventBus.on<ArrayEvent>(ARRAY_EVENT_TYPES).pipe(\n filter((event) => event.arrayKey === arrayKey()),\n map(toArrayAction),\n );\n}\n","import {\n ChangeDetectionStrategy,\n Component,\n computed,\n DestroyRef,\n EnvironmentInjector,\n inject,\n Injector,\n input,\n linkedSignal,\n Signal,\n signal,\n} from '@angular/core';\nimport { DfFieldOutlet } from '../../directives/df-field-outlet.directive';\nimport { takeUntilDestroyed } from '@angular/core/rxjs-interop';\nimport { catchError, firstValueFrom, forkJoin, map, Observable, of, tap } from 'rxjs';\nimport { explicitEffect } from 'ngxtension/explicit-effect';\nimport { ArrayField, ArrayItemDefinition, ArrayItemTemplate } from '../../definitions/default/array-field';\nimport { isGroupField } from '../../definitions/default/group-field';\nimport { injectFieldRegistry } from '../../utils/inject-field-registry/inject-field-registry';\nimport { FieldTree } from '@angular/forms/signals';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { getFieldDefaultValue } from '../../utils/default-value/default-value';\nimport { getFieldValueHandling } from '../../models/field-type';\nimport { emitComponentInitialized } from '../../utils/emit-initialization/emit-initialization';\nimport { EventBus } from '../../events/event.bus';\nimport { FieldSignalContext } from '../../mappers/types';\nimport {\n ARRAY_ITEM_ID_GENERATOR,\n ARRAY_TEMPLATE_REGISTRY,\n createArrayItemIdGenerator,\n FIELD_SIGNAL_CONTEXT,\n} from '../../models/field-signal-context.token';\nimport { determineDifferentialOperation, getArrayValue, ResolvedArrayItem } from '../../utils/array-field/array-field.types';\nimport { resolveArrayItem } from '../../utils/array-field/resolve-array-item';\nimport { observeArrayActions } from '../../utils/array-field/array-event-handler';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { ArrayFieldTree } from '../../core/field-tree-utils';\nimport { getNormalizedArrayMetadata } from '../../utils/array-field/normalized-array-metadata';\n\n/**\n * Container component for rendering dynamic arrays of fields.\n *\n * Supports add/remove/move operations via the arrayEvent() builder API.\n * Uses differential updates to optimize rendering - only recreates items when necessary.\n * Each item gets a scoped injector with ARRAY_CONTEXT for position-aware operations.\n * Supports multiple sibling fields per array item (e.g., name + email without a wrapper).\n */\n@Component({\n selector: 'array-field',\n imports: [DfFieldOutlet],\n template: `\n @for (item of resolvedItems(); track item.id; let i = $index) {\n <div\n class=\"df-array-item\"\n role=\"group\"\n [attr.aria-label]=\"'Item ' + (i + 1)\"\n [attr.data-array-item-id]=\"item.id\"\n [attr.data-array-item-index]=\"i\"\n >\n @for (field of item.fields; track $index) {\n <ng-container *dfFieldOutlet=\"field; environmentInjector: environmentInjector\" />\n }\n </div>\n }\n `,\n styleUrl: './array-field.component.scss',\n host: {\n '[class]': 'hostClasses()',\n '[class.df-container-hidden]': 'hidden()',\n '[attr.aria-hidden]': 'hidden() || null',\n '[id]': '`${key()}`',\n '[attr.data-testid]': 'key()',\n },\n providers: [\n // Each array gets its own template registry to track templates used for dynamically added items\n { provide: ARRAY_TEMPLATE_REGISTRY, useFactory: () => new Map<string, FieldDef<unknown>[]>() },\n // Each array gets its own ID generator for SSR hydration compatibility\n { provide: ARRAY_ITEM_ID_GENERATOR, useFactory: createArrayItemIdGenerator },\n ],\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport default class ArrayFieldComponent<TModel extends Record<string, unknown> = Record<string, unknown>> {\n // ─────────────────────────────────────────────────────────────────────────────\n // Dependencies\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly destroyRef = inject(DestroyRef);\n private readonly fieldRegistry = injectFieldRegistry();\n private readonly parentFieldSignalContext = inject(FIELD_SIGNAL_CONTEXT) as FieldSignalContext<TModel>;\n private readonly parentInjector = inject(Injector);\n protected readonly environmentInjector = inject(EnvironmentInjector);\n private readonly eventBus = inject(EventBus);\n private readonly logger = inject(DynamicFormLogger);\n private readonly templateRegistry = inject(ARRAY_TEMPLATE_REGISTRY);\n private readonly generateItemId = inject(ARRAY_ITEM_ID_GENERATOR);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Inputs\n // ─────────────────────────────────────────────────────────────────────────────\n\n field = input.required<ArrayField>();\n key = input.required<string>();\n className = input<string>();\n hidden = input(false);\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Computed Signals\n // ─────────────────────────────────────────────────────────────────────────────\n\n readonly hostClasses = computed(() => {\n const base = 'df-field df-array';\n const custom = this.className();\n return custom ? `${base} ${custom}` : base;\n });\n\n private readonly rawFieldRegistry = computed(() => this.fieldRegistry.raw);\n\n /**\n * Gets the auto-remove button FieldDef from normalization metadata.\n * Set by simplified array normalization for primitive arrays with remove buttons.\n * The button is rendered alongside each item without wrapping in a row,\n * preserving flat primitive form values.\n */\n private readonly autoRemoveButton = computed<FieldDef<unknown> | undefined>(() => {\n const metadata = getNormalizedArrayMetadata(this.field());\n return metadata?.autoRemoveButton;\n });\n\n /**\n * For primitive array items, the key of the value field template (e.g., 'value').\n * Used to wrap the FormControl in the item context so getFieldTree(key) works.\n * Returns undefined for object arrays (FormGroup items have natural child navigation).\n *\n * Detection order:\n * 1. Normalization metadata (for simplified arrays — always available at normalization time)\n * 2. Existing item definitions (non-empty full-API arrays)\n * 3. Dynamically discovered key from handleAddFromEvent (empty full-API arrays)\n *\n * Uses linkedSignal: recomputes when field() changes, supports manual set()\n * for the dynamic discovery case.\n */\n private readonly primitiveFieldKey = linkedSignal<string | undefined>(() => {\n // Priority 1: Normalization metadata (simplified arrays always have this)\n const metadata = getNormalizedArrayMetadata(this.field());\n if (metadata?.primitiveFieldKey) {\n return metadata.primitiveFieldKey;\n }\n\n // Priority 2: Existing item definitions (full-API arrays with initial items)\n const definitions = (this.field().fields as ArrayItemDefinition[]) || [];\n if (definitions.length > 0 && !Array.isArray(definitions[0])) {\n return (definitions[0] as FieldDef<unknown>).key;\n }\n\n return undefined;\n });\n\n /**\n * Normalized item templates WITHOUT auto-remove button appended.\n * Each element is normalized to an array: single FieldDef → [FieldDef], array stays as-is.\n *\n * Used by moveItem() to stash raw templates into the templateRegistry, preserving\n * the invariant that registry entries are pre-synthesis (withAutoRemove() adds the\n * button during resolution).\n */\n private readonly rawItemTemplates = computed<ArrayItemTemplate[]>(() => {\n const arrayField = this.field();\n const definitions = (arrayField.fields as ArrayItemDefinition[]) || [];\n\n return definitions.map((def) => {\n return (Array.isArray(def) ? def : [def]) as ArrayItemTemplate;\n });\n });\n\n /**\n * Resolves the effective fallback template for this array — used when the form\n * value contains an item with no registered template (i.e., items that were\n * neither added via event handlers nor covered by a positional entry in `fields`).\n *\n * Populated from `SimplifiedArrayField.template` via normalization metadata, so every\n * simplified array gets an automatic default. Returns undefined for full-API arrays;\n * `createResolveItemObservable` then falls back to warn-and-drop.\n *\n * Homogeneous arrays only — all fallback items receive the same template.\n */\n private readonly fallbackTemplate = computed<FieldDef<unknown>[] | undefined>(() => {\n const raw = getNormalizedArrayMetadata(this.field())?.template;\n if (!raw) return undefined;\n return (Array.isArray(raw) ? [...raw] : [raw]) as FieldDef<unknown>[];\n });\n\n /**\n * Gets the item templates (field definitions) for the array.\n * Each element can be either:\n * - A single FieldDef (primitive item) - normalized to [FieldDef]\n * - An array of FieldDefs (object item) - used as-is\n *\n * When auto-remove is configured, the remove button is appended to each item's\n * template list for rendering. This is purely visual — the form schema uses the\n * original primitive item definition (single FieldDef → FormControl → flat value).\n *\n * Returns normalized templates where all items are arrays for consistent handling.\n */\n private readonly itemTemplates = computed<ArrayItemTemplate[]>(() => {\n const raw = this.rawItemTemplates();\n const removeButton = this.autoRemoveButton();\n\n if (!removeButton) return raw;\n\n return raw.map((normalized) => {\n return [...normalized, removeButton] as unknown as ArrayItemTemplate;\n });\n });\n\n private readonly arrayFieldTrees = computed<readonly (FieldTree<unknown> | null)[]>(() => {\n const arrayKey = this.field().key;\n const parentForm = this.parentFieldSignalContext.form;\n const arrayValue = getArrayValue(this.parentFieldSignalContext.value(), arrayKey);\n\n if (arrayValue.length === 0) return [];\n\n const arrayFieldTree = (parentForm as Record<string, ArrayFieldTree<unknown>>)[arrayKey];\n if (!arrayFieldTree) return arrayValue.map(() => null);\n\n // Access array items via bracket notation - Angular Signal Forms arrays support this\n const items: (FieldTree<unknown> | null)[] = [];\n for (let i = 0; i < arrayValue.length; i++) {\n // Access item FieldTree directly via numeric indexing (ArrayFieldTree supports this)\n const itemFieldTree = arrayFieldTree[i];\n items.push(itemFieldTree ?? null);\n }\n\n return items;\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // State Signals\n // ─────────────────────────────────────────────────────────────────────────────\n\n private readonly resolvedItemsSignal = signal<ResolvedArrayItem[]>([]);\n private readonly updateVersion = signal(0);\n private readonly pendingInitializationCycle = signal<number | null>(null);\n private readonly settledInitializationCycle = signal<number | null>(null);\n\n /**\n * Map of item IDs to their current positions. O(1) lookup vs O(n) indexOf().\n * Used by child linkedSignals to reactively track their position in the array.\n */\n private readonly itemPositionMap = computed(() => {\n const items = this.resolvedItemsSignal();\n return new Map(items.map((item, idx) => [item.id, idx]));\n });\n\n /** Read-only view of resolved items for template consumption. */\n readonly resolvedItems = computed(() => this.resolvedItemsSignal());\n\n private readonly allResolvedFieldsRenderReady = computed(() =>\n this.resolvedItems().every((item) => item.fields.every((field) => field.renderReady())),\n );\n\n /**\n * Whether the array has reached its configured maxLength.\n * Exposed as a public signal so add-button components can bind [disabled]=\"atMaxLength()\".\n */\n readonly atMaxLength: Signal<boolean> = computed(() => {\n const maxLength = this.field().maxLength;\n if (maxLength === undefined) return false;\n const arrayKey = this.field().key;\n const currentArray = getArrayValue(this.parentFieldSignalContext.value(), arrayKey);\n return currentArray.length >= maxLength;\n });\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Auto-remove Cache\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Caches the result of appending the auto-remove button to template arrays.\n * Keyed by template array reference — cache hits occur during recreate/resolution\n * operations where stored template references are reused. Add operations via\n * handleAddFromEvent always create a fresh `[...template]` copy (line ~277),\n * so each add is a cache miss by design (the spread is needed for mutability).\n */\n private readonly autoRemoveCache = new WeakMap<readonly FieldDef<unknown>[], FieldDef<unknown>[]>();\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────────\n\n constructor() {\n this.setupEffects();\n this.setupEventHandlers();\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n private setupEffects(): void {\n // Sync field components when array data changes\n explicitEffect([this.arrayFieldTrees], ([fieldTrees]) => {\n this.performDifferentialUpdate(fieldTrees);\n });\n\n explicitEffect(\n [this.pendingInitializationCycle, this.settledInitializationCycle, this.allResolvedFieldsRenderReady],\n ([pending, settled, allReady]) => {\n if (pending !== null && settled === pending && allReady) {\n emitComponentInitialized(this.eventBus, 'array', this.field().key, this.parentInjector);\n this.pendingInitializationCycle.set(null);\n }\n },\n );\n }\n\n private setupEventHandlers(): void {\n observeArrayActions(this.eventBus, () => this.key())\n .pipe(takeUntilDestroyed())\n .subscribe((action) => {\n if (action.action === 'add') {\n // Template can be single FieldDef (primitive) or FieldDef[] (object)\n const templates = Array.isArray(action.template) ? action.template : action.template ? [action.template] : [];\n if (templates.length === 0) {\n this.logger.error(\n `Cannot add item to array '${this.key()}': template is REQUIRED. ` +\n 'Buttons must specify an explicit template property. ' +\n 'There is no default template - each add operation must provide its own.',\n );\n return;\n }\n void this.handleAddFromEvent(action.template, action.index);\n } else if (action.action === 'move') {\n this.moveItem(action.fromIndex, action.toIndex);\n } else {\n this.removeItem(action.index);\n }\n });\n }\n\n /**\n * Handles add operations from events (append, prepend, insert).\n * Creates resolved items FIRST, then updates form value.\n * This ensures prepend/insert work correctly - differential update sees \"none\"\n * because resolved items count already matches the new array length.\n *\n * Supports both primitive (single FieldDef) and object (FieldDef[]) templates.\n */\n private async handleAddFromEvent(template: FieldDef<unknown> | readonly FieldDef<unknown>[], index?: number): Promise<void> {\n // Normalize template to mutable array for consistent handling.\n // A single FieldDef with valueHandling: 'flatten' (container, row) is an object item\n // whose children should be flattened — NOT a primitive item. Only true leaf fields\n // (input, checkbox, etc.) are primitive when passed as a single FieldDef.\n const templates: FieldDef<unknown>[] = Array.isArray(template) ? [...template] : [template];\n const isSingleField = !Array.isArray(template);\n const isPrimitiveItem = isSingleField && getFieldValueHandling(templates[0].type, this.rawFieldRegistry()) !== 'flatten';\n\n // Track primitive field key for full-API arrays that start empty.\n // Simplified arrays already have this info from normalization metadata.\n if (isPrimitiveItem && templates[0].key && !this.primitiveFieldKey()) {\n this.primitiveFieldKey.set(templates[0].key);\n }\n\n if (templates.length === 0) {\n this.logger.error(\n `Cannot add item to array '${this.field().key}': no field templates provided. ` +\n 'Buttons must specify an explicit template property when adding array items.',\n );\n return;\n }\n\n const arrayKey = this.field().key;\n const parentForm = this.parentFieldSignalContext.form;\n const currentValue = parentForm().value() as TModel;\n const currentArray = getArrayValue(currentValue as Partial<TModel>, arrayKey);\n const insertIndex = index !== undefined ? Math.min(index, currentArray.length) : currentArray.length;\n\n // Compute default value\n let value: unknown;\n\n if (isPrimitiveItem) {\n // Primitive item: single field's value is extracted directly\n value = getFieldDefaultValue(templates[0], this.rawFieldRegistry());\n } else {\n // Object item: merge all template defaults into an object\n value = {};\n for (const templateField of templates) {\n const rawValue = getFieldDefaultValue(templateField, this.rawFieldRegistry());\n const valueHandling = getFieldValueHandling(templateField.type, this.rawFieldRegistry());\n const isContainer = templateField.type === 'group' || templateField.type === 'row' || templateField.type === 'container';\n\n if (isContainer) {\n if (isGroupField(templateField)) {\n // Groups wrap their fields under the group key\n value = { ...(value as Record<string, unknown>), [templateField.key]: rawValue };\n } else {\n // Rows and containers flatten their fields directly\n value = { ...(value as Record<string, unknown>), ...(rawValue as Record<string, unknown>) };\n }\n } else if (valueHandling === 'include' && templateField.key) {\n value = { ...(value as Record<string, unknown>), [templateField.key]: rawValue };\n }\n }\n }\n\n // Increment version and create resolved item BEFORE updating value\n this.updateVersion.update((v) => v + 1);\n const currentVersion = this.updateVersion();\n\n // Append auto-remove button to resolution templates (for rendering only)\n const resolveTemplates = this.withAutoRemove(templates);\n\n // Resolve the new item\n const resolvedItem = await firstValueFrom(\n resolveArrayItem({\n index: insertIndex,\n templates: resolveTemplates,\n arrayField: this.field(),\n itemPositionMap: this.itemPositionMap,\n parentFieldSignalContext: this.parentFieldSignalContext,\n parentInjector: this.parentInjector,\n registry: this.rawFieldRegistry(),\n destroyRef: this.destroyRef,\n loadTypeComponent: (type: string) => this.fieldRegistry.loadTypeComponent(type),\n generateItemId: this.generateItemId,\n primitiveFieldKey: isPrimitiveItem ? templates[0].key : undefined,\n }).pipe(\n catchError((error) => {\n this.logger.error(`Failed to resolve array item at index ${insertIndex}:`, error);\n return of(undefined);\n }),\n ),\n );\n\n if (currentVersion !== this.updateVersion() || !resolvedItem) {\n return;\n }\n\n // Store the template used for this item so it can be re-used during recreate operations\n this.templateRegistry.set(resolvedItem.id, templates);\n\n // Insert resolved item at correct position\n this.resolvedItemsSignal.update((current) => {\n const newItems = [...current];\n newItems.splice(insertIndex, 0, resolvedItem);\n return newItems;\n });\n\n // Update form value - differential update sees \"none\" (lengths match)\n const newArray = [...currentArray];\n newArray.splice(insertIndex, 0, value);\n // The `as any` is required because Angular Signal Forms uses complex conditional types\n // that cannot infer the correct type when setting a dynamically-keyed property\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parentForm().value.set({ ...currentValue, [arrayKey]: newArray } as any);\n }\n\n private performDifferentialUpdate(fieldTrees: readonly (FieldTree<unknown> | null)[]): void {\n const resolvedItems = this.resolvedItemsSignal();\n const operation = determineDifferentialOperation(resolvedItems, fieldTrees.length);\n\n // Only increment version for operations that do actual work.\n // \"none\" operations (value-only changes) should not interfere with async add operations.\n if (operation.type === 'none') {\n return;\n }\n\n this.updateVersion.update((v) => v + 1);\n const currentVersion = this.updateVersion();\n\n switch (operation.type) {\n case 'clear':\n // Clean up template registry when all items are removed\n this.templateRegistry.clear();\n this.resolvedItemsSignal.set([]);\n if (resolvedItems.length === 0 && this.pendingInitializationCycle() === null && this.settledInitializationCycle() === null) {\n this.pendingInitializationCycle.set(currentVersion);\n this.settledInitializationCycle.set(currentVersion);\n }\n break;\n case 'initial':\n this.pendingInitializationCycle.set(currentVersion);\n this.settledInitializationCycle.set(null);\n void this.resolveAllItems(fieldTrees, currentVersion);\n break;\n case 'append':\n void this.appendItems(fieldTrees, operation.startIndex, operation.endIndex, currentVersion);\n break;\n case 'recreate': {\n // Capture templates by item ID so each item is recreated with its original template,\n // even after move operations that change positions. Registry entries (from dynamic adds\n // or moves) take priority over positional itemTemplates lookup.\n const positionalTemplates: (FieldDef<unknown>[] | undefined)[] = resolvedItems.map((item) => {\n // Registry entries (from dynamic adds or moves) take priority;\n // unmoved initial items return undefined → falls through to itemTemplates[idx] during resolve.\n return this.templateRegistry.get(item.id);\n });\n\n this.resolvedItemsSignal.set([]);\n this.pendingInitializationCycle.set(currentVersion);\n this.settledInitializationCycle.set(null);\n void this.resolveAllItems(fieldTrees, currentVersion, positionalTemplates);\n break;\n }\n }\n }\n\n private async resolveAllItems(\n fieldTrees: readonly (FieldTree<unknown> | null)[],\n updateId: number,\n positionalTemplates?: (FieldDef<unknown>[] | undefined)[],\n ): Promise<void> {\n if (fieldTrees.length === 0) {\n this.resolvedItemsSignal.set([]);\n return;\n }\n\n // Wrap each item observable to catch individual errors\n const safeItemObservables = fieldTrees.map((_, i) =>\n this.createResolveItemObservable(i, positionalTemplates?.[i]).pipe(\n catchError((error) => {\n this.logger.error(`Failed to resolve array item at index ${i}:`, error);\n return of(undefined);\n }),\n ),\n );\n\n try {\n const items = await firstValueFrom(\n forkJoin(safeItemObservables).pipe(map((items) => items.filter((item): item is ResolvedArrayItem => item !== undefined))),\n );\n\n if (updateId === this.updateVersion()) {\n // Update template registry with new item IDs for dynamically added items\n if (positionalTemplates) {\n // Clean up old entries and add new ones\n const newItemIds = new Set(items.map((item) => item.id));\n for (const existingId of this.templateRegistry.keys()) {\n if (!newItemIds.has(existingId)) {\n this.templateRegistry.delete(existingId);\n }\n }\n items.forEach((item, idx) => {\n const template = positionalTemplates[idx];\n if (template) {\n this.templateRegistry.set(item.id, template);\n }\n });\n }\n this.resolvedItemsSignal.set(items);\n if (this.pendingInitializationCycle() === updateId) {\n this.settledInitializationCycle.set(updateId);\n }\n }\n } catch (err) {\n this.logger.error('Failed to resolve array items:', err);\n this.resolvedItemsSignal.set([]);\n }\n }\n\n private async appendItems(\n fieldTrees: readonly (FieldTree<unknown> | null)[],\n startIndex: number,\n endIndex: number,\n updateId: number,\n ): Promise<void> {\n const itemsToResolve = fieldTrees.slice(startIndex, endIndex);\n if (itemsToResolve.length === 0) return;\n\n // Wrap each item observable to catch individual errors\n const safeItemObservables = itemsToResolve.map((_, i) => {\n const index = startIndex + i;\n return this.createResolveItemObservable(index).pipe(\n catchError((error) => {\n this.logger.error(`Failed to resolve array item at index ${index}:`, error);\n return of(undefined);\n }),\n );\n });\n\n try {\n const newItems = await firstValueFrom(\n forkJoin(safeItemObservables).pipe(map((items) => items.filter((item): item is ResolvedArrayItem => item !== undefined))),\n );\n\n if (updateId === this.updateVersion()) {\n this.resolvedItemsSignal.update((current) => [...current, ...newItems]);\n }\n } catch (err) {\n this.logger.error('Failed to append array items:', err);\n }\n }\n\n /**\n * Creates an observable that resolves a single array item.\n *\n * Template resolution order:\n * 1. Use overrideTemplate if provided (from recreate with stored templates)\n * 2. Use itemTemplates[index] if within defined templates range\n * 3. Use the simplified-array fallback template (from normalization metadata) for\n * untracked items present in the form value (e.g., external `value.set`, parent\n * two-way binding, initial values beyond what was declared via simplified `value`).\n * Registers the resolved item in templateRegistry so subsequent recreates use\n * Priority 1.\n * 4. Return undefined (item cannot be resolved without a template)\n */\n private createResolveItemObservable(index: number, overrideTemplate?: FieldDef<unknown>[]): Observable<ResolvedArrayItem | undefined> {\n const itemTemplates = this.itemTemplates();\n const primitiveKey = this.primitiveFieldKey();\n\n // Priority 1: Use override template (from recreate with stored templates)\n if (overrideTemplate && overrideTemplate.length > 0) {\n return resolveArrayItem({\n index,\n templates: this.withAutoRemove(overrideTemplate),\n arrayField: this.field(),\n itemPositionMap: this.itemPositionMap,\n parentFieldSignalContext: this.parentFieldSignalContext,\n parentInjector: this.parentInjector,\n registry: this.rawFieldRegistry(),\n destroyRef: this.destroyRef,\n loadTypeComponent: (type: string) => this.fieldRegistry.loadTypeComponent(type),\n generateItemId: this.generateItemId,\n primitiveFieldKey: primitiveKey,\n });\n }\n\n // Priority 2: Use defined template at this index\n const templates = itemTemplates[index];\n if (templates && templates.length > 0) {\n return resolveArrayItem({\n index,\n templates: templates as FieldDef<unknown>[],\n arrayField: this.field(),\n itemPositionMap: this.itemPositionMap,\n parentFieldSignalContext: this.parentFieldSignalContext,\n parentInjector: this.parentInjector,\n registry: this.rawFieldRegistry(),\n destroyRef: this.destroyRef,\n loadTypeComponent: (type: string) => this.fieldRegistry.loadTypeComponent(type),\n generateItemId: this.generateItemId,\n primitiveFieldKey: primitiveKey,\n });\n }\n\n // Priority 3: Use the metadata fallback template for untracked items in the form value.\n // Homogeneous only — every fallback item receives the same template regardless of value shape.\n const fallback = this.fallbackTemplate();\n if (fallback && fallback.length > 0) {\n return resolveArrayItem({\n index,\n templates: this.withAutoRemove(fallback),\n arrayField: this.field(),\n itemPositionMap: this.itemPositionMap,\n parentFieldSignalContext: this.parentFieldSignalContext,\n parentInjector: this.parentInjector,\n registry: this.rawFieldRegistry(),\n destroyRef: this.destroyRef,\n loadTypeComponent: (type: string) => this.fieldRegistry.loadTypeComponent(type),\n generateItemId: this.generateItemId,\n primitiveFieldKey: primitiveKey,\n }).pipe(\n tap((item) => {\n // Register the fallback template against the generated item id so subsequent\n // recreates hit Priority 1 instead of re-resolving via this branch.\n if (item) this.templateRegistry.set(item.id, fallback);\n }),\n );\n }\n\n // Priority 4: no template available. Full-API arrays are positional by design —\n // `fields` declares one template per item, so values extending past `fields.length`\n // (e.g., from external `value.set`, parent two-way binding, or initial values on a\n // `fields: []` array) have no template to render. Use the simplified array API\n // (`template` + `value`) when you need homogeneous arrays with value-driven items.\n this.logger.warn(\n `No template found for array item at index ${index}. This likely occured for a Full-API array element that was created from the DynamicForm's value being set directly, which is currently not supported. Consider using the simplified array API.`,\n );\n return of(undefined);\n }\n\n /**\n * Appends the auto-remove button to a templates array for rendering.\n * The button is added for visual rendering only — it doesn't affect the form schema.\n * Original templates are stored in templateRegistry WITHOUT the remove button,\n * so this method is called during resolution to add it dynamically.\n *\n * Uses a WeakMap cache keyed by template array reference. Cache hits occur\n * during recreate/resolution paths where stored templates are reused.\n * Add operations always pass a fresh `[...template]` copy, so they miss\n * the cache intentionally (the copy is needed for mutable item construction).\n */\n private withAutoRemove(templates: FieldDef<unknown>[]): FieldDef<unknown>[] {\n const removeButton = this.autoRemoveButton();\n if (!removeButton) return templates;\n\n let cached = this.autoRemoveCache.get(templates);\n if (cached) return cached;\n\n cached = [...templates, removeButton];\n this.autoRemoveCache.set(templates, cached);\n return cached;\n }\n\n /**\n * Handles move operations — reorders an existing item without destroying it.\n * Updates resolvedItems and form value atomically. Since the array length\n * doesn't change, `determineDifferentialOperation` returns 'none' and no\n * recreate is triggered. The `@for` loop tracks by `item.id`, so Angular\n * moves the DOM node instead of destroying/recreating. The `itemPositionMap`\n * computed auto-recomputes, propagating new indices to child linkedSignals.\n */\n private moveItem(fromIndex: number, toIndex: number): void {\n const arrayKey = this.field().key;\n const parentForm = this.parentFieldSignalContext.form;\n const currentValue = parentForm().value() as TModel;\n const currentArray = getArrayValue(currentValue as Partial<TModel>, arrayKey);\n const length = currentArray.length;\n\n if (fromIndex < 0 || fromIndex >= length) {\n this.logger.warn(\n `moveArrayItem fromIndex ${fromIndex} is out of bounds for array '${arrayKey}' with length ${length}. Operation skipped.`,\n );\n return;\n }\n\n if (toIndex < 0 || toIndex >= length) {\n this.logger.warn(\n `moveArrayItem toIndex ${toIndex} is out of bounds for array '${arrayKey}' with length ${length}. Operation skipped.`,\n );\n return;\n }\n\n if (fromIndex === toIndex) return;\n\n // Register raw (pre-auto-remove) templates for all items whose position will change.\n // Initial items use itemTemplates[currentIndex] during recreate, but after\n // a move their position no longer matches their original template. Stashing\n // the template by item ID lets the recreate path resolve the correct one.\n // We use rawItemTemplates (without auto-remove button) because the recreate path\n // calls withAutoRemove() during resolution — storing the synthesized version would\n // cause duplicate remove buttons.\n const rawTemplates = this.rawItemTemplates();\n const currentItems = this.resolvedItemsSignal();\n const lo = Math.min(fromIndex, toIndex);\n const hi = Math.max(fromIndex, toIndex);\n for (let i = lo; i <= hi; i++) {\n const item = currentItems[i];\n if (item && !this.templateRegistry.has(item.id) && i < rawTemplates.length) {\n this.templateRegistry.set(item.id, rawTemplates[i] as FieldDef<unknown>[]);\n }\n }\n\n // Reorder resolvedItems — splice preserves object identity (no destroy/recreate)\n this.resolvedItemsSignal.update((current) => {\n const newItems = [...current];\n const [moved] = newItems.splice(fromIndex, 1);\n newItems.splice(toIndex, 0, moved);\n return newItems;\n });\n\n // Reorder form value array the same way\n const newArray = [...currentArray];\n const [movedValue] = newArray.splice(fromIndex, 1);\n newArray.splice(toIndex, 0, movedValue);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parentForm().value.set({ ...currentValue, [arrayKey]: newArray } as any);\n }\n\n /**\n * Handles remove operations from events (pop, shift, removeAt).\n * Updates resolvedItems FIRST, then form value - this ensures differential\n * update sees \"none\" (lengths match) and avoids unnecessary recreates.\n * Remaining items' linkedSignal indices auto-update via itemPositionMap.\n */\n private removeItem(index?: number): void {\n const arrayKey = this.field().key;\n const parentForm = this.parentFieldSignalContext.form;\n const currentValue = parentForm().value() as TModel;\n const currentArray = getArrayValue(currentValue as Partial<TModel>, arrayKey);\n\n if (currentArray.length === 0) return;\n\n // When index is undefined or -1, remove the last item.\n let removeIndex: number;\n if (index === undefined || index === -1) {\n removeIndex = currentArray.length - 1;\n } else if (index < -1 || index >= currentArray.length) {\n this.logger.warn(\n `removeArrayItem index ${index} is out of bounds for array '${arrayKey}' with length ${currentArray.length}. Operation skipped.`,\n );\n return;\n } else {\n removeIndex = index;\n }\n\n // Update resolvedItems FIRST - remove the item at the specified index.\n // This ensures differential update sees \"none\" (lengths already match).\n // Remaining items' linkedSignal indices auto-update via itemPositionMap.\n //\n // When the item is removed from resolvedItemsSignal, the @for loop removes the DOM element\n // and NgComponentOutlet destroys the component view, triggering DestroyRef callbacks.\n // Async validators use Angular's resource API tied to the form-level schema path — when the\n // array value is updated below, the resource's params re-evaluate. If the removed item's path\n // no longer exists, params returns undefined, cancelling the pending validation automatically.\n const removedItem = this.resolvedItemsSignal()[removeIndex];\n if (removedItem) {\n this.templateRegistry.delete(removedItem.id);\n }\n this.resolvedItemsSignal.update((current) => {\n const newItems = [...current];\n newItems.splice(removeIndex, 1);\n return newItems;\n });\n\n // Update the parent form with the new array value\n const newArray = [...currentArray];\n newArray.splice(removeIndex, 1);\n\n // The `as any` is required due to Angular Signal Forms' complex conditional types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parentForm().value.set({ ...currentValue, [arrayKey]: newArray } as any);\n }\n}\n\nexport { ArrayFieldComponent };\n","import {\n ChangeDetectionStrategy,\n Component,\n computed,\n DestroyRef,\n EnvironmentInjector,\n inject,\n Injector,\n input,\n TemplateRef,\n viewChild,\n ViewContainerRef,\n} from '@angular/core';\nimport { DfFieldOutlet } from '../../directives/df-field-outlet.directive';\nimport { derivedFromDeferred } from '../../utils/derived-from-deferred/derived-from-deferred';\nimport { createFieldResolutionPipe, ResolvedField } from '../../utils/resolve-field/resolve-field';\nimport { computeContainerHostClasses, setupContainerInitEffect } from '../../utils/container-utils/container-utils';\nimport { ContainerField } from '../../definitions/default/container-field';\nimport { injectFieldRegistry } from '../../utils/inject-field-registry/inject-field-registry';\nimport { EventBus } from '../../events/event.bus';\nimport { FieldDef } from '../../definitions/base/field-def';\nimport { DynamicFormLogger } from '../../providers/features/logger/logger.token';\nimport { WRAPPER_AUTO_ASSOCIATIONS } from '../../models/wrapper-type';\nimport { DEFAULT_WRAPPERS } from '../../models/field-signal-context.token';\nimport { isSameWrapperChain, resolveWrappers } from '../../utils/resolve-wrappers/resolve-wrappers';\nimport { createWrapperChainController } from '../../utils/wrapper-chain/wrapper-chain-controller';\n\n/**\n * Layout container that wraps child fields with UI chrome.\n *\n * Resolves children like a row, then chains wrapper components around them\n * using imperative `ViewContainerRef.createComponent()` — each wrapper's\n * `#fieldComponent` slot hosts the next wrapper or the children template.\n *\n * Does not create a new form context - fields share the parent's context.\n * Field values are flattened into the parent form (no nesting under container key).\n * Purely a visual/layout container with no impact on form structure.\n */\n@Component({\n selector: 'div[container-field]',\n imports: [DfFieldOutlet],\n template: `\n <ng-template #childrenTpl>\n @for (field of resolvedFields(); track field.key) {\n <ng-container *dfFieldOutlet=\"field; environmentInjector: environmentInjector\" />\n }\n </ng-template>\n <ng-container #wrapperContainer></ng-container>\n `,\n styleUrl: './container-field.component.scss',\n host: {\n '[class]': 'hostClasses()',\n '[class.disabled]': 'disabled()',\n '[class.df-container-hidden]': 'hidden()',\n '[attr.aria-hidden]': 'hidden() || null',\n '[id]': '`${key()}`',\n '[attr.data-testid]': 'key()',\n },\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport default class ContainerFieldComponent {\n private readonly destroyRef = inject(DestroyRef);\n private readonly fieldRegistry = injectFieldRegistry();\n private readonly injector = inject(Injector);\n protected readonly environmentInjector = inject(EnvironmentInjector);\n private readonly eventBus = inject(EventBus);\n private readonly logger = inject(DynamicFormLogger);\n private readonly wrapperAutoAssociations = inject(WRAPPER_AUTO_ASSOCIATIONS);\n private readonly defaultWrappersSignal = inject(DEFAULT_WRAPPERS, { optional: true });\n\n private readonly childrenTpl = viewChild.required('childrenTpl', { read: TemplateRef });\n private readonly wrapperContainer = viewChild.required('wrapperContainer', { read: ViewContainerRef });\n\n field = input.required<ContainerField>();\n key = input.required<string>();\n className = input<string>();\n hidden = input(false);\n\n readonly hostClasses = computed(() => computeContainerHostClasses('container', this.className()));\n readonly disabled = computed(() => this.field().disabled || false);\n\n private readonly rawFieldRegistry = computed(() => this.fieldRegistry.raw);\n private readonly fieldsSource = computed(() => (this.field().fields || []) as FieldDef<unknown>[]);\n\n protected readonly resolvedFields = derivedFromDeferred(\n this.fieldsSource,\n createFieldResolutionPipe(() => ({\n loadTypeComponent: (type: string) => this.fieldRegistry.loadTypeComponent(type),\n registry: this.rawFieldRegistry(),\n injector: this.injector,\n destroyRef: this.destroyRef,\n onError: (fieldDef: FieldDef<unknown>, error: unknown) => {\n const fieldKey = fieldDef.key || '<no key>';\n\n const containerKey = this.field().key || '<no key>';\n this.logger.error(\n `Failed to load component for field type '${fieldDef.type}' (key: ${fieldKey}) ` +\n `within container '${containerKey}'. Ensure the field type is registered in your field registry.`,\n error,\n );\n },\n })),\n { initialValue: [] as ResolvedField[], injector: this.injector },\n );\n\n private readonly wrappers = computed(() => resolveWrappers(this.field(), this.defaultWrappersSignal?.(), this.wrapperAutoAssociations), {\n equal: isSameWrapperChain,\n });\n\n constructor() {\n // `row` is a virtual field type backed by ContainerFieldComponent — at\n // runtime the spread in rowFieldMapper preserves `type: 'row'` on the\n // field input, even though the declared type is `ContainerField`. Widen\n // here so `(events)` consumers filtering by `componentType === 'row'`\n // keep receiving emissions.\n setupContainerInitEffect(\n this.resolvedFields,\n this.eventBus,\n () => ((this.field().type as string) === 'row' ? 'row' : 'container'),\n () => this.field().key,\n this.injector,\n );\n\n createWrapperChainController({\n vcr: this.wrapperContainer,\n wrappers: this.wrappers,\n renderInnermost: (slot) => slot.createEmbeddedView(this.childrenTpl()),\n });\n }\n}\n\nexport { ContainerFieldComponent };\n","import { ValidationError } from '../models/validation-types';\n\n/**\n * Interpolates {{param}} placeholders in message with error values\n *\n * @param message - Message template with {{param}} placeholders\n * @param error - Validation error containing parameter values\n * @returns Message with interpolated parameters\n *\n * @example\n * interpolateParams(\"Min value is {{min}}\", { kind: 'min', min: 5 })\n * // Returns: \"Min value is 5\"\n */\nexport function interpolateParams(message: string, error: ValidationError): string {\n let result = message;\n const params = extractErrorParams(error);\n\n Object.entries(params).forEach(([key, value]) => {\n const placeholder = new RegExp(`{{\\\\s*${key}\\\\s*}}`, 'g');\n result = result.replace(placeholder, safeToString(value));\n });\n\n return result;\n}\n\n/**\n * Safely converts a value to a string, handling complex objects\n * @internal\n */\nfunction safeToString(value: unknown): string {\n if (value === null || value === undefined) {\n return '';\n }\n\n // Handle primitives directly\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n\n // Handle RegExp (has its own toString)\n if (value instanceof RegExp) {\n return value.toString();\n }\n\n // Handle Date\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n return value.join(', ');\n }\n\n // For objects, try JSON.stringify first, fall back to empty string\n try {\n // Check if object has a custom toString that's not Object.prototype.toString\n if (typeof value === 'object' && value.toString !== Object.prototype.toString) {\n return value.toString();\n }\n // Otherwise use JSON representation\n return JSON.stringify(value);\n } catch {\n // If JSON.stringify fails (circular reference, etc.), return empty string\n return '[object]';\n }\n}\n\n/**\n * Extracts parameter values from validation error\n * @internal\n */\nfunction extractErrorParams(error: ValidationError): Record<string, unknown> {\n const params: Record<string, unknown> = {};\n\n // Common validation error parameters\n if ('min' in error) params.min = error.min;\n if ('max' in error) params.max = error.max;\n if ('pattern' in error) params.pattern = error.pattern;\n if ('actual' in error) params.actual = error.actual;\n if ('expected' in error) params.expected = error.expected;\n\n // Handle length validation parameters\n // Angular Signal Forms uses 'minLength'/'maxLength' properties\n // Angular Classic Forms uses 'requiredLength'/'actualLength' properties\n // We support both formats and normalize to 'requiredLength' for message templates\n if ('requiredLength' in error) {\n params.requiredLength = error.requiredLength;\n } else if ('minLength' in error) {\n // Angular Signal Forms: minLength property maps to requiredLength for templates\n params.requiredLength = error.minLength;\n params.minLength = error.minLength;\n } else if ('maxLength' in error) {\n // Angular Signal Forms: maxLength property maps to requiredLength for templates\n params.requiredLength = error.maxLength;\n params.maxLength = error.maxLength;\n }\n if ('actualLength' in error) params.actualLength = error.actualLength;\n\n // Include all custom properties from error object (for custom validators)\n // Skip 'kind' as it's the error type identifier, not a parameter\n Object.keys(error).forEach((key) => {\n if (key !== 'kind' && !(key in params)) {\n params[key] = error[key as keyof ValidationError];\n }\n });\n\n return params;\n}\n","/**\n * @ng-forge/dynamic-forms\n *\n * Dynamic forms library for Angular applications.\n *\n * ## Public API (for end users)\n * - DynamicForm component\n * - provideDynamicForm() for configuration\n * - FormConfig and field definition types\n * - Event classes (SubmitEvent, PageChangeEvent, etc.)\n *\n * ## Integration API (for UI library authors)\n * Import from '@ng-forge/dynamic-forms/integration' for:\n * - Specific field types (InputField, SelectField, etc.)\n * - Field mappers (valueFieldMapper, checkboxFieldMapper, etc.)\n * - Error utilities (createResolvedErrorsSignal, shouldShowErrors)\n *\n */\n\n// ============================================================\n// PUBLIC API - For end users\n// ============================================================\n\n// Core Component\nexport { DynamicForm } from './dynamic-form.component';\n\n// External event dispatcher — use this to dispatch events FROM OUTSIDE DynamicForm\n// (host components, parent services). For dispatching from inside a field component,\n// inject EventBus directly (it is scoped to the form's DI tree).\nexport { EventDispatcher } from './events/event-dispatcher';\n\n// Provider System\nexport { provideDynamicForm } from './providers';\nexport type { ExtractFieldDefs, ExtractFormValue } from './providers';\n\n// Logger Feature\nexport { withLoggerConfig } from './providers/features/logger/with-logger-config';\nexport { DynamicFormLogger } from './providers/features/logger/logger.token';\nexport type { Logger } from './providers/features/logger';\nexport { ConsoleLogger } from './providers/features/logger/console-logger';\nexport { NoopLogger } from './providers/features/logger/noop-logger';\n\n// Event Form Value Feature\nexport { withEventFormValue } from './providers/features/event-form-value';\nexport { hasFormValue } from './events/interfaces/form-event';\n\n// Value Exclusion Feature\nexport { withValueExclusionDefaults } from './providers/features/value-exclusion';\nexport type { ValueExclusionConfig, ResolvedValueExclusionConfig } from './models/value-exclusion-config';\n\n// Wrapper Types\nexport type { WrapperTypeDefinition, FieldWrapperContract } from './models/wrapper-type';\nexport { isWrapperTypeDefinition, WRAPPER_REGISTRY } from './models/wrapper-type';\n\n// Wrapper Registration DX\nexport { wrapperProps } from './wrappers/wrapper-props';\nexport { createWrappers, isWrappersBundle } from './wrappers/create-wrappers';\nexport type { WrapperRegistration, WrappersBundle, InferWrapperRegistry } from './wrappers/create-wrappers';\n\n// Configuration Types\nexport type { CustomFnConfig, FormConfig, FormOptions } from './models';\nexport type { DynamicText, FieldOption, ValidationError, ValidationMessages } from './models';\n\n// Submission Config\nexport type { SubmissionConfig, SubmissionActionResult, SubmitButtonOptions, NextButtonOptions } from './models';\n\n// Form State Condition\nexport type { FormStateCondition } from './models';\nexport { isFormStateCondition } from './models';\n\n// Logic Resolvers\nexport {\n resolveSubmitButtonDisabled,\n resolveNextButtonDisabled,\n resolveNonFieldHidden,\n resolveNonFieldDisabled,\n evaluateNonFieldHidden,\n evaluateNonFieldDisabled,\n} from './core/logic';\nexport type { ButtonLogicContext, NonFieldLogicContext, NonFieldLogicType, NonFieldLogicConfig } from './core/logic';\n\n// Abstract Base Field Types (for extension by UI libraries)\nexport type {\n BaseCheckedField,\n BaseValueField,\n CheckedFieldComponent,\n FieldComponent,\n FieldDef,\n FieldMeta,\n FieldWithValidation,\n ValueFieldComponent,\n ValueType,\n} from './definitions';\nexport { isCheckedField, isValueField } from './definitions';\n\n// Built-in Container Field Types\nexport type {\n ArrayButtonConfig,\n ArrayField,\n GroupField,\n PageField,\n RowField,\n SimplifiedArrayField,\n TextField,\n TextElementType,\n TextProps,\n ContainerField,\n WrapperConfig,\n CssWrapper,\n} from './definitions/default';\nexport { isRowField, isSimplifiedArrayField, isContainerTypedField } from './definitions/default';\n\n// Validation Config Types\nexport type {\n AsyncValidatorConfig,\n BaseValidatorConfig,\n BuiltInValidatorConfig,\n CustomValidatorConfig,\n DeclarativeHttpValidatorConfig,\n ValidatorConfig,\n} from './models';\n\n// HTTP Config Types\nexport type { HttpRequestConfig, HttpValidationResponseMapping } from './models';\n\n// Validator Function Types (for customFnConfig)\nexport type { AsyncCustomValidator, CustomValidator, HttpCustomValidator } from './core/validation';\n\n// Logic & Expression Types\nexport type { ConditionalExpression, HttpCondition, AsyncCondition, EvaluationContext, LogicConfig, StateLogicConfig } from './models';\n\n// Async Custom Function Types\nexport type { AsyncDerivationFunction, AsyncConditionFunction } from './core/expressions/async-custom-function-types';\n\n// Schema Types\nexport type { SchemaApplicationConfig, SchemaDefinition } from './models';\n\n// Registry Types (for module augmentation)\nexport type {\n AvailableFieldTypes,\n ContainerFieldTypes,\n DynamicFormFieldRegistry,\n ExtractField,\n FieldRegistryContainers,\n FieldRegistryLeaves,\n FieldRegistryWrappers,\n LeafFieldTypes,\n NarrowField,\n NarrowFields,\n RegisteredFieldTypes,\n} from './models';\n\n// Utility Types\nexport type {\n ArrayAllowedChildren,\n FieldPathAccess,\n FormMode,\n FormModeDetectionResult,\n GroupAllowedChildren,\n InferFormValue,\n PageAllowedChildren,\n Prettify,\n RowAllowedChildren,\n WithInputSignals,\n} from './models';\n\n// Type Guards\nexport { isArrayField, isContainerField, isDisplayOnlyField, isGroupField, isLeafField, isPageField, isValueBearingField } from './models';\n\n// Events\nexport {\n AppendArrayItemEvent,\n FormClearEvent,\n FormResetEvent,\n InsertArrayItemEvent,\n MoveArrayItemEvent,\n NextPageEvent,\n PageChangeEvent,\n PopArrayItemEvent,\n PrependArrayItemEvent,\n PreviousPageEvent,\n RemoveAtIndexEvent,\n ShiftArrayItemEvent,\n SubmitEvent,\n} from './events';\n\n// Array event builder (recommended public API)\nexport { arrayEvent } from './events';\nexport type { ArrayItemTemplate, ArrayItemDefinitionTemplate } from './events';\n\nexport type { FormEvent, FormEventConstructor, TokenContext, ArrayItemContext } from './events';\n\n// Helpers\nexport { createField, field, formConfig } from './helpers';\n\n// Errors\nexport { DynamicFormError } from './errors/dynamic-form-error';\n\n// ============================================================\n// INTERNAL EXPORTS - Used by integration entrypoint\n// These are stable APIs for UI library authors\n// ============================================================\n\n// Base mapper utilities\nexport { baseFieldMapper, buildBaseInputs } from './mappers';\nexport { arrayFieldMapper, groupFieldMapper, pageFieldMapper, rowFieldMapper, textFieldMapper, containerFieldMapper } from './mappers';\nexport type { ArrayContext, FieldSignalContext, MapperFn } from './mappers';\n\n// Field Type Definition - for registering custom field types\nexport type { FieldScope, FieldTypeDefinition, ValueHandlingMode } from './models';\nexport { FIELD_REGISTRY } from './models';\n\n// Signal Context - injection tokens for field components\nexport { ARRAY_CONTEXT, DEFAULT_PROPS, DEFAULT_VALIDATION_MESSAGES, DEFAULT_WRAPPERS, FIELD_SIGNAL_CONTEXT, FORM_OPTIONS } from './models';\n\n// Dynamic Text utilities\nexport { dynamicTextToObservable } from './utils';\nexport { DynamicTextPipe } from './pipes';\n\n// Container Components - for building custom containers\nexport { ArrayFieldComponent, GroupFieldComponent, ContainerFieldComponent } from './fields';\n\n// Validation utilities\nexport { applyValidator, applyValidators } from './core/validation';\nexport type { HttpResourceRequest } from './core/validation';\n\n// FieldTree Utilities\nexport { getArrayLength, toReadonlyFieldTree } from './core/field-tree-utils';\nexport type { ArrayFieldTree, ReadonlyFieldTree } from './core/field-tree-utils';\nexport type { WrapperFieldInputs } from './wrappers/wrapper-field-inputs';\n\n// EventBus — inject inside field components (scoped to the form's DI tree).\n// To dispatch from outside DynamicForm, use EventDispatcher instead.\nexport { EventBus, resolveTokens } from './events';\n\n// Registry Utilities\nexport { BUILT_IN_FIELDS } from './providers';\n\n// Object utilities (used by integration mappers)\nexport { isEqual, omit } from './utils/object-utils';\n\n// Interpolation utility (used by integration error utilities)\nexport { interpolateParams } from './utils/interpolate-params';\n\n// Meta utilities (used by UI library wrapped-meta directives)\nexport { applyMetaToElement } from './utils/apply-meta';\n\n// Registry services (used by UI library button mappers)\nexport { RootFormRegistryService } from './core/registry/root-form-registry.service';\n\n// Field State types (for consumers writing custom expressions)\nexport type { FieldStateInfo, FieldStateContext, FormFieldStateMap } from './models/expressions/field-state-context';\n\n// Configuration tokens — override defaults via provideDynamicForm() or Angular DI\nexport { INITIALIZATION_TIMEOUT_MS } from './utils/initialization-tracker/initialization-tracker';\n\n// Resource Composition Utilities (experimental — uses Angular's experimental resource composition APIs)\nexport { withPreviousValue } from './utils/resource-composition/with-previous-value';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":["map","filter","switchMap","catchError","isContainerWithFields","CONTAINER_TYPES","MAX_AST_CACHE_SIZE","ERROR_PREFIX","getEntriesForChangedFields","createEvaluationContext","createArrayItemEvaluationContext","traverseFields","collectFromField","extractDependencies","take","LOG_PREFIX","scan"],"mappings":";;;;;;;;;;;AA8EA;;;;AAIG;AACG,SAAU,uBAAuB,CAAC,KAAc,EAAA;AACpD,IAAA,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,aAAa,IAAI,KAAK;AAC9E;AAkCA;;;;;;AAMG;MACU,gBAAgB,GAAG,IAAI,cAAc,CAAqC,kBAAkB,EAAE;AACzG,IAAA,UAAU,EAAE,MAAM;AAClB,IAA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