@entifix/react-integration 0.19.0 → 0.20.1

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 (44) hide show
  1. package/README.md +7 -7
  2. package/dist/hooks/use-data-loading/use-data-loading.d.ts +2 -0
  3. package/dist/hooks/use-data-loading/use-data-loading.d.ts.map +1 -1
  4. package/dist/hooks/use-data-loading/use-data-loading.js +8 -1
  5. package/dist/hooks/use-data-loading/use-data-loading.js.map +1 -1
  6. package/dist/hooks/use-entity-form/use-entity-form.d.ts +1 -1
  7. package/dist/hooks/use-entity-form/use-entity-form.d.ts.map +1 -1
  8. package/dist/hooks/use-entity-form/use-entity-form.helpers.d.ts +9 -8
  9. package/dist/hooks/use-entity-form/use-entity-form.helpers.d.ts.map +1 -1
  10. package/dist/hooks/use-entity-form/use-entity-form.helpers.js +33 -17
  11. package/dist/hooks/use-entity-form/use-entity-form.helpers.js.map +1 -1
  12. package/dist/hooks/use-entity-form/use-entity-form.js +9 -16
  13. package/dist/hooks/use-entity-form/use-entity-form.js.map +1 -1
  14. package/dist/hooks/use-entity-form/use-entity-form.types.d.ts +8 -11
  15. package/dist/hooks/use-entity-form/use-entity-form.types.d.ts.map +1 -1
  16. package/dist/hooks/use-entity-form/use-entity-form.types.js.map +1 -1
  17. package/dist/hooks/use-facet-counts/index.d.ts +2 -0
  18. package/dist/hooks/use-facet-counts/index.d.ts.map +1 -0
  19. package/dist/hooks/use-facet-counts/index.js +3 -0
  20. package/dist/hooks/use-facet-counts/index.js.map +1 -0
  21. package/dist/hooks/use-facet-counts/use-facet-counts.d.ts +29 -0
  22. package/dist/hooks/use-facet-counts/use-facet-counts.d.ts.map +1 -0
  23. package/dist/hooks/use-facet-counts/use-facet-counts.js +41 -0
  24. package/dist/hooks/use-facet-counts/use-facet-counts.js.map +1 -0
  25. package/dist/index.d.ts +2 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +2 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/reactive/event-source-push-channel.d.ts.map +1 -1
  30. package/dist/reactive/event-source-push-channel.js +12 -0
  31. package/dist/reactive/event-source-push-channel.js.map +1 -1
  32. package/dist/reactive/push-channel.d.ts +14 -0
  33. package/dist/reactive/push-channel.d.ts.map +1 -1
  34. package/dist/reactive/push-channel.js +10 -2
  35. package/dist/reactive/push-channel.js.map +1 -1
  36. package/dist/reactive/push-router.d.ts +12 -3
  37. package/dist/reactive/push-router.d.ts.map +1 -1
  38. package/dist/reactive/push-router.js +18 -1
  39. package/dist/reactive/push-router.js.map +1 -1
  40. package/dist/reactive/use-push-connection.d.ts +13 -0
  41. package/dist/reactive/use-push-connection.d.ts.map +1 -0
  42. package/dist/reactive/use-push-connection.js +18 -0
  43. package/dist/reactive/use-push-connection.js.map +1 -0
  44. package/package.json +5 -5
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Hooks that connect entities to data. It puts TanStack Query and TanStack Form over the entity adapters from `@entifix/business`, so a record, a page of records or a save is one hook — and the adapter behind it, REST or anything else, is supplied once through `createAdaptersContext`.
4
4
 
5
- It also carries the draft model a form edits, schema-based validation, link resolution, wizard state, and reactive invalidation when a write elsewhere settles.
5
+ It also carries the draft model a form edits, schema-based validation, link resolution, wizard state, and reactive invalidation when a write elsewhere settles. `useEntityForm` takes a `translateKey` and speaks its validation in the `controls` catalog's words, so a key never reaches the screen; `useFacetCounts` counts a filter's choices; `usePushConnection` says whether the push stream is open, reconnecting or closed.
6
6
 
7
7
  ## Install
8
8
 
@@ -12,12 +12,12 @@ pnpm add @entifix/react-integration @tanstack/react-form @tanstack/react-query e
12
12
 
13
13
  ## Entry points
14
14
 
15
- | Import | What it holds |
16
- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
17
- | `@entifix/react-integration` | `EntifixQueryProvider`, `useEntityRecord`, `useEntityForm`, `useEntityMutation`, `useWizard`, `useReactiveInvalidation`, `useTransactionSettlement` |
18
- | `@entifix/react-integration/url-query` | `defineUrlQuery`, `anyOf`, `containing`, `inAnyYear`: the query string read as a load request (filter, sort and page), with no React — for a server component parsing `searchParams` |
19
- | `@entifix/react-integration/url` | `useUrlState`, `useEntityLoad`, `useUrlFilter`: a filter kept in the query string, answered by `loadAllUCFactory` over an `EntitySource`. No TanStack |
20
- | `@entifix/react-integration/event-source` | `makeEventSourceReactiveChannel`, the browser transport behind `ReactiveChannelTag` — imported by the composition root that picks it, never by a component |
15
+ | Import | What it holds |
16
+ | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
17
+ | `@entifix/react-integration` | `EntifixQueryProvider`, `useEntityRecord`, `useEntityForm`, `useEntityMutation`, `useWizard`, `useReactiveInvalidation`, `useTransactionSettlement`, `useFacetCounts`, `usePushConnection` |
18
+ | `@entifix/react-integration/url-query` | `defineUrlQuery`, `anyOf`, `containing`, `inAnyYear`: the query string read as a load request (filter, sort and page), with no React — for a server component parsing `searchParams` |
19
+ | `@entifix/react-integration/url` | `useUrlState`, `useEntityLoad`, `useUrlFilter`: a filter kept in the query string, answered by `loadAllUCFactory` over an `EntitySource`. No TanStack |
20
+ | `@entifix/react-integration/event-source` | `makeEventSourceReactiveChannel`, the browser transport behind `ReactiveChannelTag` — imported by the composition root that picks it, never by a component |
21
21
 
22
22
  ---
23
23
 
@@ -22,5 +22,7 @@ export declare function useDataLoading<TEntity extends Entity, TContext>({ uc, c
22
22
  onPageSizeChange: (newPageSize: number) => void;
23
23
  onFilteringChange: (filtering: FilterGroup<TEntity>) => void;
24
24
  onSortingChange: (sorting: EntitySorting<TEntity>) => void;
25
+ /** Reads the current page again — what a failed load offers as Retry. */
26
+ refetch: () => void;
25
27
  };
26
28
  //# sourceMappingURL=use-data-loading.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-data-loading.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-data-loading/use-data-loading.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,MAAM,EAGX,KAAK,aAAa,EAClB,KAAK,WAAW,EAGjB,MAAM,eAAe,CAAC;AAavB,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAoCzE;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,MAAM,EAAE,QAAQ,EAAE,EAC/D,EAAE,EACF,GAAG,EACH,eAAmC,EACnC,QAAQ,EACR,OAAc,EACd,aAAa,EACb,gBAAgB,GACjB,EAAE,qBAAqB,CAAC,OAAO,EAAE,QAAQ,CAAC;;;;;;;;;4BA0GE,MAAM;oCAIE,MAAM;mCAMP,WAAW,CAAC,OAAO,CAAC;+BAIxB,aAAa,CAAC,OAAO,CAAC;EAkBrE"}
1
+ {"version":3,"file":"use-data-loading.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-data-loading/use-data-loading.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,MAAM,EAGX,KAAK,aAAa,EAClB,KAAK,WAAW,EAGjB,MAAM,eAAe,CAAC;AAavB,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAoCzE;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,MAAM,EAAE,QAAQ,EAAE,EAC/D,EAAE,EACF,GAAG,EACH,eAAmC,EACnC,QAAQ,EACR,OAAc,EACd,aAAa,EACb,gBAAgB,GACjB,EAAE,qBAAqB,CAAC,OAAO,EAAE,QAAQ,CAAC;;;;;;;;;4BA+GE,MAAM;oCAIE,MAAM;mCAMP,WAAW,CAAC,OAAO,CAAC;+BAIxB,aAAa,CAAC,OAAO,CAAC;IAiBlE,yEAAyE;;EAG5E"}
@@ -118,6 +118,12 @@ function initialRequest(seed) {
118
118
  // it — the same cast `loadUCFactory` makes reading it back.
119
119
  loadRequest))))
120
120
  });
