@wix/bex-core 2.400.0 → 2.402.0

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.
Files changed (61) hide show
  1. package/dist/cjs/hooks/useImport.js +7 -0
  2. package/dist/cjs/hooks/useImport.js.map +1 -1
  3. package/dist/cjs/state/ImportState/ImportState.js +188 -51
  4. package/dist/cjs/state/ImportState/ImportState.js.map +1 -1
  5. package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js +551 -0
  6. package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
  7. package/dist/cjs/state/ImportState/__tests__/buildImportConfig.spec.js +30 -4
  8. package/dist/cjs/state/ImportState/__tests__/buildImportConfig.spec.js.map +1 -1
  9. package/dist/cjs/state/ImportState/__tests__/importFieldCompatibility.spec.js +91 -0
  10. package/dist/cjs/state/ImportState/__tests__/importFieldCompatibility.spec.js.map +1 -0
  11. package/dist/cjs/state/ImportState/detectFieldType.js +3 -3
  12. package/dist/cjs/state/ImportState/detectFieldType.js.map +1 -1
  13. package/dist/cjs/state/ImportState/findExistingImportIds.js +35 -0
  14. package/dist/cjs/state/ImportState/findExistingImportIds.js.map +1 -0
  15. package/dist/cjs/state/ImportState/importFieldCompatibility.js +92 -0
  16. package/dist/cjs/state/ImportState/importFieldCompatibility.js.map +1 -0
  17. package/dist/cjs/state/ImportState/importSampling.js +6 -0
  18. package/dist/cjs/state/ImportState/importSampling.js.map +1 -0
  19. package/dist/cjs/state/ImportState/index.js.map +1 -1
  20. package/dist/cjs/types/Field.js.map +1 -1
  21. package/dist/cjs/types/FieldTypeDefinition.js.map +1 -1
  22. package/dist/esm/hooks/useImport.js +7 -1
  23. package/dist/esm/hooks/useImport.js.map +1 -1
  24. package/dist/esm/state/ImportState/ImportState.js +180 -51
  25. package/dist/esm/state/ImportState/ImportState.js.map +1 -1
  26. package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js +421 -2
  27. package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
  28. package/dist/esm/state/ImportState/__tests__/buildImportConfig.spec.js +32 -4
  29. package/dist/esm/state/ImportState/__tests__/buildImportConfig.spec.js.map +1 -1
  30. package/dist/esm/state/ImportState/__tests__/importFieldCompatibility.spec.js +99 -0
  31. package/dist/esm/state/ImportState/__tests__/importFieldCompatibility.spec.js.map +1 -0
  32. package/dist/esm/state/ImportState/detectFieldType.js +3 -3
  33. package/dist/esm/state/ImportState/detectFieldType.js.map +1 -1
  34. package/dist/esm/state/ImportState/findExistingImportIds.js +24 -0
  35. package/dist/esm/state/ImportState/findExistingImportIds.js.map +1 -0
  36. package/dist/esm/state/ImportState/importFieldCompatibility.js +102 -0
  37. package/dist/esm/state/ImportState/importFieldCompatibility.js.map +1 -0
  38. package/dist/esm/state/ImportState/importSampling.js +2 -0
  39. package/dist/esm/state/ImportState/importSampling.js.map +1 -0
  40. package/dist/esm/state/ImportState/index.js.map +1 -1
  41. package/dist/esm/types/FieldTypeDefinition.js.map +1 -1
  42. package/dist/types/hooks/useImport.d.ts +7 -3
  43. package/dist/types/hooks/useImport.d.ts.map +1 -1
  44. package/dist/types/state/ImportState/ImportState.d.ts +20 -8
  45. package/dist/types/state/ImportState/ImportState.d.ts.map +1 -1
  46. package/dist/types/state/ImportState/__tests__/importFieldCompatibility.spec.d.ts +2 -0
  47. package/dist/types/state/ImportState/__tests__/importFieldCompatibility.spec.d.ts.map +1 -0
  48. package/dist/types/state/ImportState/detectFieldType.d.ts.map +1 -1
  49. package/dist/types/state/ImportState/findExistingImportIds.d.ts +3 -0
  50. package/dist/types/state/ImportState/findExistingImportIds.d.ts.map +1 -0
  51. package/dist/types/state/ImportState/importFieldCompatibility.d.ts +4 -0
  52. package/dist/types/state/ImportState/importFieldCompatibility.d.ts.map +1 -0
  53. package/dist/types/state/ImportState/importSampling.d.ts +2 -0
  54. package/dist/types/state/ImportState/importSampling.d.ts.map +1 -0
  55. package/dist/types/state/ImportState/index.d.ts +1 -0
  56. package/dist/types/state/ImportState/index.d.ts.map +1 -1
  57. package/dist/types/types/Field.d.ts +4 -0
  58. package/dist/types/types/Field.d.ts.map +1 -1
  59. package/dist/types/types/FieldTypeDefinition.d.ts +3 -2
  60. package/dist/types/types/FieldTypeDefinition.d.ts.map +1 -1
  61. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"names":["isFilterTypeConfig","filter","defineFieldType","definition","resolveFieldTypeDefinition","source","field","_source$fieldTypes","type","customType","undefined","fieldTypes","find","def"],"sources":["../../../src/types/FieldTypeDefinition.ts"],"sourcesContent":["import type {\n ComponentType,\n MutableRefObject,\n ReactElement,\n ReactNode,\n} from 'react';\nimport type { Field } from './Field';\nimport type { Filter } from '../model/filter';\nimport type {\n FieldModalCollectionInput,\n FieldPiiWarning,\n FieldSettingsSection,\n FieldsSource,\n} from './FieldsSource';\n\nexport type ValidationRule =\n | { type: 'required'; message: string }\n | { type: 'min' | 'max'; value: number; message: string }\n | { type: 'minLength' | 'maxLength'; value: number; message: string }\n | { type: 'pattern'; value: RegExp; message: string }\n | { type: 'custom'; validate: (value: unknown) => boolean; message: string }\n | {\n type: 'specificValues';\n values: { id: string; value: string }[];\n message: string;\n };\n\nexport interface Focusable {\n focus: () => void;\n}\n\nexport type EditTrigger =\n | { kind: 'type'; key: string }\n | 'enter'\n | 'click'\n | 'doubleClick';\n\nexport interface CellViewProps<V> {\n value: V;\n typeConfig?: unknown;\n validation?: ValidationRule[];\n /** Stable id of the column. Cell components can use it to derive unique DOM ids. */\n columnId: string;\n /** Stable key of the row. Cell components can use it to derive unique DOM ids. */\n rowKey: string;\n /** Whether the cell is editable. Used to conditionally render placeholders (don't show them for read-only cells). */\n isEditable?: boolean;\n}\n\nexport interface CellEditProps<V> {\n value: V;\n // Method syntax keeps CellEditProps covariant in V (see FieldTypeDefinition).\n onChange(value: V): void;\n onCommit: () => void;\n onCancel: () => void;\n /**\n * Signals that the cell is starting an editing operation that will move focus\n * outside the table (e.g., opening a media manager or a modal). Calling this\n * sets isEditing=true so the table does not clear cell focus while the\n * external UI is open. Pair with onCommit (after the operation succeeds)\n * or onCancel (if the user dismisses without a value change).\n */\n onStartEdit?: () => void;\n /** Ref to the focusable input element. Used for type-to-edit (focusing the input when user starts typing on a focused cell). */\n inputRef?: MutableRefObject<Focusable | undefined | null>;\n typeConfig?: unknown;\n /** How edit mode was triggered. Edit components can use this to customize behavior (e.g., date picker auto-opens on 'type'). */\n editTrigger?: EditTrigger | null;\n /** Column-level validation rules. Edit components can derive UI behavior (e.g., maxLength blocking/tooltip) from these. */\n validation?: ValidationRule[];\n /** Stable id of the column. Cell components can use it to derive unique DOM ids. */\n columnId: string;\n /** Stable key of the row. Cell components can use it to derive unique DOM ids. */\n rowKey: string;\n}\n\n/**\n * Props passed to a cell type's optional `EditWrapper`. The table mounts the\n * wrapper around the cell content and keeps it mounted across the edit↔view\n * transition, so the wrapper can own behavior that must outlive the inline\n * editor (e.g. a reference cell navigating to an overlay and refreshing on\n * return). The wrapper hands anything the editor needs down via its own context.\n */\nexport interface CellEditWrapperProps {\n /** The column's typeConfig (same value handed to the cell's Edit/View). */\n typeConfig?: unknown;\n /** Stable id of the column. */\n columnId: string;\n /** Stable key of the row. */\n rowKey: string;\n /** The cell content (the Edit or View component) to render inside the wrapper. */\n children: ReactNode;\n}\n\nexport type EditableCellContextMenuAction = 'copy' | 'cut' | 'paste' | 'clear';\n\nexport interface EditableCellContextMenuActionContext<V> {\n /** Current cell value, including pending or draft edits. */\n value: V;\n /** Field metadata associated with the column, when available. */\n field?: Field;\n /** Stable key of the row. */\n rowKey: string;\n /** Stable id of the column. */\n columnId: string;\n}\n\nexport interface EditableCellContextMenuActionConfig<V> {\n /** Returning a non-empty string disables the action and shows the tooltip. */\n disabledTooltip(\n context: EditableCellContextMenuActionContext<V>,\n ): string | undefined;\n}\n\n/**\n * The editable-cell slot of a field type definition: how a cell of that type\n * renders, edits, and moves through the clipboard. The definition's key\n * identifies the type and the definition's `value` owns validation, so the\n * slot carries neither.\n *\n * Members that take `V` use method syntax so a definition typed with a\n * concrete value type stays assignable where a loosely typed definition is\n * expected (see `FieldTypeDefinition`).\n */\nexport interface EditableCellConfig<V> {\n /** Render cell in view mode (read-only display). */\n ViewComponent(props: CellViewProps<V>): ReactElement | null;\n /** Render cell in edit mode (inline editor). Optional — omit for view-only cells. */\n EditComponent?(props: CellEditProps<V>): ReactElement | null;\n /** Serialize value to clipboard string. */\n serialize?(value: V): string;\n /** Deserialize clipboard string to value. */\n deserialize?(raw: string): V;\n /** Can this cell type be edited? (default: true) */\n editable?: boolean;\n /** Availability of Cairo's built-in cell context-menu actions. */\n contextMenu?: Partial<\n Record<\n EditableCellContextMenuAction,\n EditableCellContextMenuActionConfig<V>\n >\n >;\n /** Toggle value on single click (e.g., boolean checkbox). Skips focus→edit flow. */\n toggleValue?(value: V): V;\n /** Enter edit mode on single click (e.g., image cell with no value). */\n editOnClick?(value: V): boolean;\n /** Show the EditComponent when the cell is focused, without entering edit mode.\n * Keyboard navigation remains active. Similar to toggleValue but without toggling. */\n showEditWhenFocused?: boolean;\n /** Optional wrapper component the cell type defines to own behavior that must\n * outlive the inline editor. Mounted around the cell content and kept mounted\n * across the edit↔view transition. */\n EditWrapper?: ComponentType<CellEditWrapperProps>;\n /** Cell content can grow past row height when focused. Only applies to\n * showEditWhenFocused cells. */\n growable?: boolean;\n /** Called on type-to-edit. Return object with cleared value and/or prevent flag.\n * Return undefined to block the key. Return {} to enter edit mode without changing the value. */\n onTypeToEdit?(params: {\n key: string;\n validation?: ValidationRule[];\n }): { value?: V } | undefined;\n /** Optional hook to normalize the committed value (e.g. auto-prepend https://).\n * Called before the edit commits; the value is written back before committing. */\n normalizeOnCommit?(value: V): V;\n /** When true, type-to-edit flushes the edit-mode render synchronously and\n * focuses the input within the same keydown event, then lets the browser's\n * default action deliver the keystroke to the now-focused input naturally.\n * Use for cells that wrap a controlled input whose value can't be seeded via props. */\n nativeTypeToEdit?: boolean;\n}\n\n/** The props the filter builder passes to a definition's toolbar filter\n * component — the same contract the built-in filter elements receive. */\nexport interface FilterTypeComponentProps<V = any> {\n filter: Filter<V>;\n toolbarItemProps?: { label?: ReactNode };\n toolbarTagProps?: { label?: string };\n accordionItemProps?: { label?: string };\n}\n\n/** The filter slot of a field type definition: the filter state registered on\n * the collection query and the toolbar element that renders it. */\nexport interface FilterTypeConfig {\n createFilter: (field: Field) => Filter<any>;\n Component: ComponentType<FilterTypeComponentProps>;\n}\n\n/** Narrows a definition's filter slot to an active filter config. */\nexport function isFilterTypeConfig(\n filter: FieldTypeDefinition['filter'],\n): filter is FilterTypeConfig {\n return 'createFilter' in filter;\n}\n\n/**\n * The read-only table slot of a field type definition: how a cell of that\n * type renders in the table, and the column's layout. Independent of\n * `editableTable` — neither slot falls back to the other.\n */\n/** What a read-only table cell is told about itself. */\nexport interface TableCellProps<V> {\n value: V;\n /** Stable id of the column. Cell components can use it to derive unique DOM ids. */\n columnId: string;\n /** The row this cell belongs to, so a cell can act on its item and not just\n * display it. Typed loosely for the same reason as `FieldsSource.getCellValue`:\n * the row shape belongs to the source, not to Cairo. */\n row: unknown;\n}\n\nexport interface TableCellConfig<V> {\n /** Render the cell. Method syntax keeps the definition assignable to\n * `FieldTypeDefinition<unknown>` (see FieldTypeDefinition). */\n CellComponent(props: TableCellProps<V>): ReactElement | null;\n /** Column width. Required — custom types get no built-in layout default. */\n width: string;\n /** Default: 'start'. */\n align?: 'start' | 'center' | 'end';\n}\n\n/** An extra menu item a field type definition adds to a field's actions menu. */\nexport interface FieldTypeActionItem {\n key: string;\n label: string;\n icon?: ReactNode;\n skin?: 'destructive';\n onClick: (field: Field) => void;\n /** Default: visible. */\n visible?: (field: Field) => boolean;\n /** Returning a string disables the item and shows the tooltip. */\n disabledTooltip?: (field: Field) => string | undefined;\n}\n\n/** The actions slot of a field type definition: extra items for the field's \"more actions\" menu. */\nexport interface FieldActionsConfig {\n items?: FieldTypeActionItem[];\n}\n\n/** Display metadata for a field type: menu label and type icons. */\nexport interface FieldTypeDisplay {\n label: string;\n icons: {\n Small: ComponentType;\n Medium: ComponentType;\n };\n}\n\n/** Value semantics of a field type, independent of any rendering surface.\n * Members use method syntax so a definition typed with a concrete value type\n * stays assignable where a loosely typed definition is expected. */\nexport interface FieldValueBehavior<V> {\n defaultValue?: V;\n isEmpty?(value: V): boolean;\n /** Returns an error message, or null when the value is valid. Every surface\n * that validates a field of this type runs this. */\n validate?(value: V, rules?: ValidationRule[]): string | null;\n}\n\nexport interface FieldCapabilities {\n sortable: boolean;\n}\n\n/** The field-modal slot of a field type definition: opts the type into the\n * add/edit-field modal's type picker and describes its entry there. */\nexport interface FieldModalConfig {\n /** True ⇒ the add-field modal offers this type. */\n creatable: boolean;\n /** Placeholder for the name input. Absent ⇒ the modal's generic placeholder. */\n namePlaceholder?: string;\n /** Fallback field ID base when the name cannot produce a valid ID.\n * Default: the normalized type ID. Numeric suffixes resolve collisions. */\n keyBase?: string;\n /** One-line description under the type in the picker. */\n subtitle?: string;\n /** Group heading this type is listed under in the picker. */\n group?: string;\n /** Whether a field of this type can be marked PII. Absent ⇒ follows the\n * source-wide setting. */\n supportsPii?: boolean;\n /** Warning shown while the PII toggle is on. Read on every render, so it can\n * use data that only exists once the schema has loaded. Default: none. */\n piiWarning?: () => FieldPiiWarning | undefined;\n /** This type's collapsible settings section — the same contract a\n * source-declared type option carries (see `FieldSettingsSection`). */\n settingsSection?: FieldSettingsSection;\n /** Collection picker shown in the main add/edit field form. */\n collectionInput?: FieldModalCollectionInput;\n}\n\n/**\n * Props the entity-page form dispatcher passes to a field type's form\n * component. The dispatcher owns the form wiring (registration, validation\n * from the definition's `value.validate`) and the field UI (label, required\n * marker, error message); the component renders the input: read `value`,\n * report edits through `onChange`, and hand back the focusable control\n * through `inputRef` so a blocked save can reach it.\n */\nexport interface FormFieldComponentProps<V> {\n field: Field;\n value: V;\n // Method syntax keeps FormFieldComponentProps covariant in V (see FieldTypeDefinition).\n onChange(value: V): void;\n /** Call when the input loses focus — marks the field touched, so error\n * timing matches the built-in renderers. */\n onBlur: () => void;\n /** Ref to the focusable input element. Used to focus the field when a\n * blocked save reports an error on it. Absent ⇒ the entity page brings the\n * field into view and focuses the first control it finds inside. */\n inputRef?: MutableRefObject<Focusable | undefined | null>;\n dataHook?: string;\n}\n\n/** The entity-page form slot of a field type definition. */\nexport interface FormTypeConfig<V = unknown> {\n /** Renders the input. Method syntax keeps the definition assignable to\n * `FieldTypeDefinition<unknown>` (see FieldTypeDefinition). */\n Component(props: FormFieldComponentProps<V>): ReactElement | null;\n}\n\n/**\n * A consumer-defined field type. Defined once on the fields source; every\n * entry point that renders the field resolves its slot from here. `V` is the\n * field's value type — `defineFieldType` infers it, and it keeps all the\n * slots consistent with each other.\n *\n * Sources hold definitions of mixed value types in one\n * `FieldTypeDefinition[]` (= `FieldTypeDefinition<unknown>[]`) array. That\n * works because every member that takes `V` is declared with method syntax,\n * which TypeScript checks bivariantly — so `FieldTypeDefinition<number>` is\n * assignable to `FieldTypeDefinition<unknown>` without casts.\n */\nexport interface FieldTypeDefinition<V = unknown> {\n /** Unique key for the type. A built-in type uses its `PatternsFieldType`; a\n * consumer-defined type uses the string its fields reference via `customType`. */\n type: string;\n display: FieldTypeDisplay;\n /** Filter behavior, or an explicit opt-out — never silently absent. */\n filter: FilterTypeConfig | { filterable: false };\n value?: FieldValueBehavior<V>;\n capabilities?: FieldCapabilities;\n /** Absent ⇒ the field renders with the default cell in the read-only table. */\n table?: TableCellConfig<V>;\n /** Absent ⇒ the field renders as a read-only cell in editable surfaces. */\n editableTable?: EditableCellConfig<V>;\n /** Required once a field of this type renders on an entity page:\n * development throws without it; production skips the field. */\n form?: FormTypeConfig<V>;\n /** Extra items for the field's \"more actions\" menu. */\n actions?: FieldActionsConfig;\n /** Absent ⇒ the add/edit field modal never offers this type. Fields of the\n * type created elsewhere still open in the modal for name/PII edits. */\n fieldModal?: FieldModalConfig;\n}\n\n/** Identity factory: infers `V` and keeps the definition's slots type-checked. */\nexport function defineFieldType<V>(\n definition: FieldTypeDefinition<V>,\n): FieldTypeDefinition<V> {\n return definition;\n}\n\n/** Resolves the definition a CUSTOM field references on its source. */\nexport function resolveFieldTypeDefinition(\n source: Pick<FieldsSource, 'fieldTypes'>,\n field: Field,\n) {\n if (field.type !== 'CUSTOM' || !field.customType) {\n return undefined;\n }\n return source.fieldTypes?.find((def) => def.type === field.customType);\n}\n"],"mappings":";;;;;;AA4EA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAiDA;AACA;;AAQA;AACA;;AAMA;AACO,SAASA,kBAAkBA,CAChCC,MAAqC,EACT;EAC5B,OAAO,cAAc,IAAIA,MAAM;AACjC;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAqBA;;AAaA;;AAKA;;AASA;AACA;AACA;;AAaA;AACA;;AA0BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgBA;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAwBA;AACO,SAASC,eAAeA,CAC7BC,UAAkC,EACV;EACxB,OAAOA,UAAU;AACnB;;AAEA;AACO,SAASC,0BAA0BA,CACxCC,MAAwC,EACxCC,KAAY,EACZ;EAAA,IAAAC,kBAAA;EACA,IAAID,KAAK,CAACE,IAAI,KAAK,QAAQ,IAAI,CAACF,KAAK,CAACG,UAAU,EAAE;IAChD,OAAOC,SAAS;EAClB;EACA,QAAAH,kBAAA,GAAOF,MAAM,CAACM,UAAU,qBAAjBJ,kBAAA,CAAmBK,IAAI,CAAEC,GAAG,IAAKA,GAAG,CAACL,IAAI,KAAKF,KAAK,CAACG,UAAU,CAAC;AACxE","ignoreList":[]}
1
+ {"version":3,"names":["isFilterTypeConfig","filter","defineFieldType","definition","resolveFieldTypeDefinition","source","field","_source$fieldTypes","type","customType","undefined","fieldTypes","find","def"],"sources":["../../../src/types/FieldTypeDefinition.ts"],"sourcesContent":["import type {\n ComponentType,\n MutableRefObject,\n ReactElement,\n ReactNode,\n} from 'react';\nimport type { Field } from './Field';\nimport type { Filter } from '../model/filter';\nimport type {\n FieldModalCollectionInput,\n FieldPiiWarning,\n FieldSettingsSection,\n FieldsSource,\n} from './FieldsSource';\n\nexport type ValidationRule =\n | { type: 'required'; message: string }\n | { type: 'min' | 'max'; value: number; message: string }\n | { type: 'minLength' | 'maxLength'; value: number; message: string }\n | { type: 'pattern'; value: RegExp; message: string }\n | { type: 'custom'; validate: (value: unknown) => boolean; message: string }\n | {\n type: 'specificValues';\n values: { id: string; value: string }[];\n message: string;\n };\n\nexport interface Focusable {\n focus: () => void;\n}\n\nexport type EditTrigger =\n | { kind: 'type'; key: string }\n | 'enter'\n | 'click'\n | 'doubleClick';\n\nexport interface CellViewProps<V> {\n value: V;\n typeConfig?: unknown;\n validation?: ValidationRule[];\n /** Stable id of the column. Cell components can use it to derive unique DOM ids. */\n columnId: string;\n /** Stable key of the row. Cell components can use it to derive unique DOM ids. */\n rowKey: string;\n /** Whether the cell is editable. Used to conditionally render placeholders (don't show them for read-only cells). */\n isEditable?: boolean;\n /** Whether this is the focused cell, excluding a multi-cell selection. */\n isFocused?: boolean;\n}\n\nexport interface CellEditProps<V> {\n value: V;\n // Method syntax keeps CellEditProps covariant in V (see FieldTypeDefinition).\n onChange(value: V): void;\n onCommit: () => void;\n onCancel: () => void;\n /**\n * Signals that the cell is starting an editing operation that will move focus\n * outside the table (e.g., opening a media manager or a modal). Calling this\n * sets isEditing=true so the table does not clear cell focus while the\n * external UI is open. Pair with onCommit (after the operation succeeds)\n * or onCancel (if the user dismisses without a value change).\n */\n onStartEdit?: () => void;\n /** Ref to the focusable input element. Used for type-to-edit (focusing the input when user starts typing on a focused cell). */\n inputRef?: MutableRefObject<Focusable | undefined | null>;\n typeConfig?: unknown;\n /** How edit mode was triggered. Edit components can use this to customize behavior (e.g., date picker auto-opens on 'type'). */\n editTrigger?: EditTrigger | null;\n /** Column-level validation rules. Edit components can derive UI behavior (e.g., maxLength blocking/tooltip) from these. */\n validation?: ValidationRule[];\n /** Stable id of the column. Cell components can use it to derive unique DOM ids. */\n columnId: string;\n /** Stable key of the row. Cell components can use it to derive unique DOM ids. */\n rowKey: string;\n}\n\n/**\n * Props passed to a cell type's optional `EditWrapper`. The table mounts the\n * wrapper around the cell content and keeps it mounted across the edit↔view\n * transition, so the wrapper can own behavior that must outlive the inline\n * editor (e.g. a reference cell navigating to an overlay and refreshing on\n * return). The wrapper hands anything the editor needs down via its own context.\n */\nexport interface CellEditWrapperProps {\n /** The column's typeConfig (same value handed to the cell's Edit/View). */\n typeConfig?: unknown;\n /** Stable id of the column. */\n columnId: string;\n /** Stable key of the row. */\n rowKey: string;\n /** The cell content (the Edit or View component) to render inside the wrapper. */\n children: ReactNode;\n}\n\nexport type EditableCellContextMenuAction = 'copy' | 'cut' | 'paste' | 'clear';\n\nexport interface EditableCellContextMenuActionContext<V> {\n /** Current cell value, including pending or draft edits. */\n value: V;\n /** Field metadata associated with the column, when available. */\n field?: Field;\n /** Stable key of the row. */\n rowKey: string;\n /** Stable id of the column. */\n columnId: string;\n}\n\nexport interface EditableCellContextMenuActionConfig<V> {\n /** Returning a non-empty string disables the action and shows the tooltip. */\n disabledTooltip(\n context: EditableCellContextMenuActionContext<V>,\n ): string | undefined;\n}\n\n/**\n * The editable-cell slot of a field type definition: how a cell of that type\n * renders, edits, and moves through the clipboard. The definition's key\n * identifies the type and the definition's `value` owns validation, so the\n * slot carries neither.\n *\n * Members that take `V` use method syntax so a definition typed with a\n * concrete value type stays assignable where a loosely typed definition is\n * expected (see `FieldTypeDefinition`).\n */\nexport interface EditableCellConfig<V> {\n /** Render cell in view mode (read-only display). */\n ViewComponent(props: CellViewProps<V>): ReactElement | null;\n /** Render cell in edit mode (inline editor). Optional — omit for view-only cells. */\n EditComponent?(props: CellEditProps<V>): ReactElement | null;\n /** Serialize value to clipboard string. */\n serialize?(value: V): string;\n /** Deserialize clipboard string to value. */\n deserialize?(raw: string): V;\n /** Can this cell type be edited? (default: true) */\n editable?: boolean;\n /** Availability of Cairo's built-in cell context-menu actions. */\n contextMenu?: Partial<\n Record<\n EditableCellContextMenuAction,\n EditableCellContextMenuActionConfig<V>\n >\n >;\n /** Toggle value on single click (e.g., boolean checkbox). Skips focus→edit flow. */\n toggleValue?(value: V): V;\n /** Enter edit mode on single click (e.g., image cell with no value). */\n editOnClick?(value: V): boolean;\n /** Show the EditComponent when the cell is focused, without entering edit mode.\n * Keyboard navigation remains active. Similar to toggleValue but without toggling. */\n showEditWhenFocused?: boolean;\n /** Optional wrapper component the cell type defines to own behavior that must\n * outlive the inline editor. Mounted around the cell content and kept mounted\n * across the edit↔view transition. */\n EditWrapper?: ComponentType<CellEditWrapperProps>;\n /** Cell content can grow past row height when focused, including read-only views. */\n growable?: boolean;\n /** Called on type-to-edit. Return object with cleared value and/or prevent flag.\n * Return undefined to block the key. Return {} to enter edit mode without changing the value. */\n onTypeToEdit?(params: {\n key: string;\n validation?: ValidationRule[];\n }): { value?: V } | undefined;\n /** Optional hook to normalize the committed value (e.g. auto-prepend https://).\n * Called before the edit commits; the value is written back before committing. */\n normalizeOnCommit?(value: V): V;\n /** When true, type-to-edit flushes the edit-mode render synchronously and\n * focuses the input within the same keydown event, then lets the browser's\n * default action deliver the keystroke to the now-focused input naturally.\n * Use for cells that wrap a controlled input whose value can't be seeded via props. */\n nativeTypeToEdit?: boolean;\n}\n\n/** The props the filter builder passes to a definition's toolbar filter\n * component — the same contract the built-in filter elements receive. */\nexport interface FilterTypeComponentProps<V = any> {\n filter: Filter<V>;\n toolbarItemProps?: { label?: ReactNode };\n toolbarTagProps?: { label?: string };\n accordionItemProps?: { label?: string };\n}\n\n/** The filter slot of a field type definition: the filter state registered on\n * the collection query and the toolbar element that renders it. */\nexport interface FilterTypeConfig {\n createFilter: (field: Field) => Filter<any>;\n Component: ComponentType<FilterTypeComponentProps>;\n}\n\n/** Narrows a definition's filter slot to an active filter config. */\nexport function isFilterTypeConfig(\n filter: FieldTypeDefinition['filter'],\n): filter is FilterTypeConfig {\n return 'createFilter' in filter;\n}\n\n/**\n * The read-only table slot of a field type definition: how a cell of that\n * type renders in the table, and the column's layout. Independent of\n * `editableTable` — neither slot falls back to the other.\n */\n/** What a read-only table cell is told about itself. */\nexport interface TableCellProps<V> {\n value: V;\n /** Stable id of the column. Cell components can use it to derive unique DOM ids. */\n columnId: string;\n /** The row this cell belongs to, so a cell can act on its item and not just\n * display it. Typed loosely for the same reason as `FieldsSource.getCellValue`:\n * the row shape belongs to the source, not to Cairo. */\n row: unknown;\n}\n\nexport interface TableCellConfig<V> {\n /** Render the cell. Method syntax keeps the definition assignable to\n * `FieldTypeDefinition<unknown>` (see FieldTypeDefinition). */\n CellComponent(props: TableCellProps<V>): ReactElement | null;\n /** Column width. Required — custom types get no built-in layout default. */\n width: string;\n /** Default: 'start'. */\n align?: 'start' | 'center' | 'end';\n}\n\n/** An extra menu item a field type definition adds to a field's actions menu. */\nexport interface FieldTypeActionItem {\n key: string;\n label: string;\n icon?: ReactNode;\n skin?: 'destructive';\n onClick: (field: Field) => void;\n /** Default: visible. */\n visible?: (field: Field) => boolean;\n /** Returning a string disables the item and shows the tooltip. */\n disabledTooltip?: (field: Field) => string | undefined;\n}\n\n/** The actions slot of a field type definition: extra items for the field's \"more actions\" menu. */\nexport interface FieldActionsConfig {\n items?: FieldTypeActionItem[];\n}\n\n/** Display metadata for a field type: menu label and type icons. */\nexport interface FieldTypeDisplay {\n label: string;\n icons: {\n Small: ComponentType;\n Medium: ComponentType;\n };\n}\n\n/** Value semantics of a field type, independent of any rendering surface.\n * Members use method syntax so a definition typed with a concrete value type\n * stays assignable where a loosely typed definition is expected. */\nexport interface FieldValueBehavior<V> {\n defaultValue?: V;\n isEmpty?(value: V): boolean;\n /** Returns an error message, or null when the value is valid. Every surface\n * that validates a field of this type runs this. */\n validate?(value: V, rules?: ValidationRule[]): string | null;\n}\n\nexport interface FieldCapabilities {\n sortable: boolean;\n}\n\n/** The field-modal slot of a field type definition: opts the type into the\n * add/edit-field modal's type picker and describes its entry there. */\nexport interface FieldModalConfig {\n /** True ⇒ the add-field modal offers this type. */\n creatable: boolean;\n /** Placeholder for the name input. Absent ⇒ the modal's generic placeholder. */\n namePlaceholder?: string;\n /** Fallback field ID base when the name cannot produce a valid ID.\n * Default: the normalized type ID. Numeric suffixes resolve collisions. */\n keyBase?: string;\n /** One-line description under the type in the picker. */\n subtitle?: string;\n /** Group heading this type is listed under in the picker. */\n group?: string;\n /** Whether a field of this type can be marked PII. Absent ⇒ follows the\n * source-wide setting. */\n supportsPii?: boolean;\n /** Warning shown while the PII toggle is on. Read on every render, so it can\n * use data that only exists once the schema has loaded. Default: none. */\n piiWarning?: () => FieldPiiWarning | undefined;\n /** This type's collapsible settings section — the same contract a\n * source-declared type option carries (see `FieldSettingsSection`). */\n settingsSection?: FieldSettingsSection;\n /** Collection picker shown in the main add/edit field form. */\n collectionInput?: FieldModalCollectionInput;\n}\n\n/**\n * Props the entity-page form dispatcher passes to a field type's form\n * component. The dispatcher owns the form wiring (registration, validation\n * from the definition's `value.validate`) and the field UI (label, required\n * marker, error message); the component renders the input: read `value`,\n * report edits through `onChange`, and hand back the focusable control\n * through `inputRef` so a blocked save can reach it.\n */\nexport interface FormFieldComponentProps<V> {\n field: Field;\n value: V;\n // Method syntax keeps FormFieldComponentProps covariant in V (see FieldTypeDefinition).\n onChange(value: V): void;\n /** Call when the input loses focus — marks the field touched, so error\n * timing matches the built-in renderers. */\n onBlur: () => void;\n /** Ref to the focusable input element. Used to focus the field when a\n * blocked save reports an error on it. Absent ⇒ the entity page brings the\n * field into view and focuses the first control it finds inside. */\n inputRef?: MutableRefObject<Focusable | undefined | null>;\n dataHook?: string;\n}\n\n/** The entity-page form slot of a field type definition. */\nexport interface FormTypeConfig<V = unknown> {\n /** Renders the input. Method syntax keeps the definition assignable to\n * `FieldTypeDefinition<unknown>` (see FieldTypeDefinition). */\n Component(props: FormFieldComponentProps<V>): ReactElement | null;\n}\n\n/**\n * A consumer-defined field type. Defined once on the fields source; every\n * entry point that renders the field resolves its slot from here. `V` is the\n * field's value type — `defineFieldType` infers it, and it keeps all the\n * slots consistent with each other.\n *\n * Sources hold definitions of mixed value types in one\n * `FieldTypeDefinition[]` (= `FieldTypeDefinition<unknown>[]`) array. That\n * works because every member that takes `V` is declared with method syntax,\n * which TypeScript checks bivariantly — so `FieldTypeDefinition<number>` is\n * assignable to `FieldTypeDefinition<unknown>` without casts.\n */\nexport interface FieldTypeDefinition<V = unknown> {\n /** Unique key for the type. A built-in type uses its `PatternsFieldType`; a\n * consumer-defined type uses the string its fields reference via `customType`. */\n type: string;\n display: FieldTypeDisplay;\n /** Filter behavior, or an explicit opt-out — never silently absent. */\n filter: FilterTypeConfig | { filterable: false };\n value?: FieldValueBehavior<V>;\n capabilities?: FieldCapabilities;\n /** Absent ⇒ the field renders with the default cell in the read-only table. */\n table?: TableCellConfig<V>;\n /** Absent ⇒ the field renders as a read-only cell in editable surfaces. */\n editableTable?: EditableCellConfig<V>;\n /** Required once a field of this type renders on an entity page:\n * development throws without it; production skips the field. */\n form?: FormTypeConfig<V>;\n /** Extra items for the field's \"more actions\" menu. */\n actions?: FieldActionsConfig;\n /** Absent ⇒ the add/edit field modal never offers this type. Fields of the\n * type created elsewhere still open in the modal for name/PII edits. */\n fieldModal?: FieldModalConfig;\n}\n\n/** Identity factory: infers `V` and keeps the definition's slots type-checked. */\nexport function defineFieldType<V>(\n definition: FieldTypeDefinition<V>,\n): FieldTypeDefinition<V> {\n return definition;\n}\n\n/** Resolves the definition a CUSTOM field references on its source. */\nexport function resolveFieldTypeDefinition(\n source: Pick<FieldsSource, 'fieldTypes'>,\n field: Field,\n) {\n if (field.type !== 'CUSTOM' || !field.customType) {\n return undefined;\n }\n return source.fieldTypes?.find((def) => def.type === field.customType);\n}\n"],"mappings":";;;;;;AA8EA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgDA;AACA;;AAQA;AACA;;AAMA;AACO,SAASA,kBAAkBA,CAChCC,MAAqC,EACT;EAC5B,OAAO,cAAc,IAAIA,MAAM;AACjC;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAqBA;;AAaA;;AAKA;;AASA;AACA;AACA;;AAaA;AACA;;AA0BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgBA;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAwBA;AACO,SAASC,eAAeA,CAC7BC,UAAkC,EACV;EACxB,OAAOA,UAAU;AACnB;;AAEA;AACO,SAASC,0BAA0BA,CACxCC,MAAwC,EACxCC,KAAY,EACZ;EAAA,IAAAC,kBAAA;EACA,IAAID,KAAK,CAACE,IAAI,KAAK,QAAQ,IAAI,CAACF,KAAK,CAACG,UAAU,EAAE;IAChD,OAAOC,SAAS;EAClB;EACA,QAAAH,kBAAA,GAAOF,MAAM,CAACM,UAAU,qBAAjBJ,kBAAA,CAAmBK,IAAI,CAAEC,GAAG,IAAKA,GAAG,CAACL,IAAI,KAAKF,KAAK,CAACG,UAAU,CAAC;AACxE","ignoreList":[]}
@@ -1,18 +1,24 @@
1
1
  import { useCallback } from 'react';