121
+ const { refetch: refetchQuery } = query;
122
+ const refetch = useCallback(()=>{
123
+ void refetchQuery();
124
+ }, [
125
+ refetchQuery
126
+ ]);
121
127
  const onPageChange = useCallback((newPage)=>{
122
128
  dispatch({
123
129
  set: {
@@ -163,7 +169,8 @@ function initialRequest(seed) {
163
169
  onPageChange,
164
170
  onPageSizeChange,
165
171
  onFilteringChange,
166
- onSortingChange
172
+ onSortingChange,
173
+ /** Reads the current page again — what a failed load offers as Retry. */ refetch
167
174
  };
168
175
  }
169
176
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/hooks/use-data-loading/use-data-loading.ts"],"sourcesContent":["import { EntityLoadRequestTag } from '@entifix/business';\nimport {\n type EntifixFailure,\n type Entity,\n type EntityLoadRequest,\n type EntityPage,\n type EntitySorting,\n type FilterGroup,\n serializeRsql,\n serializeSort,\n} from '@entifix/core';\nimport { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport { Context, Effect } from 'effect';\nimport {\n useCallback,\n useEffect,\n useId,\n useMemo,\n useReducer,\n useRef,\n} from 'react';\n\nimport { combineFilterGroups } from '../../query/combine-filtering.js';\nimport type { UseDataLoadingOptions } from './use-data-loading.types.js';\n\nconst DEFAULT_PAGE_SIZE = 10;\n\n/**\n * The request the caller controls — page, size, and the *applied* filter/sort.\n * The response (items, loading, error) is owned by the query cache, not here.\n */\ninterface RequestState<T extends Entity> {\n currentPage: number;\n pageSize: number;\n filtering: FilterGroup<T> | undefined;\n sorting: EntitySorting<T> | undefined;\n}\n\ntype RequestAction<T extends Entity> = { set: Partial<RequestState<T>> };\n\nfunction requestReducer<T extends Entity>(\n state: RequestState<T>,\n action: RequestAction<T>,\n): RequestState<T> {\n return { ...state, ...action.set };\n}\n\nfunction initialRequest<T extends Entity>(seed: {\n pageSize: number;\n filtering: FilterGroup<T> | undefined;\n}): RequestState<T> {\n return {\n currentPage: 1,\n pageSize: seed.pageSize,\n filtering: seed.filtering,\n sorting: undefined,\n };\n}\n\n/**\n * Runs an entity list use-case and caches the result through TanStack Query.\n *\n * The reducer owns the *request* (page/size/filter/sort); `useQuery` owns the\n * *fetch* — deduping, caching, and (with a shared `queryKey`) letting mutations\n * and reactive events invalidate the list. The public shape is unchanged: the\n * `uc`/`ctx` come in the same way and the Effect runs against the same provided\n * Tags, so callers and organisms are untouched.\n */\nexport function useDataLoading<TEntity extends Entity, TContext>({\n uc,\n ctx,\n initialPageSize = DEFAULT_PAGE_SIZE,\n queryKey,\n enabled = true,\n baseFiltering,\n initialFiltering,\n}: UseDataLoadingOptions<TEntity, TContext>) {\n const [request, dispatch] = useReducer(\n requestReducer as (\n state: RequestState<TEntity>,\n action: RequestAction<TEntity>,\n ) => RequestState<TEntity>,\n { pageSize: initialPageSize, filtering: initialFiltering },\n initialRequest<TEntity>,\n );\n\n // Callers rebuild `uc`/`ctx` inline every render, so hold the latest in refs\n // and keep them out of the query key — keying on their identity would refetch\n // on every render. Written in an effect (refs may not be set during render);\n // effects fire in order, so the query below always reads the latest.\n const ucRef = useRef(uc);\n const ctxRef = useRef(ctx);\n useEffect(() => {\n ucRef.current = uc;\n ctxRef.current = ctx;\n });\n\n // What actually goes on the wire: the caller's standing restriction ANDed with\n // whatever the user applied. Kept separate from `request.filtering` because the\n // restriction is not the user's filter — the panel must keep showing only what\n // they set, while the request keeps carrying both.\n const effectiveFiltering = useMemo(\n () => combineFilterGroups<TEntity>(baseFiltering, request.filtering),\n [baseFiltering, request.filtering],\n );\n\n // The applied filter/sort are rebuilt each render, so their *serialized* form\n // — the same codec the request needs anyway — is what keys the query: a stable\n // string that changes exactly when the query does.\n const rsql = useMemo(\n () => serializeRsql(effectiveFiltering ? [effectiveFiltering] : undefined),\n [effectiveFiltering],\n );\n const sort = useMemo(\n () => serializeSort(request.sorting ? [request.sorting] : undefined),\n [request.sorting],\n );\n\n const loadRequest = useMemo<EntityLoadRequest<TEntity>>(() => {\n const built: EntityLoadRequest<TEntity> = {\n page: request.currentPage,\n pageSize: request.pageSize,\n };\n // An empty group serializes to nothing; omit it rather than send a filter\n // that matches everything.\n if (rsql !== '' && effectiveFiltering) {\n built.filtering = [effectiveFiltering];\n }\n if (sort !== '' && request.sorting) {\n built.sorting = [request.sorting];\n }\n return built;\n }, [\n request.currentPage,\n request.pageSize,\n effectiveFiltering,\n request.sorting,\n rsql,\n sort,\n ]);\n\n // Falls back to a per-instance id so an un-scoped list never collides with\n // another in the shared cache — correct, just unshared (see the type doc).\n const instanceId = useId();\n const scope = queryKey ?? [instanceId];\n\n const query = useQuery<EntityPage<TEntity>, EntifixFailure>({\n enabled,\n /**\n * Page, size, filter and sort are all part of the key, so every one of them\n * is a *different* query — and without this, `data` goes undefined the\n * instant any of them changes. The table would then see `items.length === 0`\n * with `isFetching` true, read it as a first load, and blank populated rows\n * to skeleton on every pagination click: the grey flash the loading contract\n * exists to prevent. Keeping the previous page is what makes \"skeleton only\n * on first load\" true rather than merely intended.\n */\n placeholderData: keepPreviousData,\n queryKey: [\n ...scope,\n 'load',\n request.currentPage,\n request.pageSize,\n rsql,\n sort,\n ],\n queryFn: () =>\n Effect.runPromise(\n Effect.provide(\n ucRef.current,\n ctxRef.current.pipe(\n Context.add(\n EntityLoadRequestTag,\n // The tag carries no generic, so the entity-typed request crosses\n // it — the same cast `loadUCFactory` makes reading it back.\n loadRequest as unknown as EntityLoadRequest,\n ),\n ),\n ),\n ),\n });\n\n const onPageChange = useCallback((newPage: number) => {\n dispatch({ set: { currentPage: newPage } });\n }, []);\n\n const onPageSizeChange = useCallback((newPageSize: number) => {\n dispatch({ set: { pageSize: newPageSize, currentPage: 1 } });\n }, []);\n\n // Narrowing the result set invalidates the page number: page 4 of the old\n // result is very likely past the end of the new one.\n const onFilteringChange = useCallback((filtering: FilterGroup<TEntity>) => {\n dispatch({ set: { filtering, currentPage: 1 } });\n }, []);\n\n const onSortingChange = useCallback((sorting: EntitySorting<TEntity>) => {\n dispatch({ set: { sorting, currentPage: 1 } });\n }, []);\n\n return {\n isLoading: query.isFetching,\n items: query.data?.items ?? ([] as Array<TEntity>),\n totalItems: query.data?.total ?? 0,\n currentPage: request.currentPage,\n pageSize: request.pageSize,\n error: query.error ?? undefined,\n filtering: request.filtering,\n sorting: request.sorting,\n onPageChange,\n onPageSizeChange,\n onFilteringChange,\n onSortingChange,\n };\n}\n"],"names":["EntityLoadRequestTag","serializeRsql","serializeSort","keepPreviousData","useQuery","Context","Effect","useCallback","useEffect","useId","useMemo","useReducer","useRef","combineFilterGroups","DEFAULT_PAGE_SIZE","requestReducer","state","action","set","initialRequest","seed","currentPage","pageSize","filtering","sorting","undefined","useDataLoading","uc","ctx","initialPageSize","queryKey","enabled","baseFiltering","initialFiltering","query","request","dispatch","ucRef","ctxRef","current","effectiveFiltering","rsql","sort","loadRequest","built","page","instanceId","scope","placeholderData","queryFn","runPromise","provide","pipe","add","onPageChange","newPage","onPageSizeChange","newPageSize","onFilteringChange","onSortingChange","isLoading","isFetching","items","data","totalItems","total","error"],"mappings":";AAAA,SAASA,oBAAoB,QAAQ,oBAAoB;AACzD,SAOEC,aAAa,EACbC,aAAa,QACR,gBAAgB;AACvB,SAASC,gBAAgB,EAAEC,QAAQ,QAAQ,wBAAwB;AACnE,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AACzC,SACEC,WAAW,EACXC,SAAS,EACTC,KAAK,EACLC,OAAO,EACPC,UAAU,EACVC,MAAM,QACD,QAAQ;AAEf,SAASC,mBAAmB,QAAQ,mCAAmC;AAGvE,MAAMC,oBAAoB;AAe1B,SAASC,eACPC,KAAsB,EACtBC,MAAwB;IAExB,OAAO,aAAKD,OAAUC,OAAOC,GAAG;AAClC;AAEA,SAASC,eAAiCC,IAGzC;IACC,OAAO;QACLC,aAAa;QACbC,UAAUF,KAAKE,QAAQ;QACvBC,WAAWH,KAAKG,SAAS;QACzBC,SAASC;IACX;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC,eAAiD,EAC/DC,EAAE,EACFC,GAAG,EACHC,kBAAkBf,iBAAiB,EACnCgB,QAAQ,EACRC,UAAU,IAAI,EACdC,aAAa,EACbC,gBAAgB,EACyB;q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,eAAeT;QACtBF,WAAWY,QAAQZ,SAAS;QAC5BC,SAASW,QAAQX,OAAO;QACxB8B;QACAE;QACAE;QACAC;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/hooks/use-data-loading/use-data-loading.ts"],"sourcesContent":["import { EntityLoadRequestTag } from '@entifix/business';\nimport {\n type EntifixFailure,\n type Entity,\n type EntityLoadRequest,\n type EntityPage,\n type EntitySorting,\n type FilterGroup,\n serializeRsql,\n serializeSort,\n} from '@entifix/core';\nimport { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport { Context, Effect } from 'effect';\nimport {\n useCallback,\n useEffect,\n useId,\n useMemo,\n useReducer,\n useRef,\n} from 'react';\n\nimport { combineFilterGroups } from '../../query/combine-filtering.js';\nimport type { UseDataLoadingOptions } from './use-data-loading.types.js';\n\nconst DEFAULT_PAGE_SIZE = 10;\n\n/**\n * The request the caller controls — page, size, and the *applied* filter/sort.\n * The response (items, loading, error) is owned by the query cache, not here.\n */\ninterface RequestState<T extends Entity> {\n currentPage: number;\n pageSize: number;\n filtering: FilterGroup<T> | undefined;\n sorting: EntitySorting<T> | undefined;\n}\n\ntype RequestAction<T extends Entity> = { set: Partial<RequestState<T>> };\n\nfunction requestReducer<T extends Entity>(\n state: RequestState<T>,\n action: RequestAction<T>,\n): RequestState<T> {\n return { ...state, ...action.set };\n}\n\nfunction initialRequest<T extends Entity>(seed: {\n pageSize: number;\n filtering: FilterGroup<T> | undefined;\n}): RequestState<T> {\n return {\n currentPage: 1,\n pageSize: seed.pageSize,\n filtering: seed.filtering,\n sorting: undefined,\n };\n}\n\n/**\n * Runs an entity list use-case and caches the result through TanStack Query.\n *\n * The reducer owns the *request* (page/size/filter/sort); `useQuery` owns the\n * *fetch* — deduping, caching, and (with a shared `queryKey`) letting mutations\n * and reactive events invalidate the list. The public shape is unchanged: the\n * `uc`/`ctx` come in the same way and the Effect runs against the same provided\n * Tags, so callers and organisms are untouched.\n */\nexport function useDataLoading<TEntity extends Entity, TContext>({\n uc,\n ctx,\n initialPageSize = DEFAULT_PAGE_SIZE,\n queryKey,\n enabled = true,\n baseFiltering,\n initialFiltering,\n}: UseDataLoadingOptions<TEntity, TContext>) {\n const [request, dispatch] = useReducer(\n requestReducer as (\n state: RequestState<TEntity>,\n action: RequestAction<TEntity>,\n ) => RequestState<TEntity>,\n { pageSize: initialPageSize, filtering: initialFiltering },\n initialRequest<TEntity>,\n );\n\n // Callers rebuild `uc`/`ctx` inline every render, so hold the latest in refs\n // and keep them out of the query key — keying on their identity would refetch\n // on every render. Written in an effect (refs may not be set during render);\n // effects fire in order, so the query below always reads the latest.\n const ucRef = useRef(uc);\n const ctxRef = useRef(ctx);\n useEffect(() => {\n ucRef.current = uc;\n ctxRef.current = ctx;\n });\n\n // What actually goes on the wire: the caller's standing restriction ANDed with\n // whatever the user applied. Kept separate from `request.filtering` because the\n // restriction is not the user's filter — the panel must keep showing only what\n // they set, while the request keeps carrying both.\n const effectiveFiltering = useMemo(\n () => combineFilterGroups<TEntity>(baseFiltering, request.filtering),\n [baseFiltering, request.filtering],\n );\n\n // The applied filter/sort are rebuilt each render, so their *serialized* form\n // — the same codec the request needs anyway — is what keys the query: a stable\n // string that changes exactly when the query does.\n const rsql = useMemo(\n () => serializeRsql(effectiveFiltering ? [effectiveFiltering] : undefined),\n [effectiveFiltering],\n );\n const sort = useMemo(\n () => serializeSort(request.sorting ? [request.sorting] : undefined),\n [request.sorting],\n );\n\n const loadRequest = useMemo<EntityLoadRequest<TEntity>>(() => {\n const built: EntityLoadRequest<TEntity> = {\n page: request.currentPage,\n pageSize: request.pageSize,\n };\n // An empty group serializes to nothing; omit it rather than send a filter\n // that matches everything.\n if (rsql !== '' && effectiveFiltering) {\n built.filtering = [effectiveFiltering];\n }\n if (sort !== '' && request.sorting) {\n built.sorting = [request.sorting];\n }\n return built;\n }, [\n request.currentPage,\n request.pageSize,\n effectiveFiltering,\n request.sorting,\n rsql,\n sort,\n ]);\n\n // Falls back to a per-instance id so an un-scoped list never collides with\n // another in the shared cache — correct, just unshared (see the type doc).\n const instanceId = useId();\n const scope = queryKey ?? [instanceId];\n\n const query = useQuery<EntityPage<TEntity>, EntifixFailure>({\n enabled,\n /**\n * Page, size, filter and sort are all part of the key, so every one of them\n * is a *different* query — and without this, `data` goes undefined the\n * instant any of them changes. The table would then see `items.length === 0`\n * with `isFetching` true, read it as a first load, and blank populated rows\n * to skeleton on every pagination click: the grey flash the loading contract\n * exists to prevent. Keeping the previous page is what makes \"skeleton only\n * on first load\" true rather than merely intended.\n */\n placeholderData: keepPreviousData,\n queryKey: [\n ...scope,\n 'load',\n request.currentPage,\n request.pageSize,\n rsql,\n sort,\n ],\n queryFn: () =>\n Effect.runPromise(\n Effect.provide(\n ucRef.current,\n ctxRef.current.pipe(\n Context.add(\n EntityLoadRequestTag,\n // The tag carries no generic, so the entity-typed request crosses\n // it — the same cast `loadUCFactory` makes reading it back.\n loadRequest as unknown as EntityLoadRequest,\n ),\n ),\n ),\n ),\n });\n\n const { refetch: refetchQuery } = query;\n const refetch = useCallback(() => {\n void refetchQuery();\n }, [refetchQuery]);\n\n const onPageChange = useCallback((newPage: number) => {\n dispatch({ set: { currentPage: newPage } });\n }, []);\n\n const onPageSizeChange = useCallback((newPageSize: number) => {\n dispatch({ set: { pageSize: newPageSize, currentPage: 1 } });\n }, []);\n\n // Narrowing the result set invalidates the page number: page 4 of the old\n // result is very likely past the end of the new one.\n const onFilteringChange = useCallback((filtering: FilterGroup<TEntity>) => {\n dispatch({ set: { filtering, currentPage: 1 } });\n }, []);\n\n const onSortingChange = useCallback((sorting: EntitySorting<TEntity>) => {\n dispatch({ set: { sorting, currentPage: 1 } });\n }, []);\n\n return {\n isLoading: query.isFetching,\n items: query.data?.items ?? ([] as Array<TEntity>),\n totalItems: query.data?.total ?? 0,\n currentPage: request.currentPage,\n pageSize: request.pageSize,\n error: query.error ?? undefined,\n filtering: request.filtering,\n sorting: request.sorting,\n onPageChange,\n onPageSizeChange,\n onFilteringChange,\n onSortingChange,\n /** Reads the current page again — what a failed load offers as Retry. */\n refetch,\n };\n}\n"],"names":["EntityLoadRequestTag","serializeRsql","serializeSort","keepPreviousData","useQuery","Context","Effect","useCallback","useEffect","useId","useMemo","useReducer","useRef","combineFilterGroups","DEFAULT_PAGE_SIZE","requestReducer","state","action","set","initialRequest","seed","currentPage","pageSize","filtering","sorting","undefined","useDataLoading","uc","ctx","initialPageSize","queryKey","enabled","baseFiltering","initialFiltering","query","request","dispatch","ucRef","ctxRef","current","effectiveFiltering","rsql","sort","loadRequest","built","page","instanceId","scope","placeholderData","queryFn","runPromise","provide","pipe","add","refetch","refetchQuery","onPageChange","newPage","onPageSizeChange","newPageSize","onFilteringChange","onSortingChange","isLoading","isFetching","items","data","totalItems","total","error"],"mappings":";AAAA,SAASA,oBAAoB,QAAQ,oBAAoB;AACzD,SAOEC,aAAa,EACbC,aAAa,QACR,gBAAgB;AACvB,SAASC,gBAAgB,EAAEC,QAAQ,QAAQ,wBAAwB;AACnE,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AACzC,SACEC,WAAW,EACXC,SAAS,EACTC,KAAK,EACLC,OAAO,EACPC,UAAU,EACVC,MAAM,QACD,QAAQ;AAEf,SAASC,mBAAmB,QAAQ,mCAAmC;AAGvE,MAAMC,oBAAoB;AAe1B,SAASC,eACPC,KAAsB,EACtBC,MAAwB;IAExB,OAAO,aAAKD,OAAUC,OAAOC,GAAG;AAClC;AAEA,SAASC,eAAiCC,IAGzC;IACC,OAAO;QACLC,aAAa;QACbC,UAAUF,KAAKE,QAAQ;QACvBC,WAAWH,KAAKG,SAAS;QACzBC,SAASC;IACX;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC,eAAiD,EAC/DC,EAAE,EACFC,GAAG,EACHC,kBAAkBf,iBAAiB,EACnCgB,QAAQ,EACRC,UAAU,IAAI,EACdC,aAAa,EACbC,gBAAgB,EACyB;qBAuIhCC;QAJAA,aACKA;IAnId,MAAM,CAACC,SAASC,SAAS,G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AQ;QAC1B8C,KAAK,GAAElC,eAAAA,MAAMkC,KAAK,YAAXlC,eAAeT;QACtBF,WAAWY,QAAQZ,SAAS;QAC5BC,SAASW,QAAQX,OAAO;QACxBgC;QACAE;QACAE;QACAC;QACA,uEAAuE,GACvEP;IACF;AACF"}
@@ -27,5 +27,5 @@ import type { UseEntityFormOptions, UseEntityFormResult } from './use-entity-for
27
27
  * form by the record id to reseed — the same convention `EntityForm`'s wrappers
28
28
  * already follow.
29
29
  */
30
- export declare function useEntityForm<TEntity extends Entity>({ entityConstructor, entity, draft, fields, schema, validate, validationMessages, translateKey, onSubmit, }: UseEntityFormOptions<TEntity>): UseEntityFormResult;
30
+ export declare function useEntityForm<TEntity extends Entity>({ entityConstructor, entity, draft, fields, schema, validate, translateKey, onSubmit, }: UseEntityFormOptions<TEntity>): UseEntityFormResult;
31
31
  //# sourceMappingURL=use-entity-form.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-entity-form.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-entity-form/use-entity-form.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,MAAM,EAKZ,MAAM,eAAe,CAAC;AAWvB,OAAO,KAAK,EACV,oBAAoB,EACpB,mBAAmB,EACpB,MAAM,4BAA4B,CAAC;AAEpC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,aAAa,CAAC,OAAO,SAAS,MAAM,EAAE,EACpD,iBAAiB,EACjB,MAAM,EACN,KAAK,EACL,MAAM,EACN,MAAM,EACN,QAAQ,EACR,kBAAkB,EAClB,YAAY,EACZ,QAAQ,GACT,EAAE,oBAAoB,CAAC,OAAO,CAAC,GAAG,mBAAmB,CAuMrD"}
1
+ {"version":3,"file":"use-entity-form.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-entity-form/use-entity-form.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,MAAM,EAKZ,MAAM,eAAe,CAAC;AAWvB,OAAO,KAAK,EACV,oBAAoB,EACpB,mBAAmB,EACpB,MAAM,4BAA4B,CAAC;AAEpC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,aAAa,CAAC,OAAO,SAAS,MAAM,EAAE,EACpD,iBAAiB,EACjB,MAAM,EACN,KAAK,EACL,MAAM,EACN,MAAM,EACN,QAAQ,EACR,YAAY,EACZ,QAAQ,GACT,EAAE,oBAAoB,CAAC,OAAO,CAAC,GAAG,mBAAmB,CAgMrD"}
@@ -140,14 +140,15 @@ export declare function composeEntityFormErrors({ descriptors, values, messages,
140
140
  fields: Record<string, string>;
141
141
  form?: string;
142
142
  };
143
+ /** Resolves a catalog key, with its parameters, in the reader's language. */
144
+ export type TranslateKey = (key: string, params?: Record<string, unknown>) => string;
143
145
  /**
144
- * What a caller who supplies no {@link ValidationMessages} gets: the catalog key
145
- * itself, with the field appended.
146
- *
147
- * Honest rather than English — there is no catalog in this package to resolve
148
- * against — and visible enough in a form that a host notices it has wired no
149
- * copy. It sits beside the validator rather than in `.types.ts`, which this
150
- * repository keeps type-only.
146
+ * The form's validation sentences, from the `controls` catalog's
147
+ * `validation.*` copy. Built from the caller's translator because this package
148
+ * holds no catalog, and a key must never reach the screen (ADR 0028): the
149
+ * controls package's `useTranslateKey` answers from its own catalog even with
150
+ * no i18n library installed. `count` doubles as the plural selector, so
151
+ * `minItems` reads "1 item" and "2 items".
151
152
  */
152
- export declare const DEFAULT_VALIDATION_MESSAGES: EntityDraftMessages;
153
+ export declare function validationMessagesFrom(translateKey: TranslateKey): EntityDraftMessages;
153
154
  //# sourceMappingURL=use-entity-form.helpers.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-entity-form.helpers.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-entity-form/use-entity-form.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,WAAW,EAChB,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAc1B,KAAK,gBAAgB,EAEtB,MAAM,eAAe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AAW,EACX,MAAM,EACN,QAAQ,EACR,QAAQ,EACR,MAAM,EACN,cAAc,EACd,QAAQ,GACT,EAAE,8BAA8B,GAAG;IAClC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,CAUA;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,2BAA2B,EAAE,mBASzC,CAAC"}
1
+ {"version":3,"file":"use-entity-form.helpers.d.ts","sourceRoot":"","sources":["../../../src/hooks/use-entity-form/use-entity-form.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,WAAW,EAChB,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAc1B,KAAK,gBAAgB,EAEtB,MAAM,eAAe,CAAC;AAwCvB;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,cAAc,CAC5B,UAAU,EAAE,qBAAqB,EACjC,MAAM,EAAE,OAAO,GACd,gBAAgB,CAQlB;AAuED,4EAA4E;AAC5E,wBAAgB,eAAe,CAC7B,WAAW,EAAE,SAAS,qBAAqB,EAAE,EAC7C,MAAM,EAAE,OAAO,GACd,WAAW,CAMb;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,kBAAkB,CAChC,WAAW,EAAE,SAAS,qBAAqB,EAAE,EAC7C,IAAI,EAAE,WAAW,EACjB,SAAS,EAAE,WAAW,GAAG,SAAS,GACjC,WAAW,CA0Bb;AAED,2EAA2E;AAC3E,MAAM,WAAW,cAAc;IAC7B,MAAM,CAAC,EAAE,SAAS,OAAO,EAAE,CAAC;CAC7B;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC7B,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,GAAG,SAAS,CAAC,CAAC,GAC7D,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CASxB;AAED;;;;;GAKG;AACH;;;;;GAKG;AACH,M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;AAC3E,MAAM,WAAW,8BAA8B;IAC7C,WAAW,EAAE,SAAS,qBAAqB,EAAE,CAAC;IAC9C,MAAM,EAAE,WAAW,CAAC;IACpB,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,oFAAoF;IACpF,QAAQ,CAAC,EAAE,kBAAkB,CAAC;IAC9B,MAAM,CAAC,EAAE,gBAAgB,CAAC;IAC1B,cAAc,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,KAAK,MAAM,CAAC;IACvE,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC5D;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,EACtC,WAAW,EACX,MAAM,EACN,QAAQ,EACR,QAAQ,EACR,MAAM,EACN,cAAc,EACd,QAAQ,GACT,EAAE,8BAA8B,GAAG;IAClC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,CAUA;AAED,6EAA6E;AAC7E,MAAM,MAAM,YAAY,GAAG,CACzB,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAC7B,MAAM,CAAC;AAEZ;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,YAAY,EAAE,YAAY,GACzB,mBAAmB,CAqBrB"}
@@ -409,22 +409,38 @@ const labelOf = (descriptor)=>descriptor.label;
409
409
  };
410
410
  }
411
411
  /**
412
- * What a caller who supplies no {@link ValidationMessages} gets: the catalog key
413
- * itself, with the field appended.
414
- *
415
- * Honest rather than English — there is no catalog in this package to resolve
416
- * against — and visible enough in a form that a host notices it has wired no
417
- * copy. It sits beside the validator rather than in `.types.ts`, which this
418
- * repository keeps type-only.
419
- */ export const DEFAULT_VALIDATION_MESSAGES = {
420
- required: (field)=>`validation.required:${field}`,
421
- number: (field)=>`validation.number:${field}`,
422
- date: (field)=>`validation.date:${field}`,
423
- option: (field)=>`validation.option:${field}`,
424
- minItems: (field, count)=>`validation.minItems:${field}:${count}`,
425
- maxItems: (field, count)=>`validation.maxItems:${field}:${count}`,
426
- notBefore: (field, other)=>`validation.notBefore:${field}:${other}`,
427
- locale: (field, locale)=>`validation.locale:${field}:${locale}`
428
- };
412
+ * The form's validation sentences, from the `controls` catalog's
413
+ * `validation.*` copy. Built from the caller's translator because this package
414
+ * holds no catalog, and a key must never reach the screen (ADR 0028): the
415
+ * controls package's `useTranslateKey` answers from its own catalog even with
416
+ * no i18n library installed. `count` doubles as the plural selector, so
417
+ * `minItems` reads "1 item" and "2 items".
418
+ */ export function validationMessagesFrom(translateKey) {
419
+ const say = (failure)=>(field)=>translateKey(`controls:validation.${failure}`, {
420
+ field
421
+ });
422
+ return {
423
+ required: say('required'),
424
+ number: say('number'),
425
+ date: say('date'),
426
+ option: say('option'),
427
+ minItems: (field, count)=>translateKey('controls:validation.minItems', {
428
+ field,
429
+ count
430
+ }),
431
+ maxItems: (field, count)=>translateKey('controls:validation.maxItems', {
432
+ field,
433
+ count
434
+ }),
435
+ notBefore: (field, other)=>translateKey('controls:validation.notBefore', {
436
+ field,
437
+ other
438
+ }),
439
+ locale: (field, locale)=>translateKey('controls:validation.locale', {
440
+ field,
441
+ locale: locale.toUpperCase()
442
+ })
443
+ };
444
+ }
429
445
 
430
446
  //# sourceMappingURL=use-entity-form.helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/hooks/use-entity-form/use-entity-form.helpers.ts"],"sourcesContent":["import {\n describeChildColumns,\n editableChildColumns,\n EntityCollectionLink,\n type EntityDraft,\n type EntityDraftValue,\n type EntityFieldDescriptor,\n EntityLink,\n type EntityLocalizedDraft,\n type EntityRowDraft,\n isLocalizedText,\n isRowDraftArray,\n joinFieldPath,\n locales,\n readDraftString,\n readLocalizedDraft,\n readRowDrafts,\n ROW_KEY,\n rowFieldPath,\n seededRowKey,\n type StandardSchemaV1,\n type StandardSchemaV1Issue,\n} from '@entifix/core';\n\n/**\n * A member no form writes back, whatever the draft says about it — and the only\n * one is a read-only member, because it is the only one no editor may ever\n * exist for.\n *\n * `linkCollection` used to be here too, which meant `required` on a to-many\n * relation was silently unenforced: a rule the entity declared and the form\n * never applied. Whether a collection has an editor yet is a question about the\n * controls, not about what the domain insists on, so it is excluded from the\n * *format* check below instead.\n */\nfunction isNeverEdited(descriptor: EntityFieldDescriptor): boolean {\n return descriptor.readonly;\n}\n\n/**\n * A member whose *format* the metadata can judge. Both relation shapes are\n * excluded: their draft value is a foreign key (or a joined list of them), and\n * \"is this a real id\" is a question only the service can answer — but whether\n * one is present at all is checked, which is what `required` on a relation has\n * to mean.\n *\n * A `composition` is excluded here too, but it is no longer unjudged: its rows\n * are checked one at a time by {@link validateRowDrafts}, against the child's\n * own descriptors. What has no meaning is a *format* rule on the collection\n * itself — there is no string to judge, only rows.\n *\n * `scalarCollection` is deliberately *not* excluded — its comma list is real\n * text the user typed.\n */\nfunction hasCheckableFormat(descriptor: EntityFieldDescriptor): boolean {\n return (\n descriptor.type !== 'link' &&\n descriptor.type !== 'linkCollection' &&\n descriptor.type !== 'composition'\n );\n}\n\n/**\n * The value a field seeds with from a record.\n *\n * A scalar seeds as a **string**: links with their foreign key(s), dates with a\n * `yyyy-mm-dd` value a `date` input accepts, everything else stringified.\n *\n * The array branch is explicit rather than left to `String(raw)`, even though\n * the two produce the same characters today. `String(['a','b'])` is `'a,b'` by\n * way of `Array.prototype.toString`, which is an accident: it was doing the\n * work of a `scalarCollection` seed before the type existed, and\n * `reconstructEntity` was handing the same string straight back as a `string`.\n * Both halves were wrong in the same direction, so the fixed-point spec could\n * not see it. Now the join is declared here and the split is declared there,\n * and they are inverses on purpose.\n *\n * A **`composition`** is the one member that does not seed as a string, because\n * it has no lossless string form at all — its rows seed as row drafts, each\n * with a freshly minted key. That key is the only thing here the record does not\n * supply, and it is minted at seed time rather than at render so that the rows a\n * form starts with are already addressable.\n */\nexport function seedFieldValue(\n descriptor: EntityFieldDescriptor,\n entity: unknown,\n): EntityDraftValue {\n if (descriptor.type === 'composition') {\n return seedRowDrafts(descriptor, entity);\n }\n if (descriptor.type === 'localized') {\n return seedLocalizedDraft(descriptor, entity);\n }\n return seedScalarValue(descriptor, entity);\n}\n\n/**\n * A `localized` member seeds one input per declared locale, each holding that\n * locale's text or `''`. Every declared locale is present even when the record\n * lacks it, so the form shows the empty input a translator has to fill.\n */\nfunction seedLocalizedDraft(\n descriptor: EntityFieldDescriptor,\n entity: unknown,\n): EntityLocalizedDraft {\n const raw = (entity as Record<string, unknown> | null | undefined)?.[\n descriptor.name\n ];\n const text = isLocalizedText(raw) ? raw : {};\n return Object.fromEntries(\n locales().map(locale => [locale, text[locale] ?? '']),\n );\n}\n\n/** {@link seedFieldValue} for every member that round-trips through a string. */\nfunction seedScalarValue(\n descriptor: EntityFieldDescriptor,\n entity: unknown,\n): string {\n if (entity == null) return '';\n const raw = (entity as Record<string, unknown>)[descriptor.name];\n if (raw == null) return '';\n if (raw instanceof EntityLink) return raw.id == null ? '' : String(raw.id);\n if (raw instanceof EntityCollectionLink) return raw.ids.map(String).join(',');\n if (raw instanceof Date) return raw.toISOString().slice(0, 10);\n if (Array.isArray(raw)) return raw.map(String).join(',');\n return String(raw);\n}\n\n/**\n * The rows a composition member seeds with.\n *\n * Each row is walked with the child's **own** descriptors, through the same\n * `seedScalarValue` the master's members use — so a child's `date` seeds as\n * `yyyy-mm-dd` on a line exactly as it would on a record, and\n * `reconstructChild` is its inverse for the same reason `coerceFieldValue` is.\n *\n * A row arrives as a plain object as readily as an instance (a payload off the\n * wire, a fixture), which is fine: nothing here asks what class it is, matching\n * `ChildConstructor`'s rule that a child is never `instanceof`-tested.\n *\n * A member with no declared child seeds as no rows — there are no columns to\n * walk, so there is nothing a row could be.\n */\nfunction seedRowDrafts(\n descriptor: EntityFieldDescriptor,\n entity: unknown,\n): EntityRowDraft[] {\n if (entity == null || descriptor.childType === undefined) return [];\n const raw = (entity as Record<string, unknown>)[descriptor.name];\n if (!Array.isArray(raw)) return [];\n\n const columns = describeChildColumns(descriptor.childType);\n\n return raw.map((row, index) => {\n // Deterministic, so re-seeding the same record produces the same draft —\n // see `seededRowKey` for the render loop the random one causes.\n const draft: EntityRowDraft = { [ROW_KEY]: seededRowKey(index) };\n for (const column of columns) {\n draft[column.name] = seedScalarValue(column, row);\n }\n return draft;\n });\n}\n\n/** Builds the initial draft for a record (or an empty one for a create). */\nexport function seedEntityDraft(\n descriptors: readonly EntityFieldDescriptor[],\n entity: unknown,\n): EntityDraft {\n const draft: EntityDraft = {};\n for (const descriptor of descriptors) {\n draft[descriptor.name] = seedFieldValue(descriptor, entity);\n }\n return draft;\n}\n\n/**\n * Restores a persisted draft **over** a freshly seeded one, rather than in place\n * of it.\n *\n * A draft outlives the entity that wrote it — it sits in IndexedDB across\n * refreshes and deployments — so the two can disagree by the time it comes back.\n * Replacing the seed outright is how that disagreement becomes a bug the user\n * sees: a member added since the draft was written has no entry, reaches the form\n * engine as `undefined`, and its input flips from controlled to uncontrolled\n * mid-render. A member since removed goes the other way, surviving as a value\n * nothing renders and `reconstructEntity` cannot assign.\n *\n * So the seed decides the *keys* and the draft decides the *values*: a name the\n * entity no longer declares is dropped, and a name it declares that the draft\n * lacks keeps its seeded value.\n *\n * **A value is restored only in the shape its member can hold**, which is now\n * two shapes rather than one. A scalar takes a string; a `composition` takes a\n * readable row list. Anything else is dropped back to its seed — a member that\n * changed type between the write and the read, or a row list from a build that\n * did not carry keys, restores as the record's own value instead of as\n * something no editor can render. This is per member, so one unreadable entry\n * never costs the user the rest of the form.\n *\n * This is the shape guard at the one place the shape is actually known. The\n * store-level version check (`drafts-state.ts`) can only decide that a whole\n * generation of drafts is unreadable; it cannot know which members one entity\n * declares.\n */\nexport function restoreEntityDraft(\n descriptors: readonly EntityFieldDescriptor[],\n seed: EntityDraft,\n persisted: EntityDraft | undefined,\n): EntityDraft {\n if (persisted === undefined) return seed;\n\n const restored: EntityDraft = { ...seed };\n for (const descriptor of descriptors) {\n const value = persisted[descriptor.name];\n if (value === undefined) continue;\n\n if (descriptor.type === 'composition') {\n if (isRowDraftArray(value)) restored[descriptor.name] = value;\n continue;\n }\n if (descriptor.type === 'localized') {\n // Over the seed rather than instead of it, so a locale declared since\n // the draft was saved still gets its (empty) input.\n if (isLocalizedText(value)) {\n restored[descriptor.name] = {\n ...readLocalizedDraft(seed, descriptor.name),\n ...readLocalizedDraft(persisted, descriptor.name),\n };\n }\n continue;\n }\n if (typeof value === 'string') restored[descriptor.name] = value;\n }\n return restored;\n}\n\n/** The slice of a form field's state this module reads: its error list. */\nexport interface FieldErrorMeta {\n errors?: readonly unknown[];\n}\n\n/**\n * Flattens the form engine's per-field state into the `name → message` map the\n * agnostic `EntityForm` renders. Only the first message per field survives: a\n * row shows one line, and the metadata rules already stop at the first failure.\n *\n * Kept structural rather than typed against the engine so the rest of this\n * module stays independent of which form library backs the hook.\n */\nexport function readFieldErrors(\n fieldMeta: Partial<Record<string, FieldErrorMeta | undefined>>,\n): Record<string, string> {\n const errors: Record<string, string> = {};\n\n for (const [name, meta] of Object.entries(fieldMeta)) {\n const message = meta?.errors?.find(entry => typeof entry === 'string');\n if (typeof message === 'string') errors[name] = message;\n }\n\n return errors;\n}\n\n/**\n * The four metadata-derived messages, already localized. Taken as an argument\n * rather than built here so this stays a pure function — and because the\n * sentence cannot be assembled from a label plus a hardcoded suffix: word order\n * differs between locales.\n */\n/**\n * How a message names a field. The default is the descriptor's `label`, which is\n * the accessor's `label` option or its humanized member name — never translated.\n * A host with a catalog resolves `labelKey` instead, so the message names the\n * field in the words its input and column header already use.\n */\nexport type EntityFieldLabeler = (descriptor: EntityFieldDescriptor) => string;\n\nconst labelOf: EntityFieldLabeler = descriptor => descriptor.label;\n\nexport interface EntityDraftMessages {\n required(field: string): string;\n number(field: string): string;\n date(field: string): string;\n option(field: string): string;\n /** A collection holding fewer than its `minItems`. */\n minItems(field: string, count: number): string;\n /** A collection holding more than its `maxItems`. */\n maxItems(field: string, count: number): string;\n /** A date before the one its `notBefore` names. */\n notBefore(field: string, other: string): string;\n /** A localized member with no text for one of the declared locales. */\n locale(field: string, locale: string): string;\n}\n\n/**\n * Validates a draft against what the metadata implies — `required` members must\n * be filled, and a filled `number`/`date`/`enum` must be well-formed. Read-only\n * members are skipped entirely; a relation is checked for presence but never\n * for format, since its draft value is a foreign key this side cannot resolve.\n *\n * Metadata is only the first of three rule sources; {@link composeEntityFormErrors}\n * is what layers a schema and the caller's own rules over this.\n */\nexport function validateEntityDraft(\n descriptors: readonly EntityFieldDescriptor[],\n values: EntityDraft,\n messages: EntityDraftMessages,\n labelFor: EntityFieldLabeler = labelOf,\n): Record<string, string> {\n const errors: Record<string, string> = {};\n\n for (const descriptor of descriptors) {\n if (isNeverEdited(descriptor)) continue;\n\n if (descriptor.type === 'composition') {\n Object.assign(\n errors,\n validateComposition(descriptor, values, messages, labelFor),\n );\n continue;\n }\n if (descriptor.type === 'localized') {\n const message = localizedMessage(descriptor, values, messages, labelFor);\n if (message !== undefined) errors[descriptor.name] = message;\n continue;\n }\n\n const raw = readDraftString(values, descriptor.name);\n\n if (descriptor.required && raw.trim() === '') {\n errors[descriptor.name] = messages.required(labelFor(descriptor));\n continue;\n }\n // Before the guard below: an empty list is a count of zero, and a link\n // collection's count is checkable though its ids are not.\n const counted = isCountedList(descriptor)\n ? itemCountMessage(descriptor, countItems(raw), messages, labelFor)\n : undefined;\n if (counted !== undefined) {\n errors[descriptor.name] = counted;\n continue;\n }\n if (raw === '' || !hasCheckableFormat(descriptor)) continue;\n\n const message =\n formatMessage(descriptor, raw, messages, labelFor) ??\n orderMessage(descriptor, raw, descriptors, values, messages, labelFor);\n if (message !== undefined) errors[descriptor.name] = message;\n }\n\n return errors;\n}\n\n/**\n * A localized member is all or nothing: left wholly empty it is absent, which\n * only `required` objects to; once any locale holds text, every declared one\n * must — the rule `validateRecords` holds stored content to, so a page never\n * shows one language in the middle of another.\n */\nfunction localizedMessage(\n descriptor: EntityFieldDescriptor,\n values: EntityDraft,\n messages: EntityDraftMessages,\n labelFor: EntityFieldLabeler,\n): string | undefined {\n const draft = readLocalizedDraft(values, descriptor.name);\n const missing = locales().filter(\n locale => (draft[locale] ?? '').trim() === '',\n );\n if (missing.length === locales().length) {\n return descriptor.required\n ? messages.required(labelFor(descriptor))\n : undefined;\n }\n const [first] = missing;\n return first === undefined\n ? undefined\n : messages.locale(labelFor(descriptor), first);\n}\n\n/** A collection whose draft is a comma list: values, or the ids of links. */\nfunction isCountedList(descriptor: EntityFieldDescriptor): boolean {\n return (\n descriptor.type === 'scalarCollection' ||\n descriptor.type === 'linkCollection'\n );\n}\n\n/** How many values a draft's comma list holds, blanks aside. */\nfunction countItems(raw: string): number {\n return raw.split(',').filter(item => item.trim() !== '').length;\n}\n\n/**\n * A collection's `minItems` / `maxItems`, judged on its count. The same rule\n * `validateRecords` applies to a stored record, so a draft the form accepts is\n * one a static build would too.\n */\nfunction itemCountMessage(\n descriptor: EntityFieldDescriptor,\n count: number,\n messages: EntityDraftMessages,\n labelFor: EntityFieldLabeler,\n): string | undefined {\n const { minItems, maxItems } = descriptor;\n if (minItems !== undefined && count < minItems) {\n return messages.minItems(labelFor(descriptor), minItems);\n }\n if (maxItems !== undefined && count > maxItems) {\n return messages.maxItems(labelFor(descriptor), maxItems);\n }\n return undefined;\n}\n\n/**\n * `notBefore`: a filled date that precedes the filled date it names. Either one\n * empty, or unparseable, is someone else's message.\n */\nfunction orderMessage(\n descriptor: EntityFieldDescriptor,\n raw: string,\n descriptors: readonly EntityFieldDescriptor[],\n values: EntityDraft,\n messages: EntityDraftMessages,\n labelFor: EntityFieldLabeler,\n): string | undefined {\n if (descriptor.notBefore === undefined) return undefined;\n const earlier = descriptors.find(\n other => other.name === descriptor.notBefore,\n );\n const start = new Date(readDraftString(values, descriptor.notBefore));\n if (earlier === undefined || Number.isNaN(start.getTime())) return undefined;\n return new Date(raw) < start\n ? messages.notBefore(labelFor(descriptor), labelFor(earlier))\n : undefined;\n}\n\n/**\n * The metadata rule for one filled scalar draft value, or `undefined` when it\n * passes.\n *\n * Extracted so a row's cell is judged by the **same** rule as a record's field.\n * Two copies is how a child's `number` member would quietly start accepting\n * something its master's would reject.\n */\nfunction formatMessage(\n descriptor: EntityFieldDescriptor,\n raw: string,\n messages: EntityDraftMessages,\n labelFor: EntityFieldLabeler,\n): string | undefined {\n if (descriptor.type === 'number' && Number.isNaN(Number(raw))) {\n return messages.number(labelFor(descriptor));\n }\n if (descriptor.type === 'date' && Number.isNaN(new Date(raw).getTime())) {\n return messages.date(labelFor(descriptor));\n }\n if (\n descriptor.type === 'enum' &&\n descriptor.enumValues &&\n !descriptor.enumValues.includes(raw)\n ) {\n return messages.option(labelFor(descriptor));\n }\n return undefined;\n}\n\n/**\n * The rules an owned collection carries, at both of its levels.\n *\n * **`required` on the collection means \"at least one row\"** — the only thing a\n * master can assert about a collection it owns, and a genuinely different fact\n * from `required` on a child member, which is per row. Conflating the two would\n * make an order with three lines, one of them blank, indistinguishable from an\n * order with none.\n *\n * A row's own members are judged against the child's descriptors and reported at\n * `items[2].quantity`, so the grid can put the message in the cell that caused\n * it. Read-only child members are skipped for the reason they always are: no\n * editor exists for them, so no rule the user could satisfy applies.\n */\nfunction validateComposition(\n descriptor: EntityFieldDescriptor,\n values: EntityDraft,\n messages: EntityDraftMessages,\n labelFor: EntityFieldLabeler,\n): Record<string, string> {\n const errors: Record<string, string> = {};\n const rows = readRowDrafts(values[descriptor.name]);\n\n if (descriptor.required && rows.length === 0) {\n errors[descriptor.name] = messages.required(labelFor(descriptor));\n return errors;\n }\n const counted = itemCountMessage(descriptor, rows.length, messages, labelFor);\n if (counted !== undefined) errors[descriptor.name] = counted;\n if (descriptor.childType === undefined) return errors;\n\n const columns = editableChildColumns(\n describeChildColumns(descriptor.childType),\n );\n\n rows.forEach((row, index) => {\n for (const column of columns) {\n if (isNeverEdited(column)) continue;\n\n const raw = row[column.name] ?? '';\n const path = rowFieldPath(descriptor.name, index, column.name);\n\n if (column.required && raw.trim() === '') {\n errors[path] = messages.required(labelFor(column));\n continue;\n }\n if (raw === '') continue;\n\n const message = formatMessage(column, raw, messages, labelFor);\n if (message !== undefined) errors[path] = message;\n }\n });\n\n return errors;\n}\n\n/**\n * The error-map key an issue belongs to — the **whole** path, not its head.\n *\n * It used to read `issue.path?.[0]`, which was right while every member was a\n * scalar and wrong the moment one held rows: `['items', 2, 'quantity']`\n * collapsed to `'items'`, so a rule about the third line's quantity reported\n * itself against the collection and the grid had no way to know which cell it\n * meant. Joining instead produces `items[2].quantity`, which is the key\n * `validateComposition` already writes — so a schema rule and a metadata rule\n * address the same cell the same way and `composeEntityFormErrors` can merge\n * them.\n *\n * A one-segment path still yields exactly the head, so no existing rule changes\n * meaning.\n */\nfunction issueFieldName(issue: StandardSchemaV1Issue): string | undefined {\n const path = issue.path;\n if (path == null || path.length === 0) return undefined;\n\n const segments = path.map(segment => {\n const raw =\n typeof segment === 'object' && segment !== null && 'key' in segment\n ? segment.key\n : segment;\n return typeof raw === 'number' ? raw : String(raw);\n });\n\n return joinFieldPath(segments);\n}\n\n/**\n * Runs a Standard Schema over the draft and sorts its issues into per-field\n * messages plus a form-level one (an issue with no path — a cross-field rule).\n *\n * **Schemas are authored against the string draft**, so they coerce\n * (`z.coerce.number()`) rather than expect typed values: the draft is what the\n * inputs round-trip, and the same schema then validates exactly what the user\n * sees. Only the first issue per field survives, matching how a row renders.\n *\n * Synchronous rules only. An async schema returns a Promise the form's\n * synchronous validation pass cannot wait on, so it is rejected loudly rather\n * than silently passing.\n */\nexport function readSchemaIssues(\n schema: StandardSchemaV1,\n values: EntityDraft,\n translateIssue: (message: string, field: string | undefined) => string,\n): { fields: Record<string, string>; form?: string } {\n const result = schema['~standard'].validate(values);\n\n if (result instanceof Promise) {\n throw new Error(\n 'useEntityForm cannot run an async schema: its validation pass is ' +\n 'synchronous. Move the asynchronous rule into the `validate` option.',\n );\n }\n if (!result.issues) return { fields: {} };\n\n const fields: Record<string, string> = {};\n let form: string | undefined;\n\n for (const issue of result.issues) {\n const name = issueFieldName(issue);\n const message = translateIssue(issue.message, name);\n\n if (name === undefined) form ??= message;\n else fields[name] ??= message;\n }\n\n return { fields, form };\n}\n\n/** Everything {@link composeEntityFormErrors} needs to judge one draft. */\nexport interface ComposeEntityFormErrorsOptions {\n descriptors: readonly EntityFieldDescriptor[];\n values: EntityDraft;\n messages: EntityDraftMessages;\n /** How a metadata message names its field. Defaults to the untranslated `label`. */\n labelFor?: EntityFieldLabeler;\n schema?: StandardSchemaV1;\n translateIssue: (message: string, field: string | undefined) => string;\n validate?: (values: EntityDraft) => Record<string, string>;\n}\n\n/**\n * The single composition point for a draft's errors: metadata rules first, then\n * the entity's schema, then the caller's `validate` callback. Later sources win\n * on conflict, so a caller can always override a message it disagrees with.\n */\nexport function composeEntityFormErrors({\n descriptors,\n values,\n messages,\n labelFor,\n schema,\n translateIssue,\n validate,\n}: ComposeEntityFormErrorsOptions): {\n fields: Record<string, string>;\n form?: string;\n} {\n const metadata = validateEntityDraft(descriptors, values, messages, labelFor);\n const schemaIssues = schema\n ? readSchemaIssues(schema, values, translateIssue)\n : { fields: {}, form: undefined };\n\n return {\n fields: { ...metadata, ...schemaIssues.fields, ...validate?.(values) },\n form: schemaIssues.form,\n };\n}\n\n/**\n * What a caller who supplies no {@link ValidationMessages} gets: the catalog key\n * itself, with the field appended.\n *\n * Honest rather than English — there is no catalog in this package to resolve\n * against — and visible enough in a form that a host notices it has wired no\n * copy. It sits beside the validator rather than in `.types.ts`, which this\n * repository keeps type-only.\n */\nexport const DEFAULT_VALIDATION_MESSAGES: EntityDraftMessages = {\n required: field => `validation.required:${field}`,\n number: field => `validation.number:${field}`,\n date: field => `validation.date:${field}`,\n option: field => `validation.option:${field}`,\n minItems: (field, count) => `validation.minItems:${field}:${count}`,\n maxItems: (field, count) => `validation.maxItems:${field}:${count}`,\n notBefore: (field, other) => `validation.notBefore:${field}:${other}`,\n locale: (field, locale) => `validation.locale:${field}:${locale}`,\n};\n"],"names":["describeChildColumns","editableChildColumns","EntityCollectionLink","EntityLink","isLocalizedText","isRowDraftArray","joinFieldPath","locales","readDraftString","readLocalizedDraft","readRowDrafts","ROW_KEY","rowFieldPath","seededRowKey","isNeverEdited","descriptor","readonly","hasCheckableFormat","type","seedFieldValue","entity","seedRowDrafts","seedLocalizedDraft","seedScalarValue","raw","name","text","Object","fromEntries","map","locale","id","String","ids","join","Date","toISOString","slice","Array","isArray","childType","undefined","columns","row","index","draft","column","seedEntityDraft","descriptors","restoreEntityDraft","seed","persisted","restored","value","readFieldErrors","fieldMeta","errors","meta","entries","message","find","entry","labelOf","label","validateEntityDraft","values","messages","labelFor","formatMessage","assign","validateComposition","localizedMessage","required","trim","counted","isCountedList","itemCountMessage","countItems","orderMessage","missing","filter","length","first","split","item","count","minItems","maxItems","notBefore","earlier","other","start","Number","isNaN","getTime","number","date","enumValues","includes","option","rows","forEach","path","issueFieldName","issue","segments","segment","key","readSchemaIssues","schema","translateIssue","result","validate","Promise","Error","issues","fields","form","composeEntityFormErrors","metadata","schemaIssues","DEFAULT_VALIDATION_MESSAGES","field"],"mappings":";AAAA,SACEA,oBAAoB,EACpBC,oBAAoB,EACpBC,oBAAoB,EAIpBC,UAAU,EAGVC,eAAe,EACfC,eAAe,EACfC,aAAa,EACbC,OAAO,EACPC,eAAe,EACfC,kBAAkB,EAClBC,aAAa,EACbC,OAAO,EACPC,YAAY,EACZC,YAAY,QAGP,gBAAgB;AAEvB;;;;;;;;;;CAUC,GACD,SAASC,cAAcC,UAAiC;IACtD,OAAOA,WAAWC,QAAQ;AAC5B;AAEA;;;;;;;;;;;;;;CAcC,GACD,SAASC,mBAAmBF,UAAiC;IAC3D,OACEA,WAAWG,IAAI,KAAK,UACpBH,WAAWG,IAAI,KAAK,oBACpBH,WAAWG,IAAI,KAAK;AAExB;AAEA;;;;;;;;;;;;;;;;;;;;CAoB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QC;IAAK;AACxB;AAcA;;;;CAIC,GACD,OAAO,SAASC,wBAAwB,EACtCtE,WAAW,EACXiB,MAAM,EACNC,QAAQ,EACRC,QAAQ,EACR0C,MAAM,EACNC,cAAc,EACdE,QAAQ,EACuB;IAI/B,MAAMO,WAAWvD,oBAAoBhB,aAAaiB,QAAQC,UAAUC;IACpE,MAAMqD,eAAeX,SACjBD,iBAAiBC,QAAQ5C,QAAQ6C,kBACjC;QAAEM,QAAQ,CAAC;QAAGC,MAAM5E;IAAU;IAElC,OAAO;QACL2E,QAAQ,aAAKG,UAAaC,aAAaJ,MAAM,EAAKJ,4BAAAA,SAAW/C;QAC7DoD,MAAMG,aAAaH,IAAI;IACzB;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,MAAMI,8BAAmD;IAC9DjD,UAAUkD,CAAAA,QAAS,CAAC,oBAAoB,EAAEA,OAAO;IACjD3B,QAAQ2B,CAAAA,QAAS,CAAC,kBAAkB,EAAEA,OAAO;IAC7C1B,MAAM0B,CAAAA,QAAS,CAAC,gBAAgB,EAAEA,OAAO;IACzCvB,QAAQuB,CAAAA,QAAS,CAAC,kBAAkB,EAAEA,OAAO;IAC7CpC,UAAU,CAACoC,OAAOrC,QAAU,CAAC,oBAAoB,EAAEqC,MAAM,CAAC,EAAErC,OAAO;IACnEE,UAAU,CAACmC,OAAOrC,QAAU,CAAC,oBAAoB,EAAEqC,MAAM,CAAC,EAAErC,OAAO;IACnEG,WAAW,CAACkC,OAAOhC,QAAU,CAAC,qBAAqB,EAAEgC,MAAM,CAAC,EAAEhC,OAAO;IACrE5D,QAAQ,CAAC4F,OAAO5F,SAAW,CAAC,kBAAkB,EAAE4F,MAAM,CAAC,EAAE5F,QAAQ;AACnE,EAAE"}
1
+ {"version":3,"sources":["../../../src/hooks/use-entity-form/use-entity-form.helpers.ts"],"sourcesContent":["import {\n describeChildColumns,\n editableChildColumns,\n EntityCollectionLink,\n type EntityDraft,\n type EntityDraftValue,\n type EntityFieldDescriptor,\n EntityLink,\n type EntityLocalizedDraft,\n type EntityRowDraft,\n isLocalizedText,\n isRowDraftArray,\n joinFieldPath,\n locales,\n readDraftString,\n readLocalizedDraft,\n readRowDrafts,\n ROW_KEY,\n rowFieldPath,\n seededRowKey,\n type StandardSchemaV1,\n type StandardSchemaV1Issue,\n} from '@entifix/core';\n\n/**\n * A member no form writes back, whatever the draft says about it — and the only\n * one is a read-only member, because it is the only one no editor may ever\n * exist for.\n *\n * `linkCollection` used to be here too, which meant `required` on a to-many\n * relation was silently unenforced: a rule the entity declared and the form\n * never applied. Whether a collection has an editor yet is a question about the\n * controls, not about what the domain insists on, so it is excluded from the\n * *format* check below instead.\n */\nfunction isNeverEdited(descriptor: EntityFieldDescriptor): boolean {\n return descriptor.readonly;\n}\n\n/**\n * A member whose *format* the metadata can judge. Both relation shapes are\n * excluded: their draft value is a foreign key (or a joined list of them), and\n * \"is this a real id\" is a question only the service can answer — but whether\n * one is present at all is checked, which is what `required` on a relation has\n * to mean.\n *\n * A `composition` is excluded here too, but it is no longer unjudged: its rows\n * are checked one at a time by {@link validateRowDrafts}, against the child's\n * own descriptors. What has no meaning is a *format* rule on the collection\n * itself — there is no string to judge, only rows.\n *\n * `scalarCollection` is deliberately *not* excluded — its comma list is real\n * text the user typed.\n */\nfunction hasCheckableFormat(descriptor: EntityFieldDescriptor): boolean {\n return (\n descriptor.type !== 'link' &&\n descriptor.type !== 'linkCollection' &&\n descriptor.type !== 'composition'\n );\n}\n\n/**\n * The value a field seeds with from a record.\n *\n * A scalar seeds as a **string**: links with their foreign key(s), dates with a\n * `yyyy-mm-dd` value a `date` input accepts, everything else stringified.\n *\n * The array branch is explicit rather than left to `String(raw)`, even though\n * the two produce the same characters today. `String(['a','b'])` is `'a,b'` by\n * way of `Array.prototype.toString`, which is an accident: it was doing the\n * work of a `scalarCollection` seed before the type existed, and\n * `reconstructEntity` was handing the same string straight back as a `string`.\n * Both halves were wrong in the same direction, so the fixed-point spec could\n * not see it. Now the join is declared here and the split is declared there,\n * and they are inverses on purpose.\n *\n * A **`composition`** is the one member that does not seed as a string, because\n * it has no lossless string form at all — its rows seed as row drafts, each\n * with a freshly minted key. That key is the only thing here the record does not\n * supply, and it is minted at seed time rather than at render so that the rows a\n * form starts with are already addressable.\n */\nexport function seedFieldValue(\n descriptor: EntityFieldDescriptor,\n entity: unknown,\n): EntityDraftValue {\n if (descriptor.type === 'composition') {\n return seedRowDrafts(descriptor, entity);\n }\n if (descriptor.type === 'localized') {\n return seedLocalizedDraft(descriptor, entity);\n }\n return seedScalarValue(descriptor, entity);\n}\n\n/**\n * A `localized` member seeds one input per declared locale, each holding that\n * locale's text or `''`. Every declared locale is present even when the record\n * lacks it, so the form shows the empty input a translator has to fill.\n */\nfunction seedLocalizedDraft(\n descriptor: EntityFieldDescriptor,\n entity: unknown,\n): EntityLocalizedDraft {\n const raw = (entity as Record<string, unknown> | null | undefined)?.[\n descriptor.name\n ];\n const text = isLocalizedText(raw) ? raw : {};\n return Object.fromEntries(\n locales().map(locale => [locale, text[locale] ?? '']),\n );\n}\n\n/** {@link seedFieldValue} for every member that round-trips through a string. */\nfunction seedScalarValue(\n descriptor: EntityFieldDescriptor,\n entity: unknown,\n): string {\n if (entity == null) return '';\n const raw = (entity as Record<string, unknown>)[descriptor.name];\n if (raw == null) return '';\n if (raw instanceof EntityLink) return raw.id == null ? '' : String(raw.id);\n if (raw instanceof EntityCollectionLink) return raw.ids.map(String).join(',');\n if (raw instanceof Date) return raw.toISOString().slice(0, 10);\n if (Array.isArray(raw)) return raw.map(String).join(',');\n return String(raw);\n}\n\n/**\n * The rows a composition member seeds with.\n *\n * Each row is walked with the child's **own** descriptors, through the same\n * `seedScalarValue` the master's members use — so a child's `date` seeds as\n * `yyyy-mm-dd` on a line exactly as it would on a record, and\n * `reconstructChild` is its inverse for the same reason `coerceFieldValue` is.\n *\n * A row arrives as a plain object as readily as an instance (a payload off the\n * wire, a fixture), which is fine: nothing here asks what class it is, matching\n * `ChildConstructor`'s rule that a child is never `instanceof`-tested.\n *\n * A member with no declared child seeds as no rows — there are no columns to\n * walk, so there is nothing a row could be.\n */\nfunction seedRowDrafts(\n descriptor: EntityFieldDescriptor,\n entity: unknown,\n): EntityRowDraft[] {\n if (entity == null || descriptor.childType === undefined) return [];\n const raw = (entity as Record<string, unknown>)[descriptor.name];\n if (!Array.isArray(raw)) return [];\n\n const columns = describeChildColumns(descriptor.childType);\n\n return raw.map((row, index) => {\n // Deterministic, so re-seeding the same record produces the same draft —\n // see `seededRowKey` for the render loop the random one causes.\n const draft: EntityRowDraft = { [ROW_KEY]: seededRowKey(index) };\n for (const column of columns) {\n draft[column.name] = seedScalarValue(column, row);\n }\n return draft;\n });\n}\n\n/** Builds the initial draft for a record (or an empty one for a create). */\nexport function seedEntityDraft(\n descriptors: readonly EntityFieldDescriptor[],\n entity: unknown,\n): EntityDraft {\n const draft: EntityDraft = {};\n for (const descriptor of descriptors) {\n draft[descriptor.name] = seedFieldValue(descriptor, entity);\n }\n return draft;\n}\n\n/**\n * Restores a persisted draft **over** a freshly seeded one, rather than in place\n * of it.\n *\n * A draft outlives the entity that wrote it — it sits in IndexedDB across\n * refreshes and deployments — so the two can disagree by the time it comes back.\n * Replacing the seed outright is how that disagreement becomes a bug the user\n * sees: a member added since the draft was written has no entry, reaches the form\n * engine as `undefined`, and its input flips from controlled to uncontrolled\n * mid-render. A member since removed goes the other way, surviving as a value\n * nothing renders and `reconstructEntity` cannot assign.\n *\n * So the seed decides the *keys* and the draft decides the *values*: a name the\n * entity no longer declares is dropped, and a name it declares that the draft\n * lacks keeps its seeded value.\n *\n * **A value is restored only in the shape its member can hold**, which is now\n * two shapes rather than one. A scalar takes a string; a `composition` takes a\n * readable row list. Anything else is dropped back to its seed — a member that\n * changed type between the write and the read, or a row list from a build that\n * did not carry keys, restores as the record's own value instead of as\n * something no editor can render. This is per member, so one unreadable entry\n * never costs the user the rest of the form.\n *\n * This is the shape guard at the one place the shape is actually known. The\n * store-level version check (`drafts-state.ts`) can only decide that a whole\n * generation of drafts is unreadable; it cannot know which members one entity\n * declares.\n */\nexport function restoreEntityDraft(\n descriptors: readonly EntityFieldDescriptor[],\n seed: EntityDraft,\n persisted: EntityDraft | undefined,\n): EntityDraft {\n if (persisted === undefined) return seed;\n\n const restored: EntityDraft = { ...seed };\n for (const descriptor of descriptors) {\n const value = persisted[descriptor.name];\n if (value === undefined) continue;\n\n if (descriptor.type === 'composition') {\n if (isRowDraftArray(value)) restored[descriptor.name] = value;\n continue;\n }\n if (descriptor.type === 'localized') {\n // Over the seed rather than instead of it, so a locale declared since\n // the draft was saved still gets its (empty) input.\n if (isLocalizedText(value)) {\n restored[descriptor.name] = {\n ...readLocalizedDraft(seed, descriptor.name),\n ...readLocalizedDraft(persisted, descriptor.name),\n };\n }\n continue;\n }\n if (typeof value === 'string') restored[descriptor.name] = value;\n }\n return restored;\n}\n\n/** The slice of a form field's state this module reads: its error list. */\nexport interface FieldErrorMeta {\n errors?: readonly unknown[];\n}\n\n/**\n * Flattens the form engine's per-field state into the `name → message` map the\n * agnostic `EntityForm` renders. Only the first message per field survives: a\n * row shows one line, and the metadata rules already stop at the first failure.\n *\n * Kept structural rather than typed against the engine so the rest of this\n * module stays independent of which form library backs the hook.\n */\nexport function readFieldErrors(\n fieldMeta: Partial<Record<string, FieldErrorMeta | undefined>>,\n): Record<string, string> {\n const errors: Record<string, string> = {};\n\n for (const [name, meta] of Object.entries(fieldMeta)) {\n const message = meta?.errors?.find(entry => typeof entry === 'string');\n if (typeof message === 'string') errors[name] = message;\n }\n\n return errors;\n}\n\n/**\n * The four metadata-derived messages, already localized. Taken as an argument\n * rather than built here so this stays a pure function — and because the\n * sentence cannot be assembled from a label plus a hardcoded suffix: word order\n * differs between locales.\n */\n/**\n * How a message names a field. The default is the descriptor's `label`, which is\n * the accessor's `label` option or its humanized member name — never translated.\n * A host with a catalog resolves `labelKey` instead, so the message names the\n * field in the words its input and column header already use.\n */\nexport type EntityFieldLabeler = (descriptor: EntityFieldDescriptor) => string;\n\nconst labelOf: EntityFieldLabeler = descriptor => descriptor.label;\n\nexport interface EntityDraftMessages {\n required(field: string): string;\n number(field: string): string;\n date(field: string): string;\n option(field: string): string;\n /** A collection holding fewer than its `minItems`. */\n minItems(field: string, count: number): string;\n /** A collection holding more than its `maxItems`. */\n maxItems(field: string, count: number): string;\n /** A date before the one its `notBefore` names. */\n notBefore(field: string, other: string): string;\n /** A localized member with no text for one of the declared locales. */\n locale(field: string, locale: string): string;\n}\n\n/**\n * Validates a draft against what the metadata implies — `required` members must\n * be filled, and a filled `number`/`date`/`enum` must be well-formed. Read-only\n * members are skipped entirely; a relation is checked for presence but never\n * for format, since its draft value is a foreign key this side cannot resolve.\n *\n * Metadata is only the first of three rule sources; {@link composeEntityFormErrors}\n * is what layers a schema and the caller's own rules over this.\n */\nexport function validateEntityDraft(\n descriptors: readonly EntityFieldDescriptor[],\n values: EntityDraft,\n messages: EntityDraftMessages,\n labelFor: EntityFieldLabeler = labelOf,\n): Record<string, string> {\n const errors: Record<string, string> = {};\n\n for (const descriptor of descriptors) {\n if (isNeverEdited(descriptor)) continue;\n\n if (descriptor.type === 'composition') {\n Object.assign(\n errors,\n validateComposition(descriptor, values, messages, labelFor),\n );\n continue;\n }\n if (descriptor.type === 'localized') {\n const message = localizedMessage(descriptor, values, messages, labelFor);\n if (message !== undefined) errors[descriptor.name] = message;\n continue;\n }\n\n const raw = readDraftString(values, descriptor.name);\n\n if (descriptor.required && raw.trim() === '') {\n errors[descriptor.name] = messages.required(labelFor(descriptor));\n continue;\n }\n // Before the guard below: an empty list is a count of zero, and a link\n // collection's count is checkable though its ids are not.\n const counted = isCountedList(descriptor)\n ? itemCountMessage(descriptor, countItems(raw), messages, labelFor)\n : undefined;\n if (counted !== undefined) {\n errors[descriptor.name] = counted;\n continue;\n }\n if (raw === '' || !hasCheckableFormat(descriptor)) continue;\n\n const message =\n formatMessage(descriptor, raw, messages, labelFor) ??\n orderMessage(descriptor, raw, descriptors, values, messages, labelFor);\n if (message !== undefined) errors[descriptor.name] = message;\n }\n\n return errors;\n}\n\n/**\n * A localized member is all or nothing: left wholly empty it is absent, which\n * only `required` objects to; once any locale holds text, every declared one\n * must — the rule `validateRecords` holds stored content to, so a page never\n * shows one language in the middle of another.\n */\nfunction localizedMessage(\n descriptor: EntityFieldDescriptor,\n values: EntityDraft,\n messages: EntityDraftMessages,\n labelFor: EntityFieldLabeler,\n): string | undefined {\n const draft = readLocalizedDraft(values, descriptor.name);\n const missing = locales().filter(\n locale => (draft[locale] ?? '').trim() === '',\n );\n if (missing.length === locales().length) {\n return descriptor.required\n ? messages.required(labelFor(descriptor))\n : undefined;\n }\n const [first] = missing;\n return first === undefined\n ? undefined\n : messages.locale(labelFor(descriptor), first);\n}\n\n/** A collection whose draft is a comma list: values, or the ids of links. */\nfunction isCountedList(descriptor: EntityFieldDescriptor): boolean {\n return (\n descriptor.type === 'scalarCollection' ||\n descriptor.type === 'linkCollection'\n );\n}\n\n/** How many values a draft's comma list holds, blanks aside. */\nfunction countItems(raw: string): number {\n return raw.split(',').filter(item => item.trim() !== '').length;\n}\n\n/**\n * A collection's `minItems` / `maxItems`, judged on its count. The same rule\n * `validateRecords` applies to a stored record, so a draft the form accepts is\n * one a static build would too.\n */\nfunction itemCountMessage(\n descriptor: EntityFieldDescriptor,\n count: number,\n messages: EntityDraftMessages,\n labelFor: EntityFieldLabeler,\n): string | undefined {\n const { minItems, maxItems } = descriptor;\n if (minItems !== undefined && count < minItems) {\n return messages.minItems(labelFor(descriptor), minItems);\n }\n if (maxItems !== undefined && count > maxItems) {\n return messages.maxItems(labelFor(descriptor), maxItems);\n }\n return undefined;\n}\n\n/**\n * `notBefore`: a filled date that precedes the filled date it names. Either one\n * empty, or unparseable, is someone else's message.\n */\nfunction orderMessage(\n descriptor: EntityFieldDescriptor,\n raw: string,\n descriptors: readonly EntityFieldDescriptor[],\n values: EntityDraft,\n messages: EntityDraftMessages,\n labelFor: EntityFieldLabeler,\n): string | undefined {\n if (descriptor.notBefore === undefined) return undefined;\n const earlier = descriptors.find(\n other => other.name === descriptor.notBefore,\n );\n const start = new Date(readDraftString(values, descriptor.notBefore));\n if (earlier === undefined || Number.isNaN(start.getTime())) return undefined;\n return new Date(raw) < start\n ? messages.notBefore(labelFor(descriptor), labelFor(earlier))\n : undefined;\n}\n\n/**\n * The metadata rule for one filled scalar draft value, or `undefined` when it\n * passes.\n *\n * Extracted so a row's cell is judged by the **same** rule as a record's field.\n * Two copies is how a child's `number` member would quietly start accepting\n * something its master's would reject.\n */\nfunction formatMessage(\n descriptor: EntityFieldDescriptor,\n raw: string,\n messages: EntityDraftMessages,\n labelFor: EntityFieldLabeler,\n): string | undefined {\n if (descriptor.type === 'number' && Number.isNaN(Number(raw))) {\n return messages.number(labelFor(descriptor));\n }\n if (descriptor.type === 'date' && Number.isNaN(new Date(raw).getTime())) {\n return messages.date(labelFor(descriptor));\n }\n if (\n descriptor.type === 'enum' &&\n descriptor.enumValues &&\n !descriptor.enumValues.includes(raw)\n ) {\n return messages.option(labelFor(descriptor));\n }\n return undefined;\n}\n\n/**\n * The rules an owned collection carries, at both of its levels.\n *\n * **`required` on the collection means \"at least one row\"** — the only thing a\n * master can assert about a collection it owns, and a genuinely different fact\n * from `required` on a child member, which is per row. Conflating the two would\n * make an order with three lines, one of them blank, indistinguishable from an\n * order with none.\n *\n * A row's own members are judged against the child's descriptors and reported at\n * `items[2].quantity`, so the grid can put the message in the cell that caused\n * it. Read-only child members are skipped for the reason they always are: no\n * editor exists for them, so no rule the user could satisfy applies.\n */\nfunction validateComposition(\n descriptor: EntityFieldDescriptor,\n values: EntityDraft,\n messages: EntityDraftMessages,\n labelFor: EntityFieldLabeler,\n): Record<string, string> {\n const errors: Record<string, string> = {};\n const rows = readRowDrafts(values[descriptor.name]);\n\n if (descriptor.required && rows.length === 0) {\n errors[descriptor.name] = messages.required(labelFor(descriptor));\n return errors;\n }\n const counted = itemCountMessage(descriptor, rows.length, messages, labelFor);\n if (counted !== undefined) errors[descriptor.name] = counted;\n if (descriptor.childType === undefined) return errors;\n\n const columns = editableChildColumns(\n describeChildColumns(descriptor.childType),\n );\n\n rows.forEach((row, index) => {\n for (const column of columns) {\n if (isNeverEdited(column)) continue;\n\n const raw = row[column.name] ?? '';\n const path = rowFieldPath(descriptor.name, index, column.name);\n\n if (column.required && raw.trim() === '') {\n errors[path] = messages.required(labelFor(column));\n continue;\n }\n if (raw === '') continue;\n\n const message = formatMessage(column, raw, messages, labelFor);\n if (message !== undefined) errors[path] = message;\n }\n });\n\n return errors;\n}\n\n/**\n * The error-map key an issue belongs to — the **whole** path, not its head.\n *\n * It used to read `issue.path?.[0]`, which was right while every member was a\n * scalar and wrong the moment one held rows: `['items', 2, 'quantity']`\n * collapsed to `'items'`, so a rule about the third line's quantity reported\n * itself against the collection and the grid had no way to know which cell it\n * meant. Joining instead produces `items[2].quantity`, which is the key\n * `validateComposition` already writes — so a schema rule and a metadata rule\n * address the same cell the same way and `composeEntityFormErrors` can merge\n * them.\n *\n * A one-segment path still yields exactly the head, so no existing rule changes\n * meaning.\n */\nfunction issueFieldName(issue: StandardSchemaV1Issue): string | undefined {\n const path = issue.path;\n if (path == null || path.length === 0) return undefined;\n\n const segments = path.map(segment => {\n const raw =\n typeof segment === 'object' && segment !== null && 'key' in segment\n ? segment.key\n : segment;\n return typeof raw === 'number' ? raw : String(raw);\n });\n\n return joinFieldPath(segments);\n}\n\n/**\n * Runs a Standard Schema over the draft and sorts its issues into per-field\n * messages plus a form-level one (an issue with no path — a cross-field rule).\n *\n * **Schemas are authored against the string draft**, so they coerce\n * (`z.coerce.number()`) rather than expect typed values: the draft is what the\n * inputs round-trip, and the same schema then validates exactly what the user\n * sees. Only the first issue per field survives, matching how a row renders.\n *\n * Synchronous rules only. An async schema returns a Promise the form's\n * synchronous validation pass cannot wait on, so it is rejected loudly rather\n * than silently passing.\n */\nexport function readSchemaIssues(\n schema: StandardSchemaV1,\n values: EntityDraft,\n translateIssue: (message: string, field: string | undefined) => string,\n): { fields: Record<string, string>; form?: string } {\n const result = schema['~standard'].validate(values);\n\n if (result instanceof Promise) {\n throw new Error(\n 'useEntityForm cannot run an async schema: its validation pass is ' +\n 'synchronous. Move the asynchronous rule into the `validate` option.',\n );\n }\n if (!result.issues) return { fields: {} };\n\n const fields: Record<string, string> = {};\n let form: string | undefined;\n\n for (const issue of result.issues) {\n const name = issueFieldName(issue);\n const message = translateIssue(issue.message, name);\n\n if (name === undefined) form ??= message;\n else fields[name] ??= message;\n }\n\n return { fields, form };\n}\n\n/** Everything {@link composeEntityFormErrors} needs to judge one draft. */\nexport interface ComposeEntityFormErrorsOptions {\n descriptors: readonly EntityFieldDescriptor[];\n values: EntityDraft;\n messages: EntityDraftMessages;\n /** How a metadata message names its field. Defaults to the untranslated `label`. */\n labelFor?: EntityFieldLabeler;\n schema?: StandardSchemaV1;\n translateIssue: (message: string, field: string | undefined) => string;\n validate?: (values: EntityDraft) => Record<string, string>;\n}\n\n/**\n * The single composition point for a draft's errors: metadata rules first, then\n * the entity's schema, then the caller's `validate` callback. Later sources win\n * on conflict, so a caller can always override a message it disagrees with.\n */\nexport function composeEntityFormErrors({\n descriptors,\n values,\n messages,\n labelFor,\n schema,\n translateIssue,\n validate,\n}: ComposeEntityFormErrorsOptions): {\n fields: Record<string, string>;\n form?: string;\n} {\n const metadata = validateEntityDraft(descriptors, values, messages, labelFor);\n const schemaIssues = schema\n ? readSchemaIssues(schema, values, translateIssue)\n : { fields: {}, form: undefined };\n\n return {\n fields: { ...metadata, ...schemaIssues.fields, ...validate?.(values) },\n form: schemaIssues.form,\n };\n}\n\n/** Resolves a catalog key, with its parameters, in the reader's language. */\nexport type TranslateKey = (\n key: string,\n params?: Record<string, unknown>,\n) => string;\n\n/**\n * The form's validation sentences, from the `controls` catalog's\n * `validation.*` copy. Built from the caller's translator because this package\n * holds no catalog, and a key must never reach the screen (ADR 0028): the\n * controls package's `useTranslateKey` answers from its own catalog even with\n * no i18n library installed. `count` doubles as the plural selector, so\n * `minItems` reads \"1 item\" and \"2 items\".\n */\nexport function validationMessagesFrom(\n translateKey: TranslateKey,\n): EntityDraftMessages {\n const say =\n (failure: 'required' | 'number' | 'date' | 'option') => (field: string) =>\n translateKey(`controls:validation.${failure}`, { field });\n return {\n required: say('required'),\n number: say('number'),\n date: say('date'),\n option: say('option'),\n minItems: (field, count) =>\n translateKey('controls:validation.minItems', { field, count }),\n maxItems: (field, count) =>\n translateKey('controls:validation.maxItems', { field, count }),\n notBefore: (field, other) =>\n translateKey('controls:validation.notBefore', { field, other }),\n locale: (field, locale) =>\n translateKey('controls:validation.locale', {\n field,\n locale: locale.toUpperCase(),\n }),\n };\n}\n"],"names":["describeChildColumns","editableChildColumns","EntityCollectionLink","EntityLink","isLocalizedText","isRowDraftArray","joinFieldPath","locales","readDraftString","readLocalizedDraft","readRowDrafts","ROW_KEY","rowFieldPath","seededRowKey","isNeverEdited","descriptor","readonly","hasCheckableFormat","type","seedFieldValue","entity","seedRowDrafts","seedLocalizedDraft","seedScalarValue","raw","name","text","Object","fromEntries","map","locale","id","String","ids","join","Date","toISOString","slice","Array","isArray","childType","undefined","columns","row","index","draft","column","seedEntityDraft","descriptors","restoreEntityDraft","seed","persisted","restored","value","readFieldErrors","fieldMeta","errors","meta","entries","message","find","entry","labelOf","label","validateEntityDraft","values","messages","labelFor","formatMessage","assign","validateComposition","localizedMessage","required","trim","counted","isCountedList","itemCountMessage","countItems","orderMessage","missing","filter","length","first","split","item","count","minItems","maxItems","notBefore","earlier","other","start","Number","isNaN","getTime","number","date","enumValues","includes","option","rows","forEach","path","issueFieldName","issue","segments","segment","key","readSchemaIssues","schema","translateIssue","result","validate","Promise","Error","issues","fields","form","composeEntityFormErrors","metadata","schemaIssues","validationMessagesFrom","translateKey","say","failure","field","toUpperCase"],"mappings":";AAAA,SACEA,oBAAoB,EACpBC,oBAAoB,EACpBC,oBAAoB,EAIpBC,UAAU,EAGVC,eAAe,EACfC,eAAe,EACfC,aAAa,EACbC,OAAO,EACPC,eA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,aAAa,iCAAiC;gBAAEG;gBAAOnC;YAAM;QAC/D5D,QAAQ,CAAC+F,OAAO/F,SACd4F,aAAa,8BAA8B;gBACzCG;gBACA/F,QAAQA,OAAOgG,WAAW;YAC5B;IACJ;AACF"}
@@ -3,7 +3,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
3
3
  import { describeEntityColumns, seedEntityLinkSelection } from '@entifix/core';
4
4
  import { revalidateLogic, useForm, useStore } from '@tanstack/react-form';
5
5
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
6
- import { composeEntityFormErrors, DEFAULT_VALIDATION_MESSAGES, readFieldErrors, restoreEntityDraft, seedEntityDraft } from './use-entity-form.helpers.js';
6
+ import { composeEntityFormErrors, readFieldErrors, restoreEntityDraft, seedEntityDraft, validationMessagesFrom } from './use-entity-form.helpers.js';
7
7
  /**
8
8
  * The write half of an entity form: holds the string draft and reports
9
9
  * metadata-derived validation, the counterpart to {@link useEntityRecord}
@@ -30,7 +30,7 @@ import { composeEntityFormErrors, DEFAULT_VALIDATION_MESSAGES, readFieldErrors,
30
30
  * The seed applies once, so a caller that loads its record after mount keys the
31
31
  * form by the record id to reseed — the same convention `EntityForm`'s wrappers
32
32
  * already follow.
33
- */ export function useEntityForm({ entityConstructor, entity, draft, fields, schema, validate, validationMessages, translateKey, onSubmit }) {
33
+ */ export function useEntityForm({ entityConstructor, entity, draft, fields, schema, validate, translateKey, onSubmit }) {
34
34
  // Keyed on the **names**, not the array, so a caller may write the list inline
35
35
  // — which every wizard step does, since its field set is part of its own
36
36
  // declaration rather than something worth hoisting.
@@ -56,18 +56,12 @@ import { composeEntityFormErrors, DEFAULT_VALIDATION_MESSAGES, readFieldErrors,
56
56
  // label lookup and a save keeps whatever embedded shape it arrived in. Seeded
57
57
  // once, like the draft — a caller that loads late keys the form by record id.
58
58
  const [links, setLinks] = useState(()=>seedEntityLinkSelection(descriptors, entity));
59
- // Supplied by the caller, and that is the seam.
60
- //
61
- // ⚠️ This used to reach into react-i18next and `@entifix/i18n` directly,
62
- // because both React packages are T3 and the tier register declares no
63
- // sideways import of the controls package that owns the `controls`
64
- // catalog. The effect was that anyone taking the integration hooks also took
65
- // i18next and a Spanish catalog — the composition defect the tier register
66
- // was written to catch. The one real caller, `entity-crud-form.tsx`, sits a
67
- // tier up where `useT('controls')` is reachable, so it resolves the four
68
- // sentences and hands them over.
69
- const messages = useMemo(()=>validationMessages != null ? validationMessages : DEFAULT_VALIDATION_MESSAGES, [
70
- validationMessages
59
+ // Built from the caller's translator: this package holds no catalog, and a
60
+ // tier-3 hook reaching for i18next would make everyone who takes it take
61
+ // i18next too. The controls package's translator answers from its own
62
+ // catalog with no i18n library at all, so a key never reaches the screen.
63
+ const messages = useMemo(()=>validationMessagesFrom(translateKey), [
64
+ translateKey
71
65
  ]);
72
66
  // A schema's message is authored as a catalog key (`validation.minLength`),
73
67
  // because a rule written in one language would reach the user untranslated —
@@ -83,13 +77,12 @@ import { composeEntityFormErrors, DEFAULT_VALIDATION_MESSAGES, readFieldErrors,
83
77
  // than the accessor's untranslated `label` inside a Spanish sentence. The same
84
78
  // resolver reaches a composition's cells, which are described from the child
85
79
  // type inside the validator rather than from these descriptors.
86
- const labelFor = useCallback((descriptor)=>descriptor.labelKey !== undefined && translateKey !== undefined ? translateKey(descriptor.labelKey, {
80
+ const labelFor = useCallback((descriptor)=>descriptor.labelKey !== undefined ? translateKey(descriptor.labelKey, {
87
81
  defaultValue: descriptor.label
88
82
  }) : descriptor.label, [
89
83
  translateKey
90
84
  ]);
91
85
  const translateIssue = useCallback((message, field)=>{
92
- if (translateKey === undefined) return message;
93
86
  const descriptor = descriptors.find((entry)=>entry.name === field);
94
87
  return translateKey(message, {
95
88
  defaultValue: message,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/hooks/use-entity-form/use-entity-form.ts"],"sourcesContent":["'use client';\n\nimport {\n describeEntityColumns,\n type Entity,\n type EntityDraft,\n type EntityFieldDescriptor,\n type EntityLinkSelection,\n seedEntityLinkSelection,\n} from '@entifix/core';\nimport { revalidateLogic, useForm, useStore } from '@tanstack/react-form';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport {\n composeEntityFormErrors,\n DEFAULT_VALIDATION_MESSAGES,\n readFieldErrors,\n restoreEntityDraft,\n seedEntityDraft,\n} from './use-entity-form.helpers.js';\nimport type {\n UseEntityFormOptions,\n UseEntityFormResult,\n} from './use-entity-form.types.js';\n\n/**\n * The write half of an entity form: holds the string draft and reports\n * metadata-derived validation, the counterpart to {@link useEntityRecord}\n * (which reads the record it seeds from).\n *\n * It stays out of the transport: it neither fetches nor saves. `onSubmit`\n * receives the validated draft, and the per-entity wrapper reconstructs the\n * domain entity and calls the mutation. The result plugs straight into the\n * agnostic `EntityForm` (`values`/`onFieldChange`/`errors`/`onSubmit`).\n *\n * TanStack Form owns the draft and the submission lifecycle; that is an\n * implementation detail, and the returned shape is deliberately the plain\n * `values`/`errors`/`setField`/`submit`/`isDirty` facade so `EntityForm` — which\n * renders native inputs and knows nothing about any form library — stays\n * agnostic. Fields are therefore never registered through `form.Field`; a\n * form-level validator reporting `{ fields }` reaches them anyway, because\n * `FormApi` creates meta for any field name an error arrives for.\n *\n * `revalidateLogic` is what makes a pristine form quiet: nothing validates until\n * the first submit, and every keystroke revalidates after it. Running one\n * validator under a single cause also keeps a fixed field from holding a stale\n * message left behind by another cause.\n *\n * The seed applies once, so a caller that loads its record after mount keys the\n * form by the record id to reseed — the same convention `EntityForm`'s wrappers\n * already follow.\n */\nexport function useEntityForm<TEntity extends Entity>({\n entityConstructor,\n entity,\n draft,\n fields,\n schema,\n validate,\n validationMessages,\n translateKey,\n onSubmit,\n}: UseEntityFormOptions<TEntity>): UseEntityFormResult {\n // Keyed on the **names**, not the array, so a caller may write the list inline\n // — which every wizard step does, since its field set is part of its own\n // declaration rather than something worth hoisting.\n const scope = fields?.join(',');\n const descriptors = useMemo(() => {\n const described = describeEntityColumns(entityConstructor, entity);\n return scope === undefined\n ? described\n : described.filter(descriptor =>\n scope.split(',').includes(descriptor.name),\n );\n }, [entityConstructor, entity, scope]);\n // A persisted draft is layered over the seed, never substituted for it: the\n // entity decides which members exist, the draft only decides their values.\n // See `restoreEntityDraft` for what a straight substitution costs.\n const restored = draft?.draft;\n const seed = useMemo(\n () =>\n restoreEntityDraft(\n descriptors,\n seedEntityDraft(descriptors, entity),\n restored,\n ),\n [descriptors, entity, restored],\n );\n\n // The relations the record already carries, so opening a loaded record needs no\n // label lookup and a save keeps whatever embedded shape it arrived in. Seeded\n // once, like the draft — a caller that loads late keys the form by record id.\n const [links, setLinks] = useState<EntityLinkSelection>(() =>\n seedEntityLinkSelection(descriptors, entity),\n );\n\n // Supplied by the caller, and that is the seam.\n //\n // ⚠️ This used to reach into react-i18next and `@entifix/i18n` directly,\n // because both React packages are T3 and the tier register declares no\n // sideways import of the controls package that owns the `controls`\n // catalog. The effect was that anyone taking the integration hooks also took\n // i18next and a Spanish catalog — the composition defect the tier register\n // was written to catch. The one real caller, `entity-crud-form.tsx`, sits a\n // tier up where `useT('controls')` is reachable, so it resolves the four\n // sentences and hands them over.\n const messages = useMemo(\n () => validationMessages ?? DEFAULT_VALIDATION_MESSAGES,\n [validationMessages],\n );\n\n // A schema's message is authored as a catalog key (`validation.minLength`),\n // because a rule written in one language would reach the user untranslated —\n // the one thing the i18n gate exists to prevent. `defaultValue` keeps an\n // unkeyed literal readable instead of rendering the key back at the user, and\n // `field` is offered as a parameter so a message can name its own label.\n // Supplied by the caller for the same reason the four sentences above are —\n // and this one is `useTranslateKey`'s job rather than `useT`'s, because a\n // schema's message is a key only known at runtime. With nothing supplied the\n // message renders as authored, which is what `defaultValue` always did.\n // How a message names its field: the catalog's word when the member has a\n // `labelKey` and a translator was supplied, so \"Cantidad es obligatorio\" rather\n // than the accessor's untranslated `label` inside a Spanish sentence. The same\n // resolver reaches a composition's cells, which are described from the child\n // type inside the validator rather than from these descriptors.\n const labelFor = useCallback(\n (descriptor: EntityFieldDescriptor) =>\n descriptor.labelKey !== undefined && translateKey !== undefined\n ? translateKey(descriptor.labelKey, { defaultValue: descriptor.label })\n : descriptor.label,\n [translateKey],\n );\n\n const translateIssue = useCallback(\n (message: string, field: string | undefined) => {\n if (translateKey === undefined) return message;\n const descriptor = descriptors.find(entry => entry.name === field);\n return translateKey(message, {\n defaultValue: message,\n field: descriptor === undefined ? field : labelFor(descriptor),\n });\n },\n [translateKey, descriptors, labelFor],\n );\n\n /**\n * Whether the last {@link submit} reached the caller's `onSubmit`.\n *\n * A ref rather than state: nothing renders from it, and making it state would\n * re-render the whole form on every submit attempt for a value only the\n * caller awaiting `submit()` ever reads.\n */\n const submitted = useRef(false);\n\n const form = useForm({\n defaultValues: seed,\n // Quiet until the first submit, then revalidate on every change — the\n // behaviour the hand-rolled `submitted` flag used to produce.\n validationLogic: revalidateLogic(),\n validators: {\n onDynamic: ({ value }: { value: EntityDraft }) => {\n const { fields, form } = composeEntityFormErrors({\n descriptors,\n values: value,\n messages,\n labelFor,\n schema,\n translateIssue,\n validate,\n });\n\n if (Object.keys(fields).length === 0 && form === undefined)\n return undefined;\n // `{ fields }` is how a form-level validator addresses individual\n // fields; the bare `form` message is what has no field to sit under.\n return { form, fields };\n },\n },\n onSubmit: ({ value }) => {\n // The engine calls this only when validation passed, so recording that it\n // ran *is* the answer {@link UseEntityFormResult.submit} returns. Reading\n // `form.state.isValid` afterwards would ask the engine a second question\n // whose answer depends on when it settled.\n submitted.current = true;\n return onSubmit(value);\n },\n });\n\n const values = useStore(form.store, state => state.values);\n const fieldMeta = useStore(form.store, state => state.fieldMeta);\n const formError = useStore(form.store, state => state.errorMap.onDynamic);\n // `isDefaultValue`, not `isDirty`: the draft is dirty when it *differs* from\n // its seed, so editing a field and typing the seed value back is not a change\n // the workspace should autosave.\n const isDefaultValue = useStore(form.store, state => state.isDefaultValue);\n\n const errors = useMemo(() => readFieldErrors(fieldMeta), [fieldMeta]);\n\n /**\n * Validate, then submit when clean — and **say whether it went**.\n *\n * The promise is what lets a caller gate on the result. A wizard's \"Siguiente\"\n * is the step's own submit, and before this it had nothing to wait for:\n * `handleSubmit()`'s promise was discarded, so the only way to learn the\n * outcome was to await a tick and re-read `errors`, which is the trap this\n * hook's own specs worked around.\n */\n const submit = useCallback(async () => {\n submitted.current = false;\n await form.handleSubmit();\n return submitted.current;\n }, [form]);\n\n // Both halves of a pick, in one call: the id the draft persists and the\n // instance only memory holds.\n const setLink = useCallback(\n (name: string, picked: Entity | undefined) => {\n setLinks(current => ({ ...current, [name]: picked }));\n form.setFieldValue(name, picked?.id == null ? '' : String(picked.id));\n },\n [form],\n );\n\n // The sidecar half alone. A restored draft holds the id and lost the instance,\n // and something resolved it back — that is not a user pick, so it must not\n // touch the draft: writing the field would be an edit the user did not make,\n // and on a form whose seed *is* the restored draft it would also be a no-op\n // that only risks disagreeing with the engine about equality.\n const hydrateLink = useCallback((name: string, resolved: Entity) => {\n setLinks(current =>\n current[name] === undefined ? { ...current, [name]: resolved } : current,\n );\n }, []);\n\n // Autosave. The seam lives here rather than in each page, so a form gets\n // persistence by naming a store and no call site threads a draft through.\n //\n // Two properties keep it from writing more than it means to. It writes only\n // while the draft *differs* from its seed — and on mount over a restored\n // draft the seed **is** that draft, so opening a tab re-persists nothing. And\n // it is keyed on `save`, which the port requires to be referentially stable;\n // a new identity per render would make every render a write.\n //\n // Nothing here clears: a draft is spent when the write commits, and this hook\n // never learns whether it did. See `EntityDraftStore.clear`.\n const save = draft?.save;\n useEffect(() => {\n if (!isDefaultValue) save?.(values);\n }, [values, isDefaultValue, save]);\n\n return {\n values,\n errors,\n formError: typeof formError === 'string' ? formError : undefined,\n setField: form.setFieldValue,\n links,\n setLink,\n hydrateLink,\n submit,\n isDirty: !isDefaultValue,\n };\n}\n"],"names":["describeEntityColumns","seedEntityLinkSelection","revalidateLogic","useForm","useStore","useCallback","useEffect","useMemo","useRef","useState","composeEntityFormErrors","DEFAULT_VALIDATION_MESSAGES","readFieldErrors","restoreEntityDraft","seedEntityDraft","useEntityForm","entityConstructor","entity","draft","fields","schema","validate","validationMessages","translateKey","onSubmit","scope","join","descriptors","described","undefined","filter","descriptor","split","includes","name","restored","seed","links","setLinks","messages","labelFor","labelKey","defaultValue","label","translateIssue","message","field","find","entry","submitted","form","defaultValues","validationLogic","validators","onDynamic","value","values","Object","keys","length","current","store","state","fieldMeta","formError","errorMap","isDefaultValue","errors","submit","handleSubmit","setLink","picked","setFieldValue","id","String","hydrateLink","resolved","save","setField","isDirty"],"mappings":"AAAA;;AAEA,SACEA,qBAAqB,EAKrBC,uBAAuB,QAClB,gBAAgB;AACvB,SAASC,eAAe,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,uBAAuB;AAC1E,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAQ;AAE1E,SACEC,uBAAuB,EACvBC,2BAA2B,EAC3BC,eAAe,EACfC,kBAAkB,EAClBC,eAAe,QACV,+BAA+B;AAMtC;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,OAAO,SAASC,cAAsC,EACpDC,iBAAiB,EACjBC,MAAM,EACNC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,kBAAkB,EAClBC,YAAY,EACZC,QAAQ,EACsB;IAC9B,+EAA+E;IAC/E,yEAAyE;IACzE,oDAAoD;IACpD,MAAMC,QAAQN,0BAAAA,OAAQO,IAAI,CAAC;IAC3B,MAAMC,cAAcpB,QAAQ;QAC1B,MAAMqB,YAAY5B,sBAAsBgB,mBAAmBC;QAC3D,OAAOQ,UAAUI,YACbD,YACAA,UAAUE,MAAM,CAACC,CAAAA,aACfN,MAAMO,KAAK,CAAC,KAAKC,QAAQ,CAACF,WAAWG,IAAI;IAEjD,GAAG;QAAClB;QAAmBC;QAAQQ;KAAM;IACrC,4EAA4E;IAC5E,2EAA2E;IAC3E,mEAAmE;IACnE,MAAMU,WAAWjB,yBAAAA,MAAOA,KAAK;IAC7B,MAAMkB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ASsB,CAAAA,UAAY,aAAKA;gBAAS,CAAC1B,KAAK,EAAEqC;;QAC3CrB,KAAKsB,aAAa,CAACtC,MAAMqC,CAAAA,0BAAAA,OAAQE,EAAE,KAAI,OAAO,KAAKC,OAAOH,OAAOE,EAAE;IACrE,GACA;QAACvB;KAAK;IAGR,+EAA+E;IAC/E,2EAA2E;IAC3E,6EAA6E;IAC7E,4EAA4E;IAC5E,8DAA8D;IAC9D,MAAMyB,cAActE,YAAY,CAAC6B,MAAc0C;QAC7CtC,SAASsB,CAAAA,UACPA,OAAO,CAAC1B,KAAK,KAAKL,YAAY,aAAK+B;gBAAS,CAAC1B,KAAK,EAAE0C;iBAAahB;IAErE,GAAG,EAAE;IAEL,yEAAyE;IACzE,0EAA0E;IAC1E,EAAE;IACF,4EAA4E;IAC5E,yEAAyE;IACzE,8EAA8E;IAC9E,6EAA6E;IAC7E,6DAA6D;IAC7D,EAAE;IACF,8EAA8E;IAC9E,6DAA6D;IAC7D,MAAMiB,OAAO3D,yBAAAA,MAAO2D,IAAI;IACxBvE,UAAU;QACR,IAAI,CAAC4D,gBAAgBW,wBAAAA,KAAOrB;IAC9B,GAAG;QAACA;QAAQU;QAAgBW;KAAK;IAEjC,OAAO;QACLrB;QACAW;QACAH,WAAW,OAAOA,cAAc,WAAWA,YAAYnC;QACvDiD,UAAU5B,KAAKsB,aAAa;QAC5BnC;QACAiC;QACAK;QACAP;QACAW,SAAS,CAACb;IACZ;AACF"}
1
+ {"version":3,"sources":["../../../src/hooks/use-entity-form/use-entity-form.ts"],"sourcesContent":["'use client';\n\nimport {\n describeEntityColumns,\n type Entity,\n type EntityDraft,\n type EntityFieldDescriptor,\n type EntityLinkSelection,\n seedEntityLinkSelection,\n} from '@entifix/core';\nimport { revalidateLogic, useForm, useStore } from '@tanstack/react-form';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport {\n composeEntityFormErrors,\n readFieldErrors,\n restoreEntityDraft,\n seedEntityDraft,\n validationMessagesFrom,\n} from './use-entity-form.helpers.js';\nimport type {\n UseEntityFormOptions,\n UseEntityFormResult,\n} from './use-entity-form.types.js';\n\n/**\n * The write half of an entity form: holds the string draft and reports\n * metadata-derived validation, the counterpart to {@link useEntityRecord}\n * (which reads the record it seeds from).\n *\n * It stays out of the transport: it neither fetches nor saves. `onSubmit`\n * receives the validated draft, and the per-entity wrapper reconstructs the\n * domain entity and calls the mutation. The result plugs straight into the\n * agnostic `EntityForm` (`values`/`onFieldChange`/`errors`/`onSubmit`).\n *\n * TanStack Form owns the draft and the submission lifecycle; that is an\n * implementation detail, and the returned shape is deliberately the plain\n * `values`/`errors`/`setField`/`submit`/`isDirty` facade so `EntityForm` — which\n * renders native inputs and knows nothing about any form library — stays\n * agnostic. Fields are therefore never registered through `form.Field`; a\n * form-level validator reporting `{ fields }` reaches them anyway, because\n * `FormApi` creates meta for any field name an error arrives for.\n *\n * `revalidateLogic` is what makes a pristine form quiet: nothing validates until\n * the first submit, and every keystroke revalidates after it. Running one\n * validator under a single cause also keeps a fixed field from holding a stale\n * message left behind by another cause.\n *\n * The seed applies once, so a caller that loads its record after mount keys the\n * form by the record id to reseed — the same convention `EntityForm`'s wrappers\n * already follow.\n */\nexport function useEntityForm<TEntity extends Entity>({\n entityConstructor,\n entity,\n draft,\n fields,\n schema,\n validate,\n translateKey,\n onSubmit,\n}: UseEntityFormOptions<TEntity>): UseEntityFormResult {\n // Keyed on the **names**, not the array, so a caller may write the list inline\n // — which every wizard step does, since its field set is part of its own\n // declaration rather than something worth hoisting.\n const scope = fields?.join(',');\n const descriptors = useMemo(() => {\n const described = describeEntityColumns(entityConstructor, entity);\n return scope === undefined\n ? described\n : described.filter(descriptor =>\n scope.split(',').includes(descriptor.name),\n );\n }, [entityConstructor, entity, scope]);\n // A persisted draft is layered over the seed, never substituted for it: the\n // entity decides which members exist, the draft only decides their values.\n // See `restoreEntityDraft` for what a straight substitution costs.\n const restored = draft?.draft;\n const seed = useMemo(\n () =>\n restoreEntityDraft(\n descriptors,\n seedEntityDraft(descriptors, entity),\n restored,\n ),\n [descriptors, entity, restored],\n );\n\n // The relations the record already carries, so opening a loaded record needs no\n // label lookup and a save keeps whatever embedded shape it arrived in. Seeded\n // once, like the draft — a caller that loads late keys the form by record id.\n const [links, setLinks] = useState<EntityLinkSelection>(() =>\n seedEntityLinkSelection(descriptors, entity),\n );\n\n // Built from the caller's translator: this package holds no catalog, and a\n // tier-3 hook reaching for i18next would make everyone who takes it take\n // i18next too. The controls package's translator answers from its own\n // catalog with no i18n library at all, so a key never reaches the screen.\n const messages = useMemo(\n () => validationMessagesFrom(translateKey),\n [translateKey],\n );\n\n // A schema's message is authored as a catalog key (`validation.minLength`),\n // because a rule written in one language would reach the user untranslated —\n // the one thing the i18n gate exists to prevent. `defaultValue` keeps an\n // unkeyed literal readable instead of rendering the key back at the user, and\n // `field` is offered as a parameter so a message can name its own label.\n // Supplied by the caller for the same reason the four sentences above are —\n // and this one is `useTranslateKey`'s job rather than `useT`'s, because a\n // schema's message is a key only known at runtime. With nothing supplied the\n // message renders as authored, which is what `defaultValue` always did.\n // How a message names its field: the catalog's word when the member has a\n // `labelKey` and a translator was supplied, so \"Cantidad es obligatorio\" rather\n // than the accessor's untranslated `label` inside a Spanish sentence. The same\n // resolver reaches a composition's cells, which are described from the child\n // type inside the validator rather than from these descriptors.\n const labelFor = useCallback(\n (descriptor: EntityFieldDescriptor) =>\n descriptor.labelKey !== undefined\n ? translateKey(descriptor.labelKey, { defaultValue: descriptor.label })\n : descriptor.label,\n [translateKey],\n );\n\n const translateIssue = useCallback(\n (message: string, field: string | undefined) => {\n const descriptor = descriptors.find(entry => entry.name === field);\n return translateKey(message, {\n defaultValue: message,\n field: descriptor === undefined ? field : labelFor(descriptor),\n });\n },\n [translateKey, descriptors, labelFor],\n );\n\n /**\n * Whether the last {@link submit} reached the caller's `onSubmit`.\n *\n * A ref rather than state: nothing renders from it, and making it state would\n * re-render the whole form on every submit attempt for a value only the\n * caller awaiting `submit()` ever reads.\n */\n const submitted = useRef(false);\n\n const form = useForm({\n defaultValues: seed,\n // Quiet until the first submit, then revalidate on every change — the\n // behaviour the hand-rolled `submitted` flag used to produce.\n validationLogic: revalidateLogic(),\n validators: {\n onDynamic: ({ value }: { value: EntityDraft }) => {\n const { fields, form } = composeEntityFormErrors({\n descriptors,\n values: value,\n messages,\n labelFor,\n schema,\n translateIssue,\n validate,\n });\n\n if (Object.keys(fields).length === 0 && form === undefined)\n return undefined;\n // `{ fields }` is how a form-level validator addresses individual\n // fields; the bare `form` message is what has no field to sit under.\n return { form, fields };\n },\n },\n onSubmit: ({ value }) => {\n // The engine calls this only when validation passed, so recording that it\n // ran *is* the answer {@link UseEntityFormResult.submit} returns. Reading\n // `form.state.isValid` afterwards would ask the engine a second question\n // whose answer depends on when it settled.\n submitted.current = true;\n return onSubmit(value);\n },\n });\n\n const values = useStore(form.store, state => state.values);\n const fieldMeta = useStore(form.store, state => state.fieldMeta);\n const formError = useStore(form.store, state => state.errorMap.onDynamic);\n // `isDefaultValue`, not `isDirty`: the draft is dirty when it *differs* from\n // its seed, so editing a field and typing the seed value back is not a change\n // the workspace should autosave.\n const isDefaultValue = useStore(form.store, state => state.isDefaultValue);\n\n const errors = useMemo(() => readFieldErrors(fieldMeta), [fieldMeta]);\n\n /**\n * Validate, then submit when clean — and **say whether it went**.\n *\n * The promise is what lets a caller gate on the result. A wizard's \"Siguiente\"\n * is the step's own submit, and before this it had nothing to wait for:\n * `handleSubmit()`'s promise was discarded, so the only way to learn the\n * outcome was to await a tick and re-read `errors`, which is the trap this\n * hook's own specs worked around.\n */\n const submit = useCallback(async () => {\n submitted.current = false;\n await form.handleSubmit();\n return submitted.current;\n }, [form]);\n\n // Both halves of a pick, in one call: the id the draft persists and the\n // instance only memory holds.\n const setLink = useCallback(\n (name: string, picked: Entity | undefined) => {\n setLinks(current => ({ ...current, [name]: picked }));\n form.setFieldValue(name, picked?.id == null ? '' : String(picked.id));\n },\n [form],\n );\n\n // The sidecar half alone. A restored draft holds the id and lost the instance,\n // and something resolved it back — that is not a user pick, so it must not\n // touch the draft: writing the field would be an edit the user did not make,\n // and on a form whose seed *is* the restored draft it would also be a no-op\n // that only risks disagreeing with the engine about equality.\n const hydrateLink = useCallback((name: string, resolved: Entity) => {\n setLinks(current =>\n current[name] === undefined ? { ...current, [name]: resolved } : current,\n );\n }, []);\n\n // Autosave. The seam lives here rather than in each page, so a form gets\n // persistence by naming a store and no call site threads a draft through.\n //\n // Two properties keep it from writing more than it means to. It writes only\n // while the draft *differs* from its seed — and on mount over a restored\n // draft the seed **is** that draft, so opening a tab re-persists nothing. And\n // it is keyed on `save`, which the port requires to be referentially stable;\n // a new identity per render would make every render a write.\n //\n // Nothing here clears: a draft is spent when the write commits, and this hook\n // never learns whether it did. See `EntityDraftStore.clear`.\n const save = draft?.save;\n useEffect(() => {\n if (!isDefaultValue) save?.(values);\n }, [values, isDefaultValue, save]);\n\n return {\n values,\n errors,\n formError: typeof formError === 'string' ? formError : undefined,\n setField: form.setFieldValue,\n links,\n setLink,\n hydrateLink,\n submit,\n isDirty: !isDefaultValue,\n };\n}\n"],"names":["describeEntityColumns","seedEntityLinkSelection","revalidateLogic","useForm","useStore","useCallback","useEffect","useMemo","useRef","useState","composeEntityFormErrors","readFieldErrors","restoreEntityDraft","seedEntityDraft","validationMessagesFrom","useEntityForm","entityConstructor","entity","draft","fields","schema","validate","translateKey","onSubmit","scope","join","descriptors","described","undefined","filter","descriptor","split","includes","name","restored","seed","links","setLinks","messages","labelFor","labelKey","defaultValue","label","translateIssue","message","field","find","entry","submitted","form","defaultValues","validationLogic","validators","onDynamic","value","values","Object","keys","length","current","store","state","fieldMeta","formError","errorMap","isDefaultValue","errors","submit","handleSubmit","setLink","picked","setFieldValue","id","String","hydrateLink","resolved","save","setField","isDirty"],"mappings":"AAAA;;AAEA,SACEA,qBAAqB,EAKrBC,uBAAuB,QAClB,gBAAgB;AACvB,SAASC,eAAe,EAAEC,OAAO,EAAEC,QAAQ,QAAQ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