2
2
  import { useWixPatternsContainer, useCollectionContext } from '../providers';
3
3
  import { ImportState, } from '../state';
4
+ import { findExistingImportIds } from '../state/ImportState/findExistingImportIds';
4
5
  export function useCreateImport(params) {
5
- const { config, importInputs, fieldsSource, detectColumnType, importModalState, reportBi, } = params;
6
+ const { config, createFieldValidator, schemaSource, importInputs, fieldsSource, detectColumnType, isValueCompatible, importModalState, reportBi, } = params;
6
7
  const container = useWixPatternsContainer();
7
8
  const { showToast, translate, errorHandler, window, httpClient } = container;
8
9
  const collection = useCollectionContext();
9
10
  return useCallback(() => {
10
11
  return new ImportState({
11
12
  config,
13
+ createFieldValidator,
14
+ getExistingIds: schemaSource
15
+ ? (ids, signal) => findExistingImportIds(schemaSource, ids, signal, collection.query.asComputed.extra)
16
+ : undefined,
12
17
  importInputs,
13
18
  fieldsSource,
14
19
  httpClient,
15
20
  detectColumnType,
21
+ isValueCompatible,
16
22
  collection,
17
23
  importModalState,
18
24
  showToast,
@@ -1 +1 @@
1
- {"version":3,"file":"useImport.js","sourceRoot":"","sources":["../../../src/hooks/useImport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAC7E,OAAO,EAEL,WAAW,GAIZ,MAAM,UAAU,CAAC;AAmBlB,MAAM,UAAU,eAAe,CAC7B,MAAuB;IAEvB,MAAM,EACJ,MAAM,EACN,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,GACT,GAAG,MAAM,CAAC;IACX,MAAM,SAAS,GAAG,uBAAuB,EAAE,CAAC;IAC5C,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,SAAS,CAAC;IAC7E,MAAM,UAAU,GAAG,oBAAoB,EAAQ,CAAC;IAEhD,OAAO,WAAW,CAAC,GAAG,EAAE;QACtB,OAAO,IAAI,WAAW,CAAC;YACrB,MAAM;YACN,YAAY;YACZ,YAAY;YACZ,UAAU;YACV,gBAAgB;YAChB,UAAU;YACV,gBAAgB;YAChB,SAAS;YACT,SAAS;YACT,YAAY;YACZ,QAAQ,EAAE,QAAQ,IAAI,SAAS,CAAC,QAAQ;YACxC,WAAW,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,EAAE;gBACjC,MAAM,CAAC,QAAQ,CACb,+BAA+B,kBAAkB,CAAC,OAAO,CAAC,EAAE,EAC5D,QAAQ,CACT,CAAC;YACJ,CAAC;SACF,CAAC,CAAC;IACL,CAAC,EAAE,EAAE,CAAC,CAAC;AACT,CAAC"}
1
+ {"version":3,"file":"useImport.js","sourceRoot":"","sources":["../../../src/hooks/useImport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAC7E,OAAO,EAEL,WAAW,GAMZ,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AAuBnF,MAAM,UAAU,eAAe,CAC7B,MAA0B;IAE1B,MAAM,EACJ,MAAM,EACN,oBAAoB,EACpB,YAAY,EACZ,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,QAAQ,GACT,GAAG,MAAM,CAAC;IACX,MAAM,SAAS,GAAG,uBAAuB,EAAE,CAAC;IAC5C,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,SAAS,CAAC;IAC7E,MAAM,UAAU,GAAG,oBAAoB,EAAQ,CAAC;IAEhD,OAAO,WAAW,CAAC,GAAG,EAAE;QACtB,OAAO,IAAI,WAAW,CAAC;YACrB,MAAM;YACN,oBAAoB;YACpB,cAAc,EAAE,YAAY;gBAC1B,CAAC,CAAC,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,CACd,qBAAqB,CACnB,YAAY,EACZ,GAAG,EACH,MAAM,EACN,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,KAAK,CAClC;gBACL,CAAC,CAAC,SAAS;YACb,YAAY;YACZ,YAAY;YACZ,UAAU;YACV,gBAAgB;YAChB,iBAAiB;YACjB,UAAU;YACV,gBAAgB;YAChB,SAAS;YACT,SAAS;YACT,YAAY;YACZ,QAAQ,EAAE,QAAQ,IAAI,SAAS,CAAC,QAAQ;YACxC,WAAW,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,EAAE;gBACjC,MAAM,CAAC,QAAQ,CACb,+BAA+B,kBAAkB,CAAC,OAAO,CAAC,EAAE,EAC5D,QAAQ,CACT,CAAC;YACJ,CAAC;SACF,CAAC,CAAC;IACL,CAAC,EAAE,EAAE,CAAC,CAAC;AACT,CAAC"}
@@ -7,6 +7,7 @@ import { rewriteParsedCsvForImport } from './rewriteCsv';
7
7
  import { createHubJobClient } from './hubJobClient';
8
8
  import { pollImportJob } from './importJobPoller';
9
9
  import { detectColumnType, toPatternsFieldType, TYPE_SAMPLE_SIZE, } from './detectFieldType';
10
+ import { isImportColumnCompatible, } from './importFieldCompatibility';
10
11
  import { toDataExtensionFieldEdit, toFieldEdit, toNewFieldType, } from './fieldEdit';
11
12
  import { toNewFieldDraft } from './newFieldDraft';
12
13
  import { ImportStateBIReporter, } from './ImportStateBIReporter';
@@ -56,6 +57,8 @@ export const buildImportConfig = (fieldsSource, collection, inputs = {}) => {
56
57
  id: f.id,
57
58
  header: f.displayName,
58
59
  required: f.validation?.required,
60
+ type: f.type,
61
+ ...(f.arrayMetadata && { arrayMetadata: f.arrayMetadata }),
59
62
  }));
60
63
  return [...fields, ...live];
61
64
  },
@@ -144,9 +147,26 @@ function uniqueFieldNameAndKey(header, usedNames, usedKeys, requestedKey) {
144
147
  displayName = `${header}-${suffix}`;
145
148
  }
146
149
  }
150
+ function uniqueColumnHeaders(headers) {
151
+ const reserved = new Set(headers);
152
+ const used = new Set();
153
+ return headers.map((header) => {
154
+ let unique = header;
155
+ let suffix = 2;
156
+ while (used.has(unique)) {
157
+ do {
158
+ unique = `${header} (${suffix++})`;
159
+ } while (reserved.has(unique));
160
+ }
161
+ used.add(unique);
162
+ return unique;
163
+ });
164
+ }
147
165
  export class ImportState {
148
166
  constructor(props) {
149
167
  this.discardChangesModal = new ConditionalModalState();
168
+ this._uploadedRows = undefined;
169
+ this._validationFailures = [];
150
170
  this.currentStep = 'upload';
151
171
  this.importStatus = {
152
172
  ...queryStatus.idle,
@@ -203,12 +223,16 @@ export class ImportState {
203
223
  buildImportConfig(props.fieldsSource, props.collection, props.importInputs);
204
224
  this.importModalState = props.importModalState;
205
225
  this.translate = props.translate;
226
+ this._createFieldValidator = props.createFieldValidator;
227
+ this._fieldsSource = props.fieldsSource;
228
+ this._getExistingIds = props.getExistingIds;
206
229
  this.errorHandler = props.errorHandler;
207
230
  this.showToast = props.showToast;
208
231
  this.downloadCsv = props.downloadCsv;
209
232
  this.reportBi = props.reportBi ?? NOOP_REPORT_BI;
210
233
  this.bi = new ImportStateBIReporter(this);
211
234
  this._detectColumnType = props.detectColumnType ?? detectColumnType;
235
+ this._isValueCompatible = props.isValueCompatible;
212
236
  this.hubJobClient = createHubJobClient({
213
237
  httpClient: props.httpClient,
214
238
  errorHandler: props.errorHandler,
@@ -219,6 +243,9 @@ export class ImportState {
219
243
  fileName: observable.ref,
220
244
  csvHeaders: observable.ref,
221
245
  csvRows: observable.ref,
246
+ // Auto-mapping reads these before the configuration step observes them.
247
+ _columnSamples: computed({ keepAlive: true }),
248
+ _compatibleFieldsByHeader: computed({ keepAlive: true }),
222
249
  orderedHeaders: observable.ref,
223
250
  mappingByHeader: observable.ref,
224
251
  writePolicy: observable.ref,
@@ -359,6 +386,23 @@ export class ImportState {
359
386
  .filter((m) => m?.kind === 'existing')
360
387
  .map((m) => m.fieldId));
361
388
  }
389
+ get _compatibleFieldsByHeader() {
390
+ const fields = this.fields;
391
+ return new Map(this.csvHeaders.map((header, index) => [
392
+ header,
393
+ new Set(fields
394
+ .filter((field) => !field.type ||
395
+ isImportColumnCompatible(field.type, this._columnValues(index), field.arrayMetadata, this._isValueCompatible))
396
+ .map((field) => field.id)),
397
+ ]));
398
+ }
399
+ fieldsForHeader(header) {
400
+ const compatibleIds = this._compatibleFieldsByHeader.get(header);
401
+ const mapping = this.mappingByHeader[header];
402
+ return this.fields.filter((field) => field.type !== 'UNKNOWN' &&
403
+ (compatibleIds?.has(field.id) ||
404
+ (mapping?.kind === 'existing' && mapping.fieldId === field.id)));
405
+ }
362
406
  /**
363
407
  * Required destination fields that no CSV column is mapped to (CAIRO-4452).
364
408
  * A required field is an existing collection field, so only an `existing`
@@ -444,6 +488,8 @@ export class ImportState {
444
488
  this.importStatus = {
445
489
  ...queryStatus.idle,
446
490
  };
491
+ this._uploadedRows = undefined;
492
+ this._validationFailures = [];
447
493
  this.fileName = '';
448
494
  this.csvHeaders = [];
449
495
  this.csvRows = [];
@@ -563,18 +609,19 @@ export class ImportState {
563
609
  this.currentStep = 'configuration';
564
610
  }
565
611
  }
566
- getDefaultMapping(headers) {
612
+ getDefaultMapping(headers, originalHeaders) {
567
613
  const mapping = {};
568
- const fields = this.fields.map((field) => ({
569
- id: field.id ?? '',
570
- header: field.header ?? '',
571
- }));
614
+ const matchedIds = new Set();
615
+ const fields = this.fields.filter((field) => field.type !== 'UNKNOWN');
572
616
  headers.forEach((header, index) => {
573
- const normalizedHeader = normalize(header);
574
- const matched = fields.find((field) => normalize(field.id) === normalizedHeader ||
575
- normalize(field.header) === normalizedHeader);
617
+ const normalizedHeader = normalize(originalHeaders[index]);
618
+ const matched = fields.find((field) => field.id != null &&
619
+ !matchedIds.has(field.id) &&
620
+ (normalize(field.id) === normalizedHeader ||
621
+ normalize(field.header ?? '') === normalizedHeader));
576
622
  if (matched?.id) {
577
623
  mapping[header] = { kind: 'existing', fieldId: matched.id };
624
+ matchedIds.add(matched.id);
578
625
  }
579
626
  else {
580
627
  // Unmatched columns default to creating a new field (type inferred from
@@ -590,13 +637,23 @@ export class ImportState {
590
637
  });
591
638
  return mapping;
592
639
  }
593
- // The column's values, capped at the detection sample size — detection only
594
- // looks at the first `TYPE_SAMPLE_SIZE` values, so avoid copying the whole
595
- // column (a wide CSV would otherwise allocate rows × columns strings).
640
+ get _columnSamples() {
641
+ return this.csvHeaders.map((_, columnIndex) => {
642
+ const values = [];
643
+ for (const row of this.csvRows) {
644
+ const value = row[columnIndex] ?? '';
645
+ if (value.trim() !== '') {
646
+ values.push(value);
647
+ if (values.length === TYPE_SAMPLE_SIZE) {
648
+ break;
649
+ }
650
+ }
651
+ }
652
+ return values;
653
+ });
654
+ }
596
655
  _columnValues(columnIndex) {
597
- return this.csvRows
598
- .slice(0, TYPE_SAMPLE_SIZE)
599
- .map((row) => row[columnIndex] ?? '');
656
+ return this._columnSamples[columnIndex] ?? [];
600
657
  }
601
658
  // Puts the `_id`-mapped column first (CAIRO-4418), preserving CSV order for the
602
659
  // rest. Returns a fresh array so the snapshot doesn't alias `csvHeaders`.
@@ -610,13 +667,14 @@ export class ImportState {
610
667
  this._pendingFieldsMap = undefined;
611
668
  this._createdFields.clear();
612
669
  this.fileName = fileName;
613
- this.csvHeaders = parsedCsv.headers;
670
+ // Mapping, compatibility and upload rewriting all key columns by this name.
671
+ this.csvHeaders = uniqueColumnHeaders(parsedCsv.headers);
614
672
  this.csvRows = parsedCsv.rows;
615
- this.mappingByHeader = this.getDefaultMapping(parsedCsv.headers);
673
+ this.mappingByHeader = this.getDefaultMapping(this.csvHeaders, parsedCsv.headers);
616
674
  // Snapshot the row order for this file with the auto-mapped `_id` column
617
675
  // first. Reads `idMappedHeader`, so it must run after `mappingByHeader` is
618
676
  // set. Kept stable until the next file so mapping edits don't reorder rows.
619
- this.orderedHeaders = this._orderHeadersWithIdFirst(parsedCsv.headers);
677
+ this.orderedHeaders = this._orderHeadersWithIdFirst(this.csvHeaders);
620
678
  // A new file is a fresh import: start from the default policy so a prior
621
679
  // file's Skip choice doesn't silently carry over (only the new-file path
622
680
  // resets — remapping `_id` within the same file keeps the user's choice).
@@ -696,33 +754,31 @@ export class ImportState {
696
754
  },
697
755
  });
698
756
  }
699
- /**
700
- * Builds a re-importable CSV of the rows the server rejected and hands it to
701
- * `downloadCsv`. Each failed row is prefixed with a leading "why it failed"
702
- * column holding the server's error message, so the user can see and fix each
703
- * reason. The failed rows (and their reasons) come from the job's movement
704
- * logs, mapped back to the parsed `csvRows` we still hold in memory.
705
- */
757
+ /** Downloads validation failures and server rejections with their reasons. */
706
758
  async downloadFailedRows() {
707
759
  this.bi.onSummaryCtaClicked('Download failed items CSV');
708
- const jobId = this._jobId;
709
- if (!jobId) {
710
- return;
711
- }
712
- let failures;
713
- try {
714
- failures = await this._fetchFailedRows(jobId);
715
- }
716
- catch (error) {
717
- console.error('Fetching failed rows report failed', error);
718
- return;
760
+ let serverFailures = [];
761
+ if (this._jobId && this.result.failed > this._validationFailures.length) {
762
+ try {
763
+ serverFailures = await this._fetchFailedRows(this._jobId);
764
+ }
765
+ catch (error) {
766
+ console.error('Fetching failed rows report failed', error);
767
+ return;
768
+ }
719
769
  }
720
- const rows = failures
721
- .map(({ index, reason }) => {
722
- const row = this.csvRows[index];
723
- return row != null ? [reason, ...row] : null;
724
- })
725
- .filter((row) => row != null);
770
+ const rows = [
771
+ ...this._validationFailures.map(({ index, reason }) => ({
772
+ row: this.csvRows[index],
773
+ reason,
774
+ })),
775
+ ...serverFailures.map(({ index, reason }) => ({
776
+ row: (this._uploadedRows ?? this.csvRows)[index],
777
+ reason,
778
+ })),
779
+ ]
780
+ .filter(({ row }) => row != null)
781
+ .map(({ row, reason }) => [reason, ...row]);
726
782
  if (rows.length === 0) {
727
783
  return;
728
784
  }
@@ -756,7 +812,7 @@ export class ImportState {
756
812
  const index = fileLine - 2;
757
813
  if (Number.isInteger(index) &&
758
814
  index >= 0 &&
759
- index < this.csvRows.length) {
815
+ index < (this._uploadedRows ?? this.csvRows).length) {
760
816
  failures.push({ index, reason: log.failure.description ?? '' });
761
817
  }
762
818
  }
@@ -868,8 +924,8 @@ export class ImportState {
868
924
  * a failed job so `startImport` surfaces the error state; partial success is
869
925
  * reported via `result.failed` and the partial toast.
870
926
  */
871
- async _runImportJob(resolvedMapping) {
872
- const csv = rewriteParsedCsvForImport(this.csvHeaders, this.csvRows, resolvedMapping);
927
+ async _runImportJob(resolvedMapping, rows) {
928
+ const csv = rewriteParsedCsvForImport(this.csvHeaders, rows, resolvedMapping);
873
929
  const file = new File([csv], this.fileName || 'import.csv', {
874
930
  type: 'text/csv',
875
931
  });
@@ -955,8 +1011,10 @@ export class ImportState {
955
1011
  _applyJobProgress(job) {
956
1012
  const progress = job.progress;
957
1013
  const succeeded = progress?.itemsSuccessful ?? 0;
958
- const failed = progress?.itemsRejected ?? 0;
959
- const current = progress?.current ?? succeeded + failed;
1014
+ const rejected = progress?.itemsRejected ?? 0;
1015
+ const failed = rejected + this._validationFailures.length;
1016
+ const current = (progress?.current ?? succeeded + rejected) +
1017
+ this._validationFailures.length;
960
1018
  // The server splits successful items into created (new) and updated
961
1019
  // (existing) — the summary step reports each. Some jobs omit this split
962
1020
  // entirely (`itemsSuccessfulInfo` absent); in that case treat every success
@@ -964,8 +1022,7 @@ export class ImportState {
964
1022
  const successInfo = progress?.itemsSuccessfulInfo;
965
1023
  const created = successInfo ? successInfo.itemsCreated ?? 0 : succeeded;
966
1024
  const updated = successInfo?.itemsUpdated ?? 0;
967
- // `totalCount` is fixed up front in `startImport` from the CSV row count
968
- // (one uploaded row per CSV row); polling only advances `processedCount`.
1025
+ // Validation failures are already processed; the job advances the rest.
969
1026
  runInAction(() => {
970
1027
  this.processedCount = Math.min(current, this.totalCount);
971
1028
  this.result = { succeeded, failed, created, updated };
@@ -1111,6 +1168,63 @@ export class ImportState {
1111
1168
  console.error('ImportState config.onImportCompleted failed', error);
1112
1169
  }
1113
1170
  }
1171
+ async _validateRows(mapping, signal) {
1172
+ const rows = [];
1173
+ const failedRows = [];
1174
+ const idIndex = this.csvHeaders.findIndex((header) => mapping[header] === this.idFieldKey);
1175
+ const skipExisting = this.writePolicy === WritePolicy.SKIP_EXISTING;
1176
+ const ids = [
1177
+ ...new Set(this.csvRows.map((row) => row[idIndex]).filter(Boolean)),
1178
+ ];
1179
+ const skippedIds = new Set(skipExisting && ids.length
1180
+ ? await this._getExistingIds?.(ids, signal)
1181
+ : []);
1182
+ const columns = this.csvHeaders.map((header) => {
1183
+ const fieldId = mapping[header];
1184
+ if (!fieldId || fieldId === this.idFieldKey) {
1185
+ return undefined;
1186
+ }
1187
+ const sourceField = this._pendingFieldsMap?.[fieldId] ??
1188
+ this._fieldsSource?.fields.find((field) => field.id === fieldId);
1189
+ if (sourceField?.isSystem) {
1190
+ return undefined;
1191
+ }
1192
+ const configField = this.fields.find((field) => field.id === fieldId);
1193
+ const field = {
1194
+ ...(sourceField ?? {
1195
+ id: fieldId,
1196
+ displayName: configField?.header || fieldId,
1197
+ type: 'UNKNOWN',
1198
+ }),
1199
+ validation: {
1200
+ ...sourceField?.validation,
1201
+ required: !!(configField?.required || sourceField?.validation?.required),
1202
+ },
1203
+ };
1204
+ return (this._createFieldValidator?.(field) ??
1205
+ ((raw) => field.validation?.required && !raw
1206
+ ? [
1207
+ this.translate('cairo.editableTable.field.validation.required', { fieldName: field.displayName }),
1208
+ ]
1209
+ : []));
1210
+ });
1211
+ this.csvRows.forEach((row, index) => {
1212
+ if (skippedIds.has(row[idIndex])) {
1213
+ return;
1214
+ }
1215
+ const reasons = columns.flatMap((validate, columnIndex) => validate?.(row[columnIndex] ?? '') ?? []);
1216
+ if (reasons.length) {
1217
+ failedRows.push({ index, reason: reasons.join('; ') });
1218
+ }
1219
+ else {
1220
+ rows.push(row);
1221
+ if (skipExisting && row[idIndex]) {
1222
+ skippedIds.add(row[idIndex]);
1223
+ }
1224
+ }
1225
+ });
1226
+ return { rows, failedRows };
1227
+ }
1114
1228
  async startImport() {
1115
1229
  if (!this.hasMappings) {
1116
1230
  return;
@@ -1139,8 +1253,8 @@ export class ImportState {
1139
1253
  }
1140
1254
  this._cancelled = false;
1141
1255
  this._abortController = new AbortController();
1142
- // One uploaded row per CSV row (the rewrite drops columns, not rows), so the
1143
- // total is known up front from the parsed CSV and stays fixed through polling.
1256
+ this._validationFailures = [];
1257
+ this._uploadedRows = undefined;
1144
1258
  const totalCount = this.csvRows.length;
1145
1259
  runInAction(() => {
1146
1260
  this.currentStep = 'progress';
@@ -1174,8 +1288,13 @@ export class ImportState {
1174
1288
  // before uploading. A creation failure surfaces as the error state with a
1175
1289
  // "Try again" CTA, like an upload/job failure.
1176
1290
  let resolvedMapping;
1291
+ let prepared;
1177
1292
  try {
1178
1293
  resolvedMapping = await this._resolveFieldMapping();
1294
+ if (this._cancelled) {
1295
+ return;
1296
+ }
1297
+ prepared = await this._validateRows(resolvedMapping, this._abortController.signal);
1179
1298
  }
1180
1299
  catch (error) {
1181
1300
  runInAction(() => {
@@ -1193,7 +1312,17 @@ export class ImportState {
1193
1312
  if (this._cancelled) {
1194
1313
  return;
1195
1314
  }
1196
- const promise = this._runImportJob(resolvedMapping);
1315
+ const uploadedRows = prepared.rows;
1316
+ this._uploadedRows = uploadedRows;
1317
+ this._validationFailures = prepared.failedRows;
1318
+ runInAction(() => {
1319
+ this.result = { ...this.result, failed: this._validationFailures.length };
1320
+ this.processedCount = this._validationFailures.length;
1321
+ this.totalCount = uploadedRows.length + this._validationFailures.length;
1322
+ });
1323
+ const promise = uploadedRows.length
1324
+ ? this._runImportJob(resolvedMapping, uploadedRows)
1325
+ : Promise.resolve(this.result);
1197
1326
  this.importStatus = {
1198
1327
  ...queryStatus.loading,
1199
1328
  promise,