@entifix/next-shell 0.6.0 → 0.7.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.
@@ -1 +1 @@
1
- {"version":3,"file":"make-entity-crud.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/make-entity-crud.tsx"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,mBAAmB,EAIzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAKL,KAAK,MAAM,EACX,KAAK,iBAAiB,EAIvB,MAAM,eAAe,CAAC;AAQvB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAajC,OAAO,KAAK,EACV,UAAU,EAEV,iBAAiB,EAElB,MAAM,6BAA6B,CAAC;AAUrC;;;;;;;GAOG;AACH,MAAM,MAAM,WAAW,GAAG,mBAAmB,GAAG,kBAAkB,CAAC;AAEnE;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EACxC,QAAQ,EAAE,SAAS,EACnB,UAAU,EAAE,MAAM,SAAS,EAC3B,IAAI,EAAE,eAAe,GACpB,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,CAM9B;AAuCD,wBAAgB,cAAc,CAAC,OAAO,SAAS,MAAM,EAAE,SAAS,EAC9D,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,EAC7C,OAAO,EAAE,iBAAiB,CAAC,SAAS,EAAE,OAAO,CAAC,GAC7C,UAAU,CAAC,OAAO,CAAC,CA4WrB"}
1
+ {"version":3,"file":"make-entity-crud.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/make-entity-crud.tsx"],"names":[],"mappings":"AAEA,OAAO,EAEL,KAAK,mBAAmB,EAIzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAKL,KAAK,MAAM,EACX,KAAK,iBAAiB,EAKvB,MAAM,eAAe,CAAC;AAQvB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAajC,OAAO,KAAK,EAEV,UAAU,EAEV,iBAAiB,EAElB,MAAM,6BAA6B,CAAC;AAUrC;;;;;;;GAOG;AACH,MAAM,MAAM,WAAW,GAAG,mBAAmB,GAAG,kBAAkB,CAAC;AAEnE;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EACxC,QAAQ,EAAE,SAAS,EACnB,UAAU,EAAE,MAAM,SAAS,EAC3B,IAAI,EAAE,eAAe,GACpB,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,CAM9B;AA2DD,wBAAgB,cAAc,CAAC,OAAO,SAAS,MAAM,EAAE,SAAS,EAC9D,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,EAC7C,OAAO,EAAE,iBAAiB,CAAC,SAAS,EAAE,OAAO,CAAC,GAC7C,UAAU,CAAC,OAAO,CAAC,CAuXrB"}
@@ -60,8 +60,19 @@ import { useEntityBulk } from './use-entity-bulk.js';
60
60
  */ function asEntifixError(failure) {
61
61
  return failure instanceof EntifixLogicError || failure instanceof EntifixBuildError ? failure : new EntifixLogicError(failure instanceof Error ? failure.message : String(failure));
62
62
  }
63
+ /**
64
+ * Runs each link's `useBaseFiltering` against the record being edited, in link
65
+ * order, with `undefined` for a link that declares none.
66
+ *
67
+ * Legal for the reason `useEntityLinkSources` gives: the links are a
68
+ * factory-time array, and whether a link carries a rule is fixed with it, so
69
+ * the same hooks run in the same order on every render. The lint rule cannot
70
+ * see a hook called through a member, so there is nothing for it to flag.
71
+ */ function useLinkFilters(links, record) {
72
+ return links.map((link)=>link.useBaseFiltering == null ? void 0 : link.useBaseFiltering.call(link, record));
73
+ }
63
74
  export function makeEntityCrud(entityConstructor, options) {
64
- const { useAdapters, basePath, catalogKey, repository, hiddenFields = [], columns, toolbar, links = [], metadataSource: givenMetadataSource, metadata, runBulkUseCase, runUseCase } = options;
75
+ const { useAdapters, basePath, catalogKey, repository, hiddenFields = [], columns, toolbar, pageSize, links = [], metadataSource: givenMetadataSource, metadata, runBulkUseCase, runUseCase } = options;
65
76
  if (givenMetadataSource !== undefined && metadata !== undefined) {
66
77
  throw new EntifixBuildError(`${entityConstructor.name} was given both metadataSource and metadata; pass one`);
67
78
  }
@@ -122,7 +133,7 @@ export function makeEntityCrud(entityConstructor, options) {
122
133
  // writing. Prepended below rather than patched into the cache, which a
123
134
  // refetch would undo.
124
135
  const optimistic = pendingRecordsFor(pending, entityName);
125
- const pager = useDataLoading({
136
+ const pager = useDataLoading(_extends({
126
137
  uc: loadUCFactory(),
127
138
  ctx: mergeCrudContext(adapters, repository, pending),
128
139
  // Scoped rather than left to the per-instance fallback, which is correct
@@ -131,7 +142,9 @@ export function makeEntityCrud(entityConstructor, options) {
131
142
  // the same prefix `useReactiveInvalidation`already targets, so a generated
132
143
  // list now also refreshes on a reactive change event.
133
144
  queryKey: scope
134
- });
145
+ }, pageSize === undefined ? {} : {
146
+ initialPageSize: pageSize
147
+ }));
135
148
  // Only when this caller may actually run something over a selection.
136
149
  //
137
150
  // Measured live: an `admin` holds `catalog-reference:*:read` and no
@@ -235,17 +248,23 @@ export function makeEntityCrud(entityConstructor, options) {
235
248
  deleteUc: deleteUCFactory(),
236
249
  ctx
237
250
  });
251
+ // Against the record as loaded, not the draft: the rule is about which
252
+ // record this is, not what the operator has typed into it.
253
+ const linkFilters = useLinkFilters(linkPlans, entity);
238
254
  // Rebuilt inline on every render on purpose: `useEntityLinkSource` holds
239
255
  // these in a ref and keeps them out of its query keys, precisely so a caller
240
256
  // does not have to memoise them.
241
- const linkSources = linkPlans.map((plan)=>({
257
+ const linkSources = linkPlans.map((plan, index)=>({
242
258
  field: plan.field,
243
259
  descriptor: plan.descriptor,
244
260
  config: {
245
261
  entityConstructor: plan.entityConstructor,
246
262
  loadUc: loadUCFactory(),
247
263
  getUc: getUCFactory(),
248
- ctx: mergeCrudContext(adapters, plan.repository, pending)
264
+ ctx: mergeCrudContext(adapters, plan.repository, pending),
265
+ // The config's target is erased to `Entity`, and the host's filter to
266
+ // `any`; the two meet here, where neither type is the real target's.
267
+ baseFiltering: linkFilters[index]
249
268
  }
250
269
  }));
251
270
  // Inside a workspace tab, "back to the list" is the list's tab, not a URL
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/crud/make-entity-crud.tsx"],"sourcesContent":["'use client';\n\nimport {\n deleteUCFactory,\n type EntityRepositoryTag,\n getUCFactory,\n loadUCFactory,\n saveUCFactory,\n} from '@entifix/business';\nimport {\n describeEntityColumns,\n EntifixBuildError,\n type EntifixError,\n EntifixLogicError,\n type Entity,\n type EntityConstructor,\n type EntityMetadataSource,\n envelopeEntityName,\n extractMetaEntity,\n} from '@entifix/core';\nimport { EntityTable, useCasesForSurface } from '@entifix/react-controls';\nimport {\n entityQueryScope,\n useDataLoading,\n useEntityMutation,\n useEntityRecord,\n} from '@entifix/react-integration';\nimport type { TransactionSink } from '@entifix/transactions';\nimport { TransactionSinkTag } from '@entifix/transactions';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { Context } from 'effect';\nimport { useParams, useRouter } from 'next/navigation';\nimport { useState } from 'react';\n\nimport { useLocaleHref } from '../i18n/index.js';\nimport { useEntityNavHost } from '../workspace/entity-nav.js';\nimport {\n pendingFor,\n pendingRecordsFor,\n usePendingTransactions,\n} from '../workspace/pending-transactions.js';\nimport { EntityCrudForm } from './entity-crud-form.js';\nimport { handOffWrite } from './hand-off-write.js';\nimport type {\n EntityCrud,\n EntityCrudLinkSource,\n EntityCrudOptions,\n EntityCrudSingleViewProps,\n} from './make-entity-crud.types.js';\nimport { PendingNotice } from './pending-notice.js';\nimport { CATALOG_NEW_SLUG, slugToEntityId } from './slug.js';\nimport { useCrudRenderLink } from './use-crud-render-link.js';\nimport { useEntityAffordances } from './use-entity-affordances.js';\nimport { useEntityBulk } from './use-entity-bulk.js';\n\n/** What a picker defaults to reading off its target. */\nconst TARGET_NAME_PROPERTY = 'name';\n\n/**\n * What the generated pages' use-cases run against.\n *\n * Exported because a hand-built screen needs the same three: a wizard reads\n * records, resolves pickers and writes through exactly these ports, and\n * rebuilding the union at each such call site is how one of them ends up\n * missing `TransactionSinkTag` and quietly losing its optimistic treatment.\n */\nexport type CrudContext = EntityRepositoryTag | TransactionSinkTag;\n\n/**\n * Adds the pending-write sink to one repository adapter, giving the context the\n * use-cases run against.\n *\n * The cast is the price of naming adapters by key: `AdapterKey` narrows which\n * names may be *offered*, but TypeScript will not carry that narrowing through\n * an index access on a generic record.\n */\nexport function mergeCrudContext<TAdapters>(\n adapters: TAdapters,\n repository: keyof TAdapters,\n sink: TransactionSink,\n): Context.Context<CrudContext> {\n return Context.add(\n adapters[repository] as Context.Context<EntityRepositoryTag>,\n TransactionSinkTag,\n sink,\n );\n}\n\n/**\n * Builds the list page and the single-record page for one entity.\n *\n * Every catalog entity used to cost ~10 files and ~300 lines whose only variable\n * was a class name: two organisms with a `.types.ts` each, two client pages, two\n * route files. The route files stay (Next needs a module per path); everything\n * between them is derived from the entity's own metadata, so a new reference\n * entity is this call plus a nav entry.\n *\n * Two things are checked here rather than at the call site, because both fail\n * silently otherwise. The catalog key must be the entity's own `@entity({ key })`\n * — they are the same string by convention, and a drifted one titles the form\n * after a different entity in a way only a reader of both catalogs would catch.\n * And a `links` entry must name a real member — a picker aimed at nothing renders\n * identically to a read-only field.\n *\n * **Serves compile-time `@entity()` classes only.** Operator reference data ships\n * with the code, so making this spec-driven would trade type safety for nothing;\n * a vendor-authored `EntitySpecification` renders through a separate path.\n */\n/**\n * A rejected verb, as something the form's error slot can render.\n *\n * `useErrorMessage` resolves `details.code` through the shared `errors`\n * catalog, so a shell that throws an `EntifixError` carrying one gets its\n * translated sentence; anything else — a network failure, a thrown string —\n * keeps its message rather than being relabelled with a code it never had.\n */\nfunction asEntifixError(failure: unknown): EntifixError {\n return failure instanceof EntifixLogicError ||\n failure instanceof EntifixBuildError\n ? failure\n : new EntifixLogicError(\n failure instanceof Error ? failure.message : String(failure),\n );\n}\n\nexport function makeEntityCrud<TEntity extends Entity, TAdapters>(\n entityConstructor: EntityConstructor<TEntity>,\n options: EntityCrudOptions<TAdapters, TEntity>,\n): EntityCrud<TEntity> {\n const {\n useAdapters,\n basePath,\n catalogKey,\n repository,\n hiddenFields = [],\n columns,\n toolbar,\n links = [],\n metadataSource: givenMetadataSource,\n metadata,\n runBulkUseCase,\n runUseCase,\n } = options;\n\n if (givenMetadataSource !== undefined && metadata !== undefined) {\n throw new EntifixBuildError(\n `${entityConstructor.name} was given both metadataSource and metadata; pass one`,\n );\n }\n // An adapter value, so it is resolved per render from the same `useAdapters()`\n // the records come from — the host's composition, never the caller's module.\n const metadataSourceOf = (adapters: TAdapters) =>\n metadata === undefined\n ? givenMetadataSource\n : (adapters[metadata] as EntityMetadataSource);\n\n const meta = extractMetaEntity(entityConstructor);\n if (meta.key !== catalogKey) {\n throw new EntifixBuildError(\n `${entityConstructor.name} declares key \"${String(meta.key)}\" but was given catalog key \"${catalogKey}\"`,\n );\n }\n // Read off `@entity()` rather than rebuilt from `catalogKey`. Both spellings\n // produce the same string today, and that is exactly the problem: a second\n // place that knows how an entity's catalog subtree is laid out is a second\n // place to fix when one moves. `MetaEntityOptions` makes them optional, so an\n // entity that never declared them fails here — where a screen is generated —\n // rather than on the render that first tries to title a tab with `undefined`.\n const { labelKey: entityLabelKey, pluralKey: entityPluralKey } = meta;\n if (entityLabelKey === undefined || entityPluralKey === undefined) {\n throw new EntifixBuildError(\n `${entityConstructor.name} must declare labelKey and pluralKey on @entity() to be generated`,\n );\n }\n\n // Computed once: a descriptor is a property of the class, so nothing about it\n // depends on the record being edited. `linkLabelProperty`/`linkSearchProperty`\n // are overridden here because a scalar foreign key's `@accessor()` cannot name\n // the target's members — it may not import the target at all.\n // The wire name, which is also what a pending entry records and what\n // `entityQueryScopeFor` keys on — one derivation, so a notice and an\n // invalidation can never disagree about which entity they mean.\n const entityName = envelopeEntityName(entityConstructor);\n const descriptors = describeEntityColumns(entityConstructor);\n const linkPlans = links.map(link => {\n const descriptor = descriptors.find(entry => entry.name === link.field);\n if (descriptor === undefined) {\n throw new EntifixBuildError(\n `${entityConstructor.name} has no member \"${link.field}\" for a link source`,\n );\n }\n return {\n ...link,\n descriptor: {\n ...descriptor,\n linkLabelProperty: link.labelProperty ?? TARGET_NAME_PROPERTY,\n linkSearchProperty: link.searchProperty ?? TARGET_NAME_PROPERTY,\n },\n };\n });\n\n function ListPage() {\n const adapters = useAdapters();\n // Outside a `PendingTransactionsProvider` this watches nothing, so a host\n // that has not mounted one behaves exactly as it did before.\n const pending = usePendingTransactions();\n // Every internal href carries the locale. An unprefixed one still resolves —\n // the middleware redirects it — but the visitor pays a round trip per click.\n const withLocale = useLocaleHref();\n\n const queryClient = useQueryClient();\n const scope = entityQueryScope(entityConstructor);\n const metadataSource = metadataSourceOf(adapters);\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n const renderLink = useCrudRenderLink(catalogKey);\n\n // Records this browser has created but the service has not finished\n // writing. Prepended below rather than patched into the cache, which a\n // refetch would undo.\n const optimistic = pendingRecordsFor<TEntity>(pending, entityName);\n\n const pager = useDataLoading<TEntity, CrudContext>({\n uc: loadUCFactory<TEntity>(),\n ctx: mergeCrudContext(adapters, repository, pending),\n // Scoped rather than left to the per-instance fallback, which is correct\n // but unshared: with the entity's own scope one invalidation refreshes\n // every page and filter of it, which is what a bulk run needs — and it is\n // the same prefix `useReactiveInvalidation`already targets, so a generated\n // list now also refreshes on a reactive change event.\n queryKey: scope,\n });\n\n // Only when this caller may actually run something over a selection.\n //\n // Measured live: an `admin` holds `catalog-reference:*:read` and no\n // `retire`, so the service filters the verb out of `$metadata` — but the\n // selection column still rendered, offering a set that no action could be\n // taken on. A checkbox that can lead nowhere is worse than no checkbox: it\n // reads as a permission the user does not have.\n //\n // Decided from the served document rather than from the runner, because\n // the runner is a property of the *shell* (it knows the route) and the\n // grant is a property of the *caller*. The column therefore appears when\n // the document lands, which is the asynchrony serving affordances accepts\n // for every action surface.\n const canRunBulk =\n useCasesForSurface('bulk-bar', affordances.metadata?.useCases).length > 0;\n\n const bulk = useEntityBulk<TEntity>({\n run: canRunBulk ? runBulkUseCase : undefined,\n // A bulk write changed the rows underneath the listing, so the page is\n // re-read; the selection deliberately survives it (\"the selection\n // is still there afterwards\"), because the operator's next act is usually\n // to retry the failures or run a second verb on the same rows.\n onCompleted: () => {\n void queryClient.invalidateQueries({ queryKey: scope });\n },\n });\n\n // What a row's overflow menu runs, and the one place the list reports a\n // verb that failed.\n //\n // ⚠️ **A row verb and the form's are the same runner with different\n // arguments.** `EntityTable` hands back the whole record, because that is\n // what it has; `runUseCase` takes an id, because that is what a route needs\n // The list has no error slot of its own, so a failure lands in the\n // table's own error region — the same one a failed page read uses.\n const [useCaseError, setUseCaseError] = useState<EntifixError | undefined>(\n undefined,\n );\n // Called unconditionally and the *result* gated, the way the surfaces are\n // read in `EntityForm`: the name begins with `use`, so short-circuiting it\n // reads to `react-hooks/rules-of-hooks` as a conditional hook.\n const rowUseCases = useCasesForSurface(\n 'row-menu',\n affordances.metadata?.useCases,\n );\n const canRunRowUseCase = runUseCase !== undefined && rowUseCases.length > 0;\n\n const handleRowUseCase = canRunRowUseCase\n ? (key: string, item: TEntity) => {\n if (item.id == null) return;\n setUseCaseError(undefined);\n void runUseCase(key, item.id).then(\n () => queryClient.invalidateQueries({ queryKey: scope }),\n (failure: unknown) => setUseCaseError(asEntifixError(failure)),\n );\n }\n : undefined;\n\n return (\n <div className=\"flex flex-col gap-s\">\n {/* Above the table, because this is where `afterSave()` leaves the\n operator after a create — and a create is the only transactional\n write there is, so this is the surface the pending state has. */}\n <PendingNotice\n entries={pendingFor(pending, entityName)}\n onDismiss={pending.dismiss}\n />\n <EntityTable\n entityConstructor={entityConstructor}\n {...pager}\n items={[...optimistic, ...pager.items]}\n totalItems={pager.totalItems + optimistic.length}\n hrefFor={id => withLocale(`${basePath}/${String(id)}`)}\n newHref={withLocale(`${basePath}/${CATALOG_NEW_SLUG}`)}\n renderLink={renderLink}\n {...affordances}\n {...bulk.tableProps}\n onUseCase={handleRowUseCase}\n error={useCaseError ?? pager.error}\n >\n {columns}\n {toolbar}\n </EntityTable>\n </div>\n );\n }\n\n /**\n * Dual-host: as a route it reads its slug from the URL and returns to the list\n * on save; in a workspace tab it takes the slug and the post-save action as\n * props.\n */\n function SingleViewPage({\n slug,\n onSaved,\n onDeleted,\n draft,\n }: EntityCrudSingleViewProps = {}) {\n const adapters = useAdapters();\n const metadataSource = metadataSourceOf(adapters);\n const pending = usePendingTransactions();\n const router = useRouter();\n const withLocale = useLocaleHref();\n const params = useParams<{ slug: string }>();\n // A verb's failure is this page's, not the record fetch's or the mutation's,\n // so it needs a slot of its own to reach the form's error area.\n const [useCaseError, setUseCaseError] = useState<EntifixError | undefined>(\n undefined,\n );\n const id = slugToEntityId(slug ?? params.slug);\n\n const ctx = mergeCrudContext(adapters, repository, pending);\n\n const {\n entity,\n isLoading,\n error: loadError,\n reload,\n } = useEntityRecord<TEntity, CrudContext>({\n uc: getUCFactory<TEntity>(),\n ctx,\n id,\n });\n\n const {\n save,\n remove,\n isSaving,\n isDeleting,\n error: writeError,\n } = useEntityMutation<TEntity, CrudContext>({\n saveUc: saveUCFactory<TEntity>(),\n deleteUc: deleteUCFactory<TEntity>(),\n ctx,\n });\n\n // Rebuilt inline on every render on purpose: `useEntityLinkSource` holds\n // these in a ref and keeps them out of its query keys, precisely so a caller\n // does not have to memoise them.\n const linkSources: EntityCrudLinkSource[] = linkPlans.map(plan => ({\n field: plan.field,\n descriptor: plan.descriptor,\n config: {\n entityConstructor: plan.entityConstructor,\n loadUc: loadUCFactory(),\n getUc: getUCFactory(),\n ctx: mergeCrudContext(adapters, plan.repository, pending),\n },\n }));\n\n // Inside a workspace tab, \"back to the list\" is the list's tab, not a URL\n // that would leave the workspace. A host's own callbacks still win.\n const host = useEntityNavHost();\n const renderLink = useCrudRenderLink(catalogKey);\n const queryClient = useQueryClient();\n // The list this page returns to has its page cached, and it is no longer\n // true. Invalidated rather than patched, for the reason `handOffWrite`\n // gives: a transactional create is not in the service yet, and the pending\n // set, not the cache, is what keeps it visible until it is.\n //\n // ⚠️ Invisible while every Open was a document load, which threw the cache\n // away anyway (#20): the first client-side navigation back to the list\n // showed the record as it was before the save.\n const refreshList = () =>\n queryClient.invalidateQueries({\n queryKey: entityQueryScope(entityConstructor),\n });\n const toList = () =>\n host === undefined\n ? router.push(withLocale(basePath))\n : host.toList(catalogKey);\n const afterSave = onSaved ?? toList;\n const afterDelete = onDeleted ?? toList;\n\n // The draft is spent once the write *commits*, and only here is that known:\n // `useEntityForm` neither fetches nor saves, so it cannot clear its own.\n // A failed mutation deliberately keeps the draft — the edit is still the\n // user's only copy of what they typed.\n const handleSave = async (next: TEntity) => {\n const saved = await save(next);\n if (saved === undefined) return;\n\n // ⚠️ Deliberately *not* a `setQueriesData` patch. The list refetches on\n // mount — precisely when the operator arrives, having just been navigated\n // here — and the server legitimately does not hold the record yet, so the\n // refetch would replace the patched page and the row would vanish a\n // moment after appearing. The pending set outlives refetches.\n handOffWrite({ id: String(saved.id), record: saved, pending, draft });\n void refreshList();\n afterSave();\n };\n\n const handleDelete = async () => {\n if (await remove(id)) {\n draft?.clear();\n void refreshList();\n afterDelete();\n }\n };\n\n /**\n * An `entity`-bound verb, on the record being shown.\n *\n * It **reloads** rather than patching what it has: the service decides the\n * resulting state — a `publish` may land on `published` from four different\n * places — and a client that assumed the new value would show the wrong one\n * the first time the rule changed. `id == null` means the create form,\n * where there is no record to act on and the form renders no verbs anyway.\n *\n * ⚠️ The rejection is **caught and shown**, never left to the promise.\n * `EntityForm`'s `onUseCase` returns `void`, so an uncaught rejection here\n * reaches the console and nothing else — measured on an offering refusing\n * `unpublish` from `draft`: the service answered `409` with a coded body,\n * the record correctly did not move, and the operator saw a button that\n * appeared to do nothing at all.\n */\n const handleUseCase =\n runUseCase === undefined || id == null\n ? undefined\n : (key: string) => {\n setUseCaseError(undefined);\n void runUseCase(key, id).then(\n () => reload(),\n (failure: unknown) => setUseCaseError(asEntifixError(failure)),\n );\n };\n\n return (\n <EntityCrudForm<TEntity>\n // Remounts (and reseeds the fields) once the record arrives.\n key={String(entity?.id ?? CATALOG_NEW_SLUG)}\n entityConstructor={entityConstructor}\n catalogKey={catalogKey}\n metadataSource={metadataSource}\n hiddenFields={hiddenFields}\n links={linkSources}\n entity={entity}\n isLoading={isLoading}\n isSaving={isSaving}\n isDeleting={isDeleting}\n error={loadError ?? writeError ?? useCaseError}\n onSave={handleSave}\n onDelete={id == null ? undefined : handleDelete}\n onUseCase={handleUseCase}\n backHref={withLocale(basePath)}\n renderLink={renderLink}\n draft={draft}\n />\n );\n }\n\n return {\n entityConstructor,\n entityKey: catalogKey,\n entityLabelKey,\n entityPluralKey,\n basePath,\n ListPage,\n SingleViewPage,\n };\n}\n"],"names":["deleteUCFactory","getUCFactory","loadUCFactory","saveUCFactory","describeEntityColumns","EntifixBuildError","EntifixLogicError","envelopeEntityName","extractMetaEntity","EntityTable","useCasesForSurface","entityQueryScope","useDataLoading","useEntityMutation","useEntityRecord","TransactionSinkTag","useQueryClient","Context","useParams","useRouter","useState","useLocaleHref","useEntityNavHost","pendingFor","pendingRecordsFor","usePendingTransactions","EntityCrudForm","handOffWrite","PendingNotice","CATALOG_NEW_SLUG","slugToEntityId","useCrudRenderLink","useEntityAffordances","useEntityBulk","TARGET_NAME_PROPERTY","mergeCrudContext","adapters","repository","sink","add","asEntifixError","failure","Error","message","String","makeEntityCrud","entityConstructor","options","useAdapters","basePath","catalogKey","hiddenFields","columns","toolbar","links","metadataSource","givenMetadataSource","metadata","runBulkUseCase","runUseCase","undefined","name","metadataSourceOf","meta","key","labelKey","entityLabelKey","pluralKey","entityPluralKey","entityName","descriptors","linkPlans","map","link","descriptor","find","entry","field","linkLabelProperty","labelProperty","linkSearchProperty","searchProperty","ListPage","affordances","pending","withLocale","queryClient","scope","renderLink","optimistic","pager","uc","ctx","queryKey","canRunBulk","useCases","length","bulk","run","onCompleted","invalidateQueries","useCaseError","setUseCaseError","rowUseCases","canRunRowUseCase","handleRowUseCase","item","id","then","div","className","entries","onDismiss","dismiss","items","totalItems","hrefFor","newHref","tableProps","onUseCase","error","SingleViewPage","slug","onSaved","onDeleted","draft","loadError","router","params","entity","isLoading","reload","save","remove","isSaving","isDeleting","writeError","saveUc","deleteUc","linkSources","plan","config","loadUc","getUc","host","refreshList","toList","push","afterSave","afterDelete","handleSave","next","saved","record","handleDelete","clear","handleUseCase","onSave","onDelete","backHref","entityKey"],"mappings":"AAAA;;;AAEA,SACEA,eAAe,EAEfC,YAAY,EACZC,aAAa,EACbC,aAAa,QACR,oBAAoB;AAC3B,SACEC,qBAAqB,EACrBC,iBAAiB,EAEjBC,iBAAiB,EAIjBC,kBAAkB,EAClBC,iBAAiB,QACZ,gBAAgB;AACvB,SAASC,WAAW,EAAEC,kBAAkB,QAAQ,0BAA0B;AAC1E,SACEC,gBAAgB,EAChBC,cAAc,EACdC,iBAAiB,EACjBC,eAAe,QACV,6BAA6B;AAEpC,SAASC,kBAAkB,QAAQ,wBAAwB;AAC3D,SAASC,cAAc,QAAQ,wBAAwB;AACvD,SAASC,OAAO,QAAQ,SAAS;AACjC,SAASC,SAAS,EAAEC,SAAS,QAAQ,kBAAkB;AACvD,SAASC,QAAQ,QAAQ,QAAQ;AAEjC,SAASC,aAAa,QAAQ,mBAAmB;AACjD,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SACEC,UAAU,EACVC,iBAAiB,EACjBC,sBAAsB,QACjB,uCAAuC;AAC9C,SAASC,cAAc,QAAQ,wBAAwB;AACvD,SAASC,YAAY,QAAQ,sBAAsB;AAOnD,SAASC,aAAa,QAAQ,sBAAsB;AACpD,SAASC,gBAAgB,EAA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wE;YACxE,0EAA0E;YAC1E,0EAA0E;YAC1E,oEAAoE;YACpE,8DAA8D;YAC9DjC,aAAa;gBAAEgF,IAAI/D,OAAO4G,MAAM7C,EAAE;gBAAG8C,QAAQD;gBAAOpE;gBAASyC;YAAM;YACnE,KAAKoB;YACLG;QACF;QAEA,MAAMM,eAAe;YACnB,IAAI,MAAMrB,OAAO1B,KAAK;gBACpBkB,yBAAAA,MAAO8B,KAAK;gBACZ,KAAKV;gBACLI;YACF;QACF;QAEA;;;;;;;;;;;;;;;KAeC,GACD,MAAMO,gBACJjG,eAAeC,aAAa+C,MAAM,OAC9B/C,YACA,CAACI;YACCsC,gBAAgB1C;YAChB,KAAKD,WAAWK,KAAK2C,IAAIC,IAAI,CAC3B,IAAMuB,UACN,CAAC1F,UAAqB6D,gBAAgB9D,eAAeC;QAEzD;QAEN,qBACE,KAACf;YAGCoB,mBAAmBA;YACnBI,YAAYA;YACZK,gBAAgBA;YAChBJ,cAAcA;YACdG,OAAOqF;YACPV,QAAQA;YACRC,WAAWA;YACXI,UAAUA;YACVC,YAAYA;YACZf,KAAK,GAAEM,OAAAA,oBAAAA,YAAaU,sBAAbV,OAA2BzB;YAClCwD,QAAQP;YACRQ,UAAUnD,MAAM,OAAO/C,YAAY8F;YACnCnC,WAAWqC;YACXG,UAAU1E,WAAWpC;YACrBuC,YAAYA;YACZqC,OAAOA;WAhBFjF,gBAAOqF,0BAAAA,OAAQtB,EAAE,oBAAI9E;IAmBhC;IAEA,OAAO;QACLiB;QACAkH,WAAW9G;QACXgB;QACAE;QACAnB;QACAiC;QACAuC;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/lib/crud/make-entity-crud.tsx"],"sourcesContent":["'use client';\n\nimport {\n deleteUCFactory,\n type EntityRepositoryTag,\n getUCFactory,\n loadUCFactory,\n saveUCFactory,\n} from '@entifix/business';\nimport {\n describeEntityColumns,\n EntifixBuildError,\n type EntifixError,\n EntifixLogicError,\n type Entity,\n type EntityConstructor,\n type EntityMetadataSource,\n envelopeEntityName,\n extractMetaEntity,\n type FilterGroup,\n} from '@entifix/core';\nimport { EntityTable, useCasesForSurface } from '@entifix/react-controls';\nimport {\n entityQueryScope,\n useDataLoading,\n useEntityMutation,\n useEntityRecord,\n} from '@entifix/react-integration';\nimport type { TransactionSink } from '@entifix/transactions';\nimport { TransactionSinkTag } from '@entifix/transactions';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { Context } from 'effect';\nimport { useParams, useRouter } from 'next/navigation';\nimport { useState } from 'react';\n\nimport { useLocaleHref } from '../i18n/index.js';\nimport { useEntityNavHost } from '../workspace/entity-nav.js';\nimport {\n pendingFor,\n pendingRecordsFor,\n usePendingTransactions,\n} from '../workspace/pending-transactions.js';\nimport { EntityCrudForm } from './entity-crud-form.js';\nimport { handOffWrite } from './hand-off-write.js';\nimport type {\n AnyFilterGroup,\n EntityCrud,\n EntityCrudLinkSource,\n EntityCrudOptions,\n EntityCrudSingleViewProps,\n} from './make-entity-crud.types.js';\nimport { PendingNotice } from './pending-notice.js';\nimport { CATALOG_NEW_SLUG, slugToEntityId } from './slug.js';\nimport { useCrudRenderLink } from './use-crud-render-link.js';\nimport { useEntityAffordances } from './use-entity-affordances.js';\nimport { useEntityBulk } from './use-entity-bulk.js';\n\n/** What a picker defaults to reading off its target. */\nconst TARGET_NAME_PROPERTY = 'name';\n\n/**\n * What the generated pages' use-cases run against.\n *\n * Exported because a hand-built screen needs the same three: a wizard reads\n * records, resolves pickers and writes through exactly these ports, and\n * rebuilding the union at each such call site is how one of them ends up\n * missing `TransactionSinkTag` and quietly losing its optimistic treatment.\n */\nexport type CrudContext = EntityRepositoryTag | TransactionSinkTag;\n\n/**\n * Adds the pending-write sink to one repository adapter, giving the context the\n * use-cases run against.\n *\n * The cast is the price of naming adapters by key: `AdapterKey` narrows which\n * names may be *offered*, but TypeScript will not carry that narrowing through\n * an index access on a generic record.\n */\nexport function mergeCrudContext<TAdapters>(\n adapters: TAdapters,\n repository: keyof TAdapters,\n sink: TransactionSink,\n): Context.Context<CrudContext> {\n return Context.add(\n adapters[repository] as Context.Context<EntityRepositoryTag>,\n TransactionSinkTag,\n sink,\n );\n}\n\n/**\n * Builds the list page and the single-record page for one entity.\n *\n * Every catalog entity used to cost ~10 files and ~300 lines whose only variable\n * was a class name: two organisms with a `.types.ts` each, two client pages, two\n * route files. The route files stay (Next needs a module per path); everything\n * between them is derived from the entity's own metadata, so a new reference\n * entity is this call plus a nav entry.\n *\n * Two things are checked here rather than at the call site, because both fail\n * silently otherwise. The catalog key must be the entity's own `@entity({ key })`\n * — they are the same string by convention, and a drifted one titles the form\n * after a different entity in a way only a reader of both catalogs would catch.\n * And a `links` entry must name a real member — a picker aimed at nothing renders\n * identically to a read-only field.\n *\n * **Serves compile-time `@entity()` classes only.** Operator reference data ships\n * with the code, so making this spec-driven would trade type safety for nothing;\n * a vendor-authored `EntitySpecification` renders through a separate path.\n */\n/**\n * A rejected verb, as something the form's error slot can render.\n *\n * `useErrorMessage` resolves `details.code` through the shared `errors`\n * catalog, so a shell that throws an `EntifixError` carrying one gets its\n * translated sentence; anything else — a network failure, a thrown string —\n * keeps its message rather than being relabelled with a code it never had.\n */\nfunction asEntifixError(failure: unknown): EntifixError {\n return failure instanceof EntifixLogicError ||\n failure instanceof EntifixBuildError\n ? failure\n : new EntifixLogicError(\n failure instanceof Error ? failure.message : String(failure),\n );\n}\n\n/**\n * Runs each link's `useBaseFiltering` against the record being edited, in link\n * order, with `undefined` for a link that declares none.\n *\n * Legal for the reason `useEntityLinkSources` gives: the links are a\n * factory-time array, and whether a link carries a rule is fixed with it, so\n * the same hooks run in the same order on every render. The lint rule cannot\n * see a hook called through a member, so there is nothing for it to flag.\n */\nfunction useLinkFilters<TEntity extends Entity>(\n links: readonly {\n readonly useBaseFiltering?: (\n record: TEntity | undefined,\n ) => AnyFilterGroup | undefined;\n }[],\n record: TEntity | undefined,\n): (AnyFilterGroup | undefined)[] {\n return links.map(link => link.useBaseFiltering?.(record));\n}\n\nexport function makeEntityCrud<TEntity extends Entity, TAdapters>(\n entityConstructor: EntityConstructor<TEntity>,\n options: EntityCrudOptions<TAdapters, TEntity>,\n): EntityCrud<TEntity> {\n const {\n useAdapters,\n basePath,\n catalogKey,\n repository,\n hiddenFields = [],\n columns,\n toolbar,\n pageSize,\n links = [],\n metadataSource: givenMetadataSource,\n metadata,\n runBulkUseCase,\n runUseCase,\n } = options;\n\n if (givenMetadataSource !== undefined && metadata !== undefined) {\n throw new EntifixBuildError(\n `${entityConstructor.name} was given both metadataSource and metadata; pass one`,\n );\n }\n // An adapter value, so it is resolved per render from the same `useAdapters()`\n // the records come from — the host's composition, never the caller's module.\n const metadataSourceOf = (adapters: TAdapters) =>\n metadata === undefined\n ? givenMetadataSource\n : (adapters[metadata] as EntityMetadataSource);\n\n const meta = extractMetaEntity(entityConstructor);\n if (meta.key !== catalogKey) {\n throw new EntifixBuildError(\n `${entityConstructor.name} declares key \"${String(meta.key)}\" but was given catalog key \"${catalogKey}\"`,\n );\n }\n // Read off `@entity()` rather than rebuilt from `catalogKey`. Both spellings\n // produce the same string today, and that is exactly the problem: a second\n // place that knows how an entity's catalog subtree is laid out is a second\n // place to fix when one moves. `MetaEntityOptions` makes them optional, so an\n // entity that never declared them fails here — where a screen is generated —\n // rather than on the render that first tries to title a tab with `undefined`.\n const { labelKey: entityLabelKey, pluralKey: entityPluralKey } = meta;\n if (entityLabelKey === undefined || entityPluralKey === undefined) {\n throw new EntifixBuildError(\n `${entityConstructor.name} must declare labelKey and pluralKey on @entity() to be generated`,\n );\n }\n\n // Computed once: a descriptor is a property of the class, so nothing about it\n // depends on the record being edited. `linkLabelProperty`/`linkSearchProperty`\n // are overridden here because a scalar foreign key's `@accessor()` cannot name\n // the target's members — it may not import the target at all.\n // The wire name, which is also what a pending entry records and what\n // `entityQueryScopeFor` keys on — one derivation, so a notice and an\n // invalidation can never disagree about which entity they mean.\n const entityName = envelopeEntityName(entityConstructor);\n const descriptors = describeEntityColumns(entityConstructor);\n const linkPlans = links.map(link => {\n const descriptor = descriptors.find(entry => entry.name === link.field);\n if (descriptor === undefined) {\n throw new EntifixBuildError(\n `${entityConstructor.name} has no member \"${link.field}\" for a link source`,\n );\n }\n return {\n ...link,\n descriptor: {\n ...descriptor,\n linkLabelProperty: link.labelProperty ?? TARGET_NAME_PROPERTY,\n linkSearchProperty: link.searchProperty ?? TARGET_NAME_PROPERTY,\n },\n };\n });\n\n function ListPage() {\n const adapters = useAdapters();\n // Outside a `PendingTransactionsProvider` this watches nothing, so a host\n // that has not mounted one behaves exactly as it did before.\n const pending = usePendingTransactions();\n // Every internal href carries the locale. An unprefixed one still resolves —\n // the middleware redirects it — but the visitor pays a round trip per click.\n const withLocale = useLocaleHref();\n\n const queryClient = useQueryClient();\n const scope = entityQueryScope(entityConstructor);\n const metadataSource = metadataSourceOf(adapters);\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n const renderLink = useCrudRenderLink(catalogKey);\n\n // Records this browser has created but the service has not finished\n // writing. Prepended below rather than patched into the cache, which a\n // refetch would undo.\n const optimistic = pendingRecordsFor<TEntity>(pending, entityName);\n\n const pager = useDataLoading<TEntity, CrudContext>({\n uc: loadUCFactory<TEntity>(),\n ctx: mergeCrudContext(adapters, repository, pending),\n // Scoped rather than left to the per-instance fallback, which is correct\n // but unshared: with the entity's own scope one invalidation refreshes\n // every page and filter of it, which is what a bulk run needs — and it is\n // the same prefix `useReactiveInvalidation`already targets, so a generated\n // list now also refreshes on a reactive change event.\n queryKey: scope,\n ...(pageSize === undefined ? {} : { initialPageSize: pageSize }),\n });\n\n // Only when this caller may actually run something over a selection.\n //\n // Measured live: an `admin` holds `catalog-reference:*:read` and no\n // `retire`, so the service filters the verb out of `$metadata` — but the\n // selection column still rendered, offering a set that no action could be\n // taken on. A checkbox that can lead nowhere is worse than no checkbox: it\n // reads as a permission the user does not have.\n //\n // Decided from the served document rather than from the runner, because\n // the runner is a property of the *shell* (it knows the route) and the\n // grant is a property of the *caller*. The column therefore appears when\n // the document lands, which is the asynchrony serving affordances accepts\n // for every action surface.\n const canRunBulk =\n useCasesForSurface('bulk-bar', affordances.metadata?.useCases).length > 0;\n\n const bulk = useEntityBulk<TEntity>({\n run: canRunBulk ? runBulkUseCase : undefined,\n // A bulk write changed the rows underneath the listing, so the page is\n // re-read; the selection deliberately survives it (\"the selection\n // is still there afterwards\"), because the operator's next act is usually\n // to retry the failures or run a second verb on the same rows.\n onCompleted: () => {\n void queryClient.invalidateQueries({ queryKey: scope });\n },\n });\n\n // What a row's overflow menu runs, and the one place the list reports a\n // verb that failed.\n //\n // ⚠️ **A row verb and the form's are the same runner with different\n // arguments.** `EntityTable` hands back the whole record, because that is\n // what it has; `runUseCase` takes an id, because that is what a route needs\n // The list has no error slot of its own, so a failure lands in the\n // table's own error region — the same one a failed page read uses.\n const [useCaseError, setUseCaseError] = useState<EntifixError | undefined>(\n undefined,\n );\n // Called unconditionally and the *result* gated, the way the surfaces are\n // read in `EntityForm`: the name begins with `use`, so short-circuiting it\n // reads to `react-hooks/rules-of-hooks` as a conditional hook.\n const rowUseCases = useCasesForSurface(\n 'row-menu',\n affordances.metadata?.useCases,\n );\n const canRunRowUseCase = runUseCase !== undefined && rowUseCases.length > 0;\n\n const handleRowUseCase = canRunRowUseCase\n ? (key: string, item: TEntity) => {\n if (item.id == null) return;\n setUseCaseError(undefined);\n void runUseCase(key, item.id).then(\n () => queryClient.invalidateQueries({ queryKey: scope }),\n (failure: unknown) => setUseCaseError(asEntifixError(failure)),\n );\n }\n : undefined;\n\n return (\n <div className=\"flex flex-col gap-s\">\n {/* Above the table, because this is where `afterSave()` leaves the\n operator after a create — and a create is the only transactional\n write there is, so this is the surface the pending state has. */}\n <PendingNotice\n entries={pendingFor(pending, entityName)}\n onDismiss={pending.dismiss}\n />\n <EntityTable\n entityConstructor={entityConstructor}\n {...pager}\n items={[...optimistic, ...pager.items]}\n totalItems={pager.totalItems + optimistic.length}\n hrefFor={id => withLocale(`${basePath}/${String(id)}`)}\n newHref={withLocale(`${basePath}/${CATALOG_NEW_SLUG}`)}\n renderLink={renderLink}\n {...affordances}\n {...bulk.tableProps}\n onUseCase={handleRowUseCase}\n error={useCaseError ?? pager.error}\n >\n {columns}\n {toolbar}\n </EntityTable>\n </div>\n );\n }\n\n /**\n * Dual-host: as a route it reads its slug from the URL and returns to the list\n * on save; in a workspace tab it takes the slug and the post-save action as\n * props.\n */\n function SingleViewPage({\n slug,\n onSaved,\n onDeleted,\n draft,\n }: EntityCrudSingleViewProps = {}) {\n const adapters = useAdapters();\n const metadataSource = metadataSourceOf(adapters);\n const pending = usePendingTransactions();\n const router = useRouter();\n const withLocale = useLocaleHref();\n const params = useParams<{ slug: string }>();\n // A verb's failure is this page's, not the record fetch's or the mutation's,\n // so it needs a slot of its own to reach the form's error area.\n const [useCaseError, setUseCaseError] = useState<EntifixError | undefined>(\n undefined,\n );\n const id = slugToEntityId(slug ?? params.slug);\n\n const ctx = mergeCrudContext(adapters, repository, pending);\n\n const {\n entity,\n isLoading,\n error: loadError,\n reload,\n } = useEntityRecord<TEntity, CrudContext>({\n uc: getUCFactory<TEntity>(),\n ctx,\n id,\n });\n\n const {\n save,\n remove,\n isSaving,\n isDeleting,\n error: writeError,\n } = useEntityMutation<TEntity, CrudContext>({\n saveUc: saveUCFactory<TEntity>(),\n deleteUc: deleteUCFactory<TEntity>(),\n ctx,\n });\n\n // Against the record as loaded, not the draft: the rule is about which\n // record this is, not what the operator has typed into it.\n const linkFilters = useLinkFilters(linkPlans, entity);\n\n // Rebuilt inline on every render on purpose: `useEntityLinkSource` holds\n // these in a ref and keeps them out of its query keys, precisely so a caller\n // does not have to memoise them.\n const linkSources: EntityCrudLinkSource[] = linkPlans.map(\n (plan, index) => ({\n field: plan.field,\n descriptor: plan.descriptor,\n config: {\n entityConstructor: plan.entityConstructor,\n loadUc: loadUCFactory(),\n getUc: getUCFactory(),\n ctx: mergeCrudContext(adapters, plan.repository, pending),\n // The config's target is erased to `Entity`, and the host's filter to\n // `any`; the two meet here, where neither type is the real target's.\n baseFiltering: linkFilters[index] as FilterGroup<Entity> | undefined,\n },\n }),\n );\n\n // Inside a workspace tab, \"back to the list\" is the list's tab, not a URL\n // that would leave the workspace. A host's own callbacks still win.\n const host = useEntityNavHost();\n const renderLink = useCrudRenderLink(catalogKey);\n const queryClient = useQueryClient();\n // The list this page returns to has its page cached, and it is no longer\n // true. Invalidated rather than patched, for the reason `handOffWrite`\n // gives: a transactional create is not in the service yet, and the pending\n // set, not the cache, is what keeps it visible until it is.\n //\n // ⚠️ Invisible while every Open was a document load, which threw the cache\n // away anyway (#20): the first client-side navigation back to the list\n // showed the record as it was before the save.\n const refreshList = () =>\n queryClient.invalidateQueries({\n queryKey: entityQueryScope(entityConstructor),\n });\n const toList = () =>\n host === undefined\n ? router.push(withLocale(basePath))\n : host.toList(catalogKey);\n const afterSave = onSaved ?? toList;\n const afterDelete = onDeleted ?? toList;\n\n // The draft is spent once the write *commits*, and only here is that known:\n // `useEntityForm` neither fetches nor saves, so it cannot clear its own.\n // A failed mutation deliberately keeps the draft — the edit is still the\n // user's only copy of what they typed.\n const handleSave = async (next: TEntity) => {\n const saved = await save(next);\n if (saved === undefined) return;\n\n // ⚠️ Deliberately *not* a `setQueriesData` patch. The list refetches on\n // mount — precisely when the operator arrives, having just been navigated\n // here — and the server legitimately does not hold the record yet, so the\n // refetch would replace the patched page and the row would vanish a\n // moment after appearing. The pending set outlives refetches.\n handOffWrite({ id: String(saved.id), record: saved, pending, draft });\n void refreshList();\n afterSave();\n };\n\n const handleDelete = async () => {\n if (await remove(id)) {\n draft?.clear();\n void refreshList();\n afterDelete();\n }\n };\n\n /**\n * An `entity`-bound verb, on the record being shown.\n *\n * It **reloads** rather than patching what it has: the service decides the\n * resulting state — a `publish` may land on `published` from four different\n * places — and a client that assumed the new value would show the wrong one\n * the first time the rule changed. `id == null` means the create form,\n * where there is no record to act on and the form renders no verbs anyway.\n *\n * ⚠️ The rejection is **caught and shown**, never left to the promise.\n * `EntityForm`'s `onUseCase` returns `void`, so an uncaught rejection here\n * reaches the console and nothing else — measured on an offering refusing\n * `unpublish` from `draft`: the service answered `409` with a coded body,\n * the record correctly did not move, and the operator saw a button that\n * appeared to do nothing at all.\n */\n const handleUseCase =\n runUseCase === undefined || id == null\n ? undefined\n : (key: string) => {\n setUseCaseError(undefined);\n void runUseCase(key, id).then(\n () => reload(),\n (failure: unknown) => setUseCaseError(asEntifixError(failure)),\n );\n };\n\n return (\n <EntityCrudForm<TEntity>\n // Remounts (and reseeds the fields) once the record arrives.\n key={String(entity?.id ?? CATALOG_NEW_SLUG)}\n entityConstructor={entityConstructor}\n catalogKey={catalogKey}\n metadataSource={metadataSource}\n hiddenFields={hiddenFields}\n links={linkSources}\n entity={entity}\n isLoading={isLoading}\n isSaving={isSaving}\n isDeleting={isDeleting}\n error={loadError ?? writeError ?? useCaseError}\n onSave={handleSave}\n onDelete={id == null ? undefined : handleDelete}\n onUseCase={handleUseCase}\n backHref={withLocale(basePath)}\n renderLink={renderLink}\n draft={draft}\n />\n );\n }\n\n return {\n entityConstructor,\n entityKey: catalogKey,\n entityLabelKey,\n entityPluralKey,\n basePath,\n ListPage,\n SingleViewPage,\n };\n}\n"],"names":["deleteUCFactory","getUCFactory","loadUCFactory","saveUCFactory","describeEntityColumns","EntifixBuildError","EntifixLogicError","envelopeEntityName","extractMetaEntity","EntityTable","useCasesForSurface","entityQueryScope","useDataLoading","useEntityMutation","useEntityRecord","TransactionSinkTag","useQueryClient","Context","useParams","useRouter","useState","useLocaleHref","useEntityNavHost","pendingFor","pendingRecordsFor","usePendingTransactions","EntityCrudForm","handOffWrite","PendingNotice","CATALOG_NEW_SLUG","slugToEntityId","useCrudRenderLink","useEntityAffordances","useEntityBulk","TARGET_NAME_PROPERTY","mergeCrudContext","adapters","repository","sink","add","asEntifixError","failure","Error","message","String","useLinkFilters","links","record","map","link","useBaseFiltering","makeEntityCrud","entityConstructor","options","useAdapters","basePath","catalogKey","hiddenFields","columns","toolbar","pageSize","metadataSource","givenMetadataSource","metadata","runBulkUseCase","runUseCase","undefined","name","metadataSourceOf","meta","key","labelKey","entityLabelKey","pluralKey","entityPluralKey","entityName","descriptors","linkPlans","descriptor","find","entry","field","linkLabelProperty","labelProperty","linkSearchProperty","searchProperty","ListPage","affordances","pending","withLocale","queryClient","scope","renderLink","optimistic","pager","uc","ctx","queryKey","initialPageSize","canRunBulk","useCases","length","bulk","run","onCompleted","invalidateQueries","useCaseError","setUseCaseError","rowUseCases","canRunRowUseCase","handleRowUseCase","item","id","then","div","className","entries","onDismiss","dismiss","items","totalItems","hrefFor","newHref","tableProps","onUseCase","error","SingleViewPage","slug","onSaved","onDeleted","draft","loadError","router","params","entity","isLoading","reload","save","remove","isSaving","isDeleting","writeError","saveUc","deleteUc","linkFilters","linkSources","plan","index","config","loadUc","getUc","baseFiltering","host","refreshList","toList","push","afterSave","afterDelete","handleSave","next","saved","handleDelete","clear","handleUseCase","onSave","onDelete","backHref","entityKey"],"mappings":"AAAA;;;AAEA,SACEA,eAAe,EAEfC,YAAY,EACZC,aAAa,EACbC,aAAa,QACR,oBAAoB;AAC3B,SACEC,qBAAqB,EACrBC,iBAAiB,EAEjBC,iBAAiB,EAIjBC,kBAAkB,EAClBC,iBAAiB,QAEZ,gBAAgB;AACvB,SAASC,WAAW,EAAEC,kBAAkB,QAAQ,0BAA0B;AAC1E,SACEC,gBAAgB,EAChBC,cAAc,EACdC,iBAAiB,EACjBC,eAAe,QACV,6BAA6B;AAEpC,SAASC,kBAAkB,QAAQ,wBAAwB;AAC3D,SAASC,cAAc,QAAQ,wBAAwB;AACvD,SAASC,OAAO,QAAQ,SAAS;AACjC,SAASC,SAAS,EAAEC,SAAS,QAAQ,kBAAkB;AACvD,SAASC,QAAQ,QAAQ,QAAQ;AAEjC,SAASC,aAAa,QAAQ,mBAAmB;AACjD,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SACEC,UAAU,EACVC,iBAAiB,EACjBC,sBAAsB,QACjB,uCAAuC;AA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V,OAA2BzB;YAClC0D,QAAQN;YACRO,UAAUrD,MAAM,OAAO9C,YAAY+F;YACnCrC,WAAWuC;YACXG,UAAU7E,WAAWlC;YACrBqC,YAAYA;YACZsC,OAAOA;WAhBFtF,gBAAO0F,0BAAAA,OAAQtB,EAAE,oBAAInF;IAmBhC;IAEA,OAAO;QACLuB;QACAmH,WAAW/G;QACXgB;QACAE;QACAnB;QACA+B;QACAwC;IACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import type { EntityRepositoryTag } from '@entifix/business';
2
- import type { BulkOutcome, Entity, EntityConstructor, EntityFieldDescriptor, EntityId, EntityMetadataSource, EntitySelection } from '@entifix/core';
2
+ import type { BulkOutcome, Entity, EntityConstructor, EntityFieldDescriptor, EntityId, EntityMetadataSource, EntitySelection, FilterGroup } from '@entifix/core';
3
3
  import type { EntityDraftStore, EntityLinkSourceConfig } from '@entifix/react-integration';
4
4
  import type { Context } from 'effect/Context';
5
5
  import type { CustomTypeOptions } from 'i18next';
@@ -73,7 +73,7 @@ type EntityCatalogOf<TResources> = TResources extends {
73
73
  * `400`; `useEntityLinkSource` throws at render rather than letting that surface
74
74
  * as an empty suggestion list.
75
75
  */
76
- export interface EntityCrudLink<TAdapters> {
76
+ export interface EntityCrudLink<TAdapters, TEntity extends Entity = Entity> {
77
77
  /** The owning entity's accessor name, e.g. `'brandId'`. */
78
78
  readonly field: string;
79
79
  readonly entityConstructor: EntityConstructor<Entity>;
@@ -87,7 +87,33 @@ export interface EntityCrudLink<TAdapters> {
87
87
  readonly labelProperty?: string;
88
88
  /** Defaults to `'name'`. Must be `filterable` on the target. */
89
89
  readonly searchProperty?: string;
90
+ /**
91
+ * A restriction on what may be picked **for this record**, ANDed into every
92
+ * quick and browse request — `useEntityLinkSource`'s `baseFiltering`, built
93
+ * from the record being edited rather than fixed at factory time.
94
+ *
95
+ * A record-dependent rule is the case it exists for: a parent picker that
96
+ * must not offer the record itself or anything beneath it. That rule needs
97
+ * more than the record — its descendants are other records — which is why
98
+ * this is a **hook** and not a function of the record: it may load what it
99
+ * needs through the host's own adapters, and answer `undefined` until it has.
100
+ *
101
+ * Called on every render of the single view, under the rules of hooks: once
102
+ * per link, unconditionally, with `undefined` while the record loads and
103
+ * throughout a create. `undefined` back means no restriction. Its members
104
+ * must be `filterable` on the target, or the service answers `400`. It
105
+ * narrows the suggestions and nothing else — the service still has to refuse
106
+ * a value the picker would not have offered.
107
+ */
108
+ readonly useBaseFiltering?: (record: TEntity | undefined) => AnyFilterGroup | undefined;
90
109
  }
110
+ /**
111
+ * A restriction over a picker's target, with the target's type erased — the
112
+ * link names its target only as `EntityConstructor<Entity>`, so a filter typed
113
+ * on the real target would not be assignable. Erased for the reason
114
+ * {@link AnyEntityLinkSourceConfig} is.
115
+ */
116
+ export type AnyFilterGroup = FilterGroup<any>;
91
117
  /** The keys of `TAdapters` whose value is assignable to `TValue`. */
92
118
  export type AdapterKey<TAdapters, TValue> = {
93
119
  [K in keyof TAdapters]: TAdapters[K] extends TValue ? K : never;
@@ -124,8 +150,17 @@ export interface EntityCrudOptions<TAdapters, TEntity extends Entity> {
124
150
  * to go here is a link into a wizard, which is not a column by any reading.
125
151
  */
126
152
  readonly toolbar?: ReactNode;
153
+ /**
154
+ * How many rows the list asks for on its first load. Defaults to
155
+ * `useDataLoading`'s own default.
156
+ *
157
+ * Raised for a vocabulary that should be seen whole: `EntityTable` nests a
158
+ * hierarchy only within the page it was given, so a tree larger than one page
159
+ * shows the children whose parent fell on another page as roots.
160
+ */
161
+ readonly pageSize?: number;
127
162
  /** Frozen at factory time — see `use-entity-link-sources.ts`. */
128
- readonly links?: readonly EntityCrudLink<TAdapters>[];
163
+ readonly links?: readonly EntityCrudLink<TAdapters, TEntity>[];
129
164
  /**
130
165
  * Where the entity's served affordances come from — `GET /api/<entity>/$metadata`.
131
166
  *
@@ -1 +1 @@
1
- {"version":3,"file":"make-entity-crud.types.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/make-entity-crud.types.ts"],"names":[],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ositoryTag } from '@entifix/business';\nimport type {\n BulkOutcome,\n Entity,\n EntityConstructor,\n EntityFieldDescriptor,\n EntityId,\n EntityMetadataSource,\n EntitySelection,\n} from '@entifix/core';\nimport type {\n EntityDraftStore,\n EntityLinkSourceConfig,\n} from '@entifix/react-integration';\nimport type { Context } from 'effect/Context';\nimport type { CustomTypeOptions } from 'i18next';\nimport type { ReactElement, ReactNode } from 'react';\n\n/**\n * The `entity` catalog keys that carry **both** form titles, a `label` and a\n * `plural`.\n *\n * Derived from the Spanish catalog rather than written out, so the union is the\n * catalog: an entity whose subtree has no `form.editTitle`/`form.newTitle`\n * cannot be handed to {@link makeEntityCrud} at all, and adding a reference\n * entity therefore starts by adding its copy to both locales. That is the whole\n * i18n gate for this factory — a host's catalog check typically scans its\n * domain packages for `@useCase()` decorators and never `.tsx`, so a runtime\n * key here would be checked by nothing.\n *\n * `label`/`plural` joined the condition when {@link EntityCrud} began carrying\n * them, so that a workspace tab and a nav entry derived from this descriptor\n * name the entity in the catalog's own words. They are part of the **type**\n * rather than a runtime assertion in the factory, because the catalog is\n * statically known here: a missing `plural` should fail at the call site that\n * generates the screens, not on the render that first tries to title a tab.\n *\n * Keeping the key typed is what lets the generated form call `useT('entity')`\n * with a template literal and still fail the build on a typo, instead of\n * reaching for the `useTranslateKey` escape hatch that authored copy must not\n * use. `AccountLabelKey` in `../session/account-links.ts` is the same trick\n * written out by hand; this one cannot drift because it is computed.\n */\nexport type EntityCatalogKey<\n TEntityCatalog = EntityCatalogOf<TypeOptionsResources>,\n> = [TEntityCatalog] extends [never]\n ? // No host augmentation in this compilation — this package's own specs, or\n // an adopter who has not declared one. The factory still works; the key is\n // simply unchecked, which is the same trade `useTranslateKey` makes.\n string\n : {\n [K in keyof TEntityCatalog]: TEntityCatalog[K] extends {\n form: { editTitle: string; newTitle: string };\n label: string;\n plural: string;\n }\n ? K\n : never;\n }[keyof TEntityCatalog] &\n string;\n\n/**\n * The host's `entity` namespace, read back out of its own `i18next`\n * augmentation.\n *\n * ⚠️ **The `entity` catalog is the host's, not entifix's.** It names *their*\n * entities — a parameter, an offering, a sales channel — so a framework that\n * shipped one would be shipping an application's product copy. Reading it back\n * through `CustomTypeOptions` keeps the key union computed rather than written\n * out, which is what stops it drifting, while leaving the catalog where it\n * belongs. A host that declares no augmentation gets `string`, and the factory\n * still works with the gate relaxed.\n */\ntype TypeOptionsResources = CustomTypeOptions extends { resources: infer R }\n ? R\n : never;\n\ntype EntityCatalogOf<TResources> = TResources extends { entity: infer E }\n ? E\n : never;\n\n/**\n * A relation the generated form edits with a picker.\n *\n * The target is named here rather than derived, because the common case is a\n * **plain foreign key**: when the target lives in another slice's store a typed\n * `EntityLink` is both an illegal import and a cross-store join, so the member\n * is a bare `string` (`ProductSpecification.brandId` into `catalog-reference`)\n * and its `@accessor()` has no vocabulary for \"the target's name\". Hence\n * `labelProperty`/`searchProperty` are stated at the call site instead of being\n * left to `describeEntityColumns`' `'name'` default, which happens to be right\n * today and states nothing.\n *\n * `searchProperty` must be `filterable` on the **target** or the service answers\n * `400`; `useEntityLinkSource` throws at render rather than letting that surface\n * as an empty suggestion list.\n */\nexport interface EntityCrudLink<TAdapters> {\n /** The owning entity's accessor name, e.g. `'brandId'`. */\n readonly field: string;\n readonly entityConstructor: EntityConstructor<Entity>;\n /**\n * Which adapter holds the **target's** repository. Often a different service\n * than the record's own: `catalog-reference` is another slice's store, so\n * resolving an id goes through that domain's own read path.\n */\n readonly repository: AdapterKey<TAdapters, Context<EntityRepositoryTag>>;\n /** Defaults to `'name'`. */\n readonly labelProperty?: string;\n /** Defaults to `'name'`. Must be `filterable` on the target. */\n readonly searchProperty?: string;\n}\n\n/** The keys of `TAdapters` whose value is assignable to `TValue`. */\nexport type AdapterKey<TAdapters, TValue> = {\n [K in keyof TAdapters]: TAdapters[K] extends TValue ? K : never;\n}[keyof TAdapters];\n\nexport interface EntityCrudOptions<TAdapters, TEntity extends Entity> {\n /** The domain shell's adapters hook, e.g. `useMarketplaceAdminAdapters`. */\n readonly useAdapters: () => TAdapters;\n /** Route prefix for both pages, e.g. `'/catalog/product-brand'`. */\n readonly basePath: string;\n /**\n * The entity's `entity` catalog key. Asserted against `@entity({ key })` at\n * factory time — the two are the same string by convention\n * (`entity:product-brand.label` mirrors `key: 'product-brand'`), and letting\n * them drift would title a form after a different entity.\n */\n readonly catalogKey: EntityCatalogKey;\n /** Which adapter holds this entity's own repository. */\n readonly repository: AdapterKey<TAdapters, Context<EntityRepositoryTag>>;\n /**\n * Members the form keeps but does not show — `id` always, plus anything a\n * transaction assigns. A hidden member still round-trips: it is dropped from\n * the rendered fields, not from the draft, so `reconstructEntity` carries it\n * back out of the seeded values.\n */\n readonly hiddenFields?: readonly string[];\n /** `<EntityColumn>` overrides for the list, for presentation metadata cannot express. */\n readonly columns?: ReactNode;\n /**\n * Extra controls beside the table's own — an `<EntityTableToolbar>`.\n *\n * Its own option rather than more `columns`, though both end up as\n * `EntityTable` children and the slots are sorted by component identity: a\n * toolbar filed under a columns prop is a name that lies, and the first thing\n * to go here is a link into a wizard, which is not a column by any reading.\n */\n readonly toolbar?: ReactNode;\n /** Frozen at factory time — see `use-entity-link-sources.ts`. */\n readonly links?: readonly EntityCrudLink<TAdapters>[];\n /**\n * Where the entity's served affordances come from — `GET /api/<entity>/$metadata`.\n *\n * Supplying it is what turns on every served affordance:\n * Save and Delete filtered against the caller's real grants, the declared\n * verbs on the form, the row overflow menu, and the bulk bar. Omitting it\n * keeps the pre-0026 behaviour exactly, which is what every generated catalog\n * rendered before this option existed.\n *\n * A `EntityMetadataSource` rather than a URL because the two hosts reach\n * their service differently — one through the config-driven REST adapters,\n * one through a shell's own same-origin routes.\n */\n readonly metadataSource?: EntityMetadataSource;\n /**\n * Which adapter holds this entity's {@link EntityMetadataSource} — the same\n * source as {@link metadataSource}, resolved from the host's composition\n * instead of built by the caller.\n *\n * Prefer it: a source is a transport, and naming it by key keeps the module\n * that generates the screens free of the adapter that fetches, exactly as\n * {@link repository} already does for records. Supplying both is a build\n * error — two answers to where the document comes from.\n */\n readonly metadata?: AdapterKey<TAdapters, EntityMetadataSource>;\n /**\n * Runs a `collection`-bound verb over a selection, and reports **per row**.\n *\n * Supplying it opts the list into the selection column and the bulk bar.\n * It is separate from `metadataSource` because the two are independent: an\n * entity can declare no collection verb and still want permission-filtered\n * Save, and the endpoint a verb posts to is the shell's knowledge, not\n * metadata's.\n */\n readonly runBulkUseCase?: (\n key: string,\n selection: EntitySelection<TEntity>,\n ) => Promise<readonly BulkOutcome[]>;\n /**\n * Runs an `entity`-bound verb on the record the single view is showing.\n *\n * The sibling of {@link runBulkUseCase}, and it had to exist for the same\n * reason: `EntityForm` has rendered these buttons for a long time, and\n * `EntityCrudForm` has accepted an `onUseCase` for as long — but nothing ever\n * passed one, so a generated screen showed a declared, granted, served verb\n * that did nothing when clicked. Measured on `ProductOffering`'s `publish`,\n * which passed every check its host's register ran and appeared nowhere.\n *\n * Resolving means the record changed, and the page reloads it: a verb that\n * moves a lifecycle leaves the form showing the old state otherwise, which\n * reads as \"the button did nothing\". Rejecting surfaces through the form's\n * own error slot, so a `409` from an illegal transition renders as the coded\n * message the catalog holds rather than a thrown promise nobody catches.\n */\n readonly runUseCase?: (key: string, id: EntityId) => Promise<void>;\n}\n\n/**\n * Props both hosts pass. A route host passes none — the slug comes from the URL\n * and a save returns to the list; the workspace tab host passes all of them.\n */\nexport interface EntityCrudSingleViewProps {\n /** Defaults to the `[slug]` route param. */\n readonly slug?: string;\n /** Defaults to navigating back to the list. */\n readonly onSaved?: () => void;\n readonly onDeleted?: () => void;\n /**\n * Where to autosave the edit. Supplying it is the whole opt-in: the form\n * seeds from the persisted draft, writes to it on every edit, and the page\n * clears it once a save or delete commits.\n *\n * A route host omits it and stays ephemeral, which is the rule stated as a\n * missing prop rather than as a flag — there is no value of \"absent\" that\n * accidentally starts persisting.\n */\n readonly draft?: EntityDraftStore;\n}\n\n/**\n * What the factory returns: a **named descriptor**, not four loose components.\n *\n * The identity fields are here so the workspace registry and the nav are derived\n * from a list of these rather than from the hand-written const maps they replace.\n */\nexport interface EntityCrud<TEntity extends Entity> {\n readonly entityConstructor: EntityConstructor<TEntity>;\n /** `@entity({ key })`, which is also `catalogKey` and the tab address payload. */\n readonly entityKey: EntityCatalogKey;\n /**\n * `@entity({ labelKey })` — how one record is named. A record tab's title.\n *\n * Read off the decorator rather than passed, so the tab strip, the nav and the\n * search results all name the entity from the one place it names itself.\n */\n readonly entityLabelKey: string;\n /** `@entity({ pluralKey })` — how the collection is named. A list tab's title. */\n readonly entityPluralKey: string;\n readonly basePath: string;\n readonly ListPage: () => ReactElement;\n readonly SingleViewPage: (props?: EntityCrudSingleViewProps) => ReactElement;\n}\n\n/**\n * A picker's transport with its context tags erased.\n *\n * The factory cannot preserve one type parameter per link — the pages that\n * build these know their adapters, the generated form only forwards them — and\n * `EntityForm.linkSources` is already `Record<string, EntityLinkSource<any>>`\n * for the same reason.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyEntityLinkSourceConfig = EntityLinkSourceConfig<Entity, any>;\n\n/**\n * One picker, resolved: the descriptor computed once at factory time, and the\n * use-cases plus adapter context the page builds per render.\n */\nexport interface EntityCrudLinkSource {\n readonly field: string;\n readonly descriptor: EntityFieldDescriptor;\n readonly config: AnyEntityLinkSourceConfig;\n}\n"],"names":[],"mappings":"AA0QA;;;CAGC,GACD,WAIC"}
1
+ {"version":3,"sources":["../../../src/lib/crud/make-entity-crud.types.ts"],"sourcesContent":["import type { EntityRepositoryTag } from '@entifix/business';\nimport type {\n BulkOutcome,\n Entity,\n EntityConstructor,\n EntityFieldDescriptor,\n EntityId,\n EntityMetadataSource,\n EntitySelection,\n FilterGroup,\n} from '@entifix/core';\nimport type {\n EntityDraftStore,\n EntityLinkSourceConfig,\n} from '@entifix/react-integration';\nimport type { Context } from 'effect/Context';\nimport type { CustomTypeOptions } from 'i18next';\nimport type { ReactElement, ReactNode } from 'react';\n\n/**\n * The `entity` catalog keys that carry **both** form titles, a `label` and a\n * `plural`.\n *\n * Derived from the Spanish catalog rather than written out, so the union is the\n * catalog: an entity whose subtree has no `form.editTitle`/`form.newTitle`\n * cannot be handed to {@link makeEntityCrud} at all, and adding a reference\n * entity therefore starts by adding its copy to both locales. That is the whole\n * i18n gate for this factory — a host's catalog check typically scans its\n * domain packages for `@useCase()` decorators and never `.tsx`, so a runtime\n * key here would be checked by nothing.\n *\n * `label`/`plural` joined the condition when {@link EntityCrud} began carrying\n * them, so that a workspace tab and a nav entry derived from this descriptor\n * name the entity in the catalog's own words. They are part of the **type**\n * rather than a runtime assertion in the factory, because the catalog is\n * statically known here: a missing `plural` should fail at the call site that\n * generates the screens, not on the render that first tries to title a tab.\n *\n * Keeping the key typed is what lets the generated form call `useT('entity')`\n * with a template literal and still fail the build on a typo, instead of\n * reaching for the `useTranslateKey` escape hatch that authored copy must not\n * use. `AccountLabelKey` in `../session/account-links.ts` is the same trick\n * written out by hand; this one cannot drift because it is computed.\n */\nexport type EntityCatalogKey<\n TEntityCatalog = EntityCatalogOf<TypeOptionsResources>,\n> = [TEntityCatalog] extends [never]\n ? // No host augmentation in this compilation — this package's own specs, or\n // an adopter who has not declared one. The factory still works; the key is\n // simply unchecked, which is the same trade `useTranslateKey` makes.\n string\n : {\n [K in keyof TEntityCatalog]: TEntityCatalog[K] extends {\n form: { editTitle: string; newTitle: string };\n label: string;\n plural: string;\n }\n ? K\n : never;\n }[keyof TEntityCatalog] &\n string;\n\n/**\n * The host's `entity` namespace, read back out of its own `i18next`\n * augmentation.\n *\n * ⚠️ **The `entity` catalog is the host's, not entifix's.** It names *their*\n * entities — a parameter, an offering, a sales channel — so a framework that\n * shipped one would be shipping an application's product copy. Reading it back\n * through `CustomTypeOptions` keeps the key union computed rather than written\n * out, which is what stops it drifting, while leaving the catalog where it\n * belongs. A host that declares no augmentation gets `string`, and the factory\n * still works with the gate relaxed.\n */\ntype TypeOptionsResources = CustomTypeOptions extends { resources: infer R }\n ? R\n : never;\n\ntype EntityCatalogOf<TResources> = TResources extends { entity: infer E }\n ? E\n : never;\n\n/**\n * A relation the generated form edits with a picker.\n *\n * The target is named here rather than derived, because the common case is a\n * **plain foreign key**: when the target lives in another slice's store a typed\n * `EntityLink` is both an illegal import and a cross-store join, so the member\n * is a bare `string` (`ProductSpecification.brandId` into `catalog-reference`)\n * and its `@accessor()` has no vocabulary for \"the target's name\". Hence\n * `labelProperty`/`searchProperty` are stated at the call site instead of being\n * left to `describeEntityColumns`' `'name'` default, which happens to be right\n * today and states nothing.\n *\n * `searchProperty` must be `filterable` on the **target** or the service answers\n * `400`; `useEntityLinkSource` throws at render rather than letting that surface\n * as an empty suggestion list.\n */\nexport interface EntityCrudLink<TAdapters, TEntity extends Entity = Entity> {\n /** The owning entity's accessor name, e.g. `'brandId'`. */\n readonly field: string;\n readonly entityConstructor: EntityConstructor<Entity>;\n /**\n * Which adapter holds the **target's** repository. Often a different service\n * than the record's own: `catalog-reference` is another slice's store, so\n * resolving an id goes through that domain's own read path.\n */\n readonly repository: AdapterKey<TAdapters, Context<EntityRepositoryTag>>;\n /** Defaults to `'name'`. */\n readonly labelProperty?: string;\n /** Defaults to `'name'`. Must be `filterable` on the target. */\n readonly searchProperty?: string;\n /**\n * A restriction on what may be picked **for this record**, ANDed into every\n * quick and browse request — `useEntityLinkSource`'s `baseFiltering`, built\n * from the record being edited rather than fixed at factory time.\n *\n * A record-dependent rule is the case it exists for: a parent picker that\n * must not offer the record itself or anything beneath it. That rule needs\n * more than the record — its descendants are other records — which is why\n * this is a **hook** and not a function of the record: it may load what it\n * needs through the host's own adapters, and answer `undefined` until it has.\n *\n * Called on every render of the single view, under the rules of hooks: once\n * per link, unconditionally, with `undefined` while the record loads and\n * throughout a create. `undefined` back means no restriction. Its members\n * must be `filterable` on the target, or the service answers `400`. It\n * narrows the suggestions and nothing else — the service still has to refuse\n * a value the picker would not have offered.\n */\n readonly useBaseFiltering?: (\n record: TEntity | undefined,\n ) => AnyFilterGroup | undefined;\n}\n\n/**\n * A restriction over a picker's target, with the target's type erased — the\n * link names its target only as `EntityConstructor<Entity>`, so a filter typed\n * on the real target would not be assignable. Erased for the reason\n * {@link AnyEntityLinkSourceConfig} is.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyFilterGroup = FilterGroup<any>;\n\n/** The keys of `TAdapters` whose value is assignable to `TValue`. */\nexport type AdapterKey<TAdapters, TValue> = {\n [K in keyof TAdapters]: TAdapters[K] extends TValue ? K : never;\n}[keyof TAdapters];\n\nexport interface EntityCrudOptions<TAdapters, TEntity extends Entity> {\n /** The domain shell's adapters hook, e.g. `useMarketplaceAdminAdapters`. */\n readonly useAdapters: () => TAdapters;\n /** Route prefix for both pages, e.g. `'/catalog/product-brand'`. */\n readonly basePath: string;\n /**\n * The entity's `entity` catalog key. Asserted against `@entity({ key })` at\n * factory time — the two are the same string by convention\n * (`entity:product-brand.label` mirrors `key: 'product-brand'`), and letting\n * them drift would title a form after a different entity.\n */\n readonly catalogKey: EntityCatalogKey;\n /** Which adapter holds this entity's own repository. */\n readonly repository: AdapterKey<TAdapters, Context<EntityRepositoryTag>>;\n /**\n * Members the form keeps but does not show — `id` always, plus anything a\n * transaction assigns. A hidden member still round-trips: it is dropped from\n * the rendered fields, not from the draft, so `reconstructEntity` carries it\n * back out of the seeded values.\n */\n readonly hiddenFields?: readonly string[];\n /** `<EntityColumn>` overrides for the list, for presentation metadata cannot express. */\n readonly columns?: ReactNode;\n /**\n * Extra controls beside the table's own — an `<EntityTableToolbar>`.\n *\n * Its own option rather than more `columns`, though both end up as\n * `EntityTable` children and the slots are sorted by component identity: a\n * toolbar filed under a columns prop is a name that lies, and the first thing\n * to go here is a link into a wizard, which is not a column by any reading.\n */\n readonly toolbar?: ReactNode;\n /**\n * How many rows the list asks for on its first load. Defaults to\n * `useDataLoading`'s own default.\n *\n * Raised for a vocabulary that should be seen whole: `EntityTable` nests a\n * hierarchy only within the page it was given, so a tree larger than one page\n * shows the children whose parent fell on another page as roots.\n */\n readonly pageSize?: number;\n /** Frozen at factory time — see `use-entity-link-sources.ts`. */\n readonly links?: readonly EntityCrudLink<TAdapters, TEntity>[];\n /**\n * Where the entity's served affordances come from — `GET /api/<entity>/$metadata`.\n *\n * Supplying it is what turns on every served affordance:\n * Save and Delete filtered against the caller's real grants, the declared\n * verbs on the form, the row overflow menu, and the bulk bar. Omitting it\n * keeps the pre-0026 behaviour exactly, which is what every generated catalog\n * rendered before this option existed.\n *\n * A `EntityMetadataSource` rather than a URL because the two hosts reach\n * their service differently — one through the config-driven REST adapters,\n * one through a shell's own same-origin routes.\n */\n readonly metadataSource?: EntityMetadataSource;\n /**\n * Which adapter holds this entity's {@link EntityMetadataSource} — the same\n * source as {@link metadataSource}, resolved from the host's composition\n * instead of built by the caller.\n *\n * Prefer it: a source is a transport, and naming it by key keeps the module\n * that generates the screens free of the adapter that fetches, exactly as\n * {@link repository} already does for records. Supplying both is a build\n * error — two answers to where the document comes from.\n */\n readonly metadata?: AdapterKey<TAdapters, EntityMetadataSource>;\n /**\n * Runs a `collection`-bound verb over a selection, and reports **per row**.\n *\n * Supplying it opts the list into the selection column and the bulk bar.\n * It is separate from `metadataSource` because the two are independent: an\n * entity can declare no collection verb and still want permission-filtered\n * Save, and the endpoint a verb posts to is the shell's knowledge, not\n * metadata's.\n */\n readonly runBulkUseCase?: (\n key: string,\n selection: EntitySelection<TEntity>,\n ) => Promise<readonly BulkOutcome[]>;\n /**\n * Runs an `entity`-bound verb on the record the single view is showing.\n *\n * The sibling of {@link runBulkUseCase}, and it had to exist for the same\n * reason: `EntityForm` has rendered these buttons for a long time, and\n * `EntityCrudForm` has accepted an `onUseCase` for as long — but nothing ever\n * passed one, so a generated screen showed a declared, granted, served verb\n * that did nothing when clicked. Measured on `ProductOffering`'s `publish`,\n * which passed every check its host's register ran and appeared nowhere.\n *\n * Resolving means the record changed, and the page reloads it: a verb that\n * moves a lifecycle leaves the form showing the old state otherwise, which\n * reads as \"the button did nothing\". Rejecting surfaces through the form's\n * own error slot, so a `409` from an illegal transition renders as the coded\n * message the catalog holds rather than a thrown promise nobody catches.\n */\n readonly runUseCase?: (key: string, id: EntityId) => Promise<void>;\n}\n\n/**\n * Props both hosts pass. A route host passes none — the slug comes from the URL\n * and a save returns to the list; the workspace tab host passes all of them.\n */\nexport interface EntityCrudSingleViewProps {\n /** Defaults to the `[slug]` route param. */\n readonly slug?: string;\n /** Defaults to navigating back to the list. */\n readonly onSaved?: () => void;\n readonly onDeleted?: () => void;\n /**\n * Where to autosave the edit. Supplying it is the whole opt-in: the form\n * seeds from the persisted draft, writes to it on every edit, and the page\n * clears it once a save or delete commits.\n *\n * A route host omits it and stays ephemeral, which is the rule stated as a\n * missing prop rather than as a flag — there is no value of \"absent\" that\n * accidentally starts persisting.\n */\n readonly draft?: EntityDraftStore;\n}\n\n/**\n * What the factory returns: a **named descriptor**, not four loose components.\n *\n * The identity fields are here so the workspace registry and the nav are derived\n * from a list of these rather than from the hand-written const maps they replace.\n */\nexport interface EntityCrud<TEntity extends Entity> {\n readonly entityConstructor: EntityConstructor<TEntity>;\n /** `@entity({ key })`, which is also `catalogKey` and the tab address payload. */\n readonly entityKey: EntityCatalogKey;\n /**\n * `@entity({ labelKey })` — how one record is named. A record tab's title.\n *\n * Read off the decorator rather than passed, so the tab strip, the nav and the\n * search results all name the entity from the one place it names itself.\n */\n readonly entityLabelKey: string;\n /** `@entity({ pluralKey })` — how the collection is named. A list tab's title. */\n readonly entityPluralKey: string;\n readonly basePath: string;\n readonly ListPage: () => ReactElement;\n readonly SingleViewPage: (props?: EntityCrudSingleViewProps) => ReactElement;\n}\n\n/**\n * A picker's transport with its context tags erased.\n *\n * The factory cannot preserve one type parameter per link — the pages that\n * build these know their adapters, the generated form only forwards them — and\n * `EntityForm.linkSources` is already `Record<string, EntityLinkSource<any>>`\n * for the same reason.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyEntityLinkSourceConfig = EntityLinkSourceConfig<Entity, any>;\n\n/**\n * One picker, resolved: the descriptor computed once at factory time, and the\n * use-cases plus adapter context the page builds per render.\n */\nexport interface EntityCrudLinkSource {\n readonly field: string;\n readonly descriptor: EntityFieldDescriptor;\n readonly config: AnyEntityLinkSourceConfig;\n}\n"],"names":[],"mappings":"AAkTA;;;CAGC,GACD,WAIC"}
@@ -1 +1 @@
1
- {"version":3,"file":"use-crud-render-link.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/use-crud-render-link.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAoB1D;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,UAAU,CAyB/D"}
1
+ {"version":3,"file":"use-crud-render-link.d.ts","sourceRoot":"","sources":["../../../src/lib/crud/use-crud-render-link.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAoB1D;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,UAAU,CAiC/D"}
@@ -24,7 +24,11 @@ import { CATALOG_NEW_SLUG } from './slug.js';
24
24
  href: href,
25
25
  className: className,
26
26
  onClick: (event)=>{
27
- if (host === undefined || !isPlainClick(event)) return;
27
+ // A page of the listing on screen is that listing's own address, so
28
+ // there is nothing for a tab host to open: the link is followed.
29
+ if (host === undefined || !isPlainClick(event) || intent.kind === 'page') {
30
+ return;
31
+ }
28
32
  event.preventDefault();
29
33
  if (intent.kind === 'open') {
30
34
  host.toEntity(entityKey, String(intent.id));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/crud/use-crud-render-link.tsx"],"sourcesContent":["'use client';\n\nimport type { RenderLink } from '@entifix/react-controls';\nimport Link from 'next/link';\nimport { type MouseEvent, useCallback } from 'react';\n\nimport { useEntityNavHost } from '../workspace/entity-nav.js';\nimport { CATALOG_NEW_SLUG } from './slug.js';\n\n/**\n * A click the page may take over: the primary button with no modifier. Anything\n * else — middle-click, ⌘/Ctrl-click, Shift-click — is the visitor asking for the\n * link itself, in a new tab or window, and must be left to the browser.\n */\nconst isPlainClick = (event: MouseEvent<HTMLAnchorElement>): boolean =>\n !event.defaultPrevented &&\n event.button === 0 &&\n !event.metaKey &&\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey;\n\n/**\n * How a generated page renders its Open, New and Back links (#20).\n *\n * A plain anchor was a full document load: the bundle rebuilt, every cache\n * emptied, and inside a workspace tab the click left the workspace for the route\n * page. So every link is `next/link` — a client-side navigation on a route host —\n * and, when a tab host is mounted, a plain click opens the matching tab instead:\n * the record, its create form (`<key>:new`), or the list. The `href` stays real\n * either way, so a modified click still opens the route in a new browser tab.\n */\nexport function useCrudRenderLink(entityKey: string): RenderLink {\n const host = useEntityNavHost();\n\n return useCallback<RenderLink>(\n ({ href, className, children, intent }) => (\n <Link\n href={href}\n className={className}\n onClick={event => {\n if (host === undefined || !isPlainClick(event)) return;\n event.preventDefault();\n if (intent.kind === 'open') {\n host.toEntity(entityKey, String(intent.id));\n } else if (intent.kind === 'new') {\n host.toEntity(entityKey, CATALOG_NEW_SLUG);\n } else {\n host.toList(entityKey);\n }\n }}\n >\n {children}\n </Link>\n ),\n [host, entityKey],\n );\n}\n"],"names":["Link","useCallback","useEntityNavHost","CATALOG_NEW_SLUG","isPlainClick","event","defaultPrevented","button","metaKey","ctrlKey","shiftKey","altKey","useCrudRenderLink","entityKey","host","href","className","children","intent","onClick","undefined","preventDefault","kind","toEntity","String","id","toList"],"mappings":"AAAA;;AAGA,OAAOA,UAAU,YAAY;AAC7B,SAA0BC,WAAW,QAAQ,QAAQ;AAErD,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAASC,gBAAgB,QAAQ,YAAY;AAE7C;;;;CAIC,GACD,MAAMC,eAAe,CAACC,QACpB,CAACA,MAAMC,gBAAgB,IACvBD,MAAME,MAAM,KAAK,KACjB,CAACF,MAAMG,OAAO,IACd,CAACH,MAAMI,OAAO,IACd,CAACJ,MAAMK,QAAQ,IACf,CAACL,MAAMM,MAAM;AAEf;;;;;;;;;CASC,GACD,OAAO,SAASC,kBAAkBC,SAAiB;IACjD,MAAMC,OAAOZ;IAEb,OAAOD,YACL,CAAC,EAAEc,IAAI,EAAEC,SAAS,EAAEC,QAAQ,EAAEC,MAAM,EAAE,iBACpC,KAAClB;YACCe,MAAMA;YACNC,WAAWA;YACXG,SAASd,CAAAA;gBACP,IAAIS,SAASM,aAAa,CAAChB,aAAaC,QAAQ;gBAChDA,MAAMgB,cAAc;gBACpB,IAAIH,OAAOI,IAAI,KAAK,QAAQ;oBAC1BR,KAAKS,QAAQ,CAACV,WAAWW,OAAON,OAAOO,EAAE;gBAC3C,OAAO,IAAIP,OAAOI,IAAI,KAAK,OAAO;oBAChCR,KAAKS,QAAQ,CAACV,WAAWV;gBAC3B,OAAO;oBACLW,KAAKY,MAAM,CAACb;gBACd;YACF;sBAECI;YAGL;QAACH;QAAMD;KAAU;AAErB"}
1
+ {"version":3,"sources":["../../../src/lib/crud/use-crud-render-link.tsx"],"sourcesContent":["'use client';\n\nimport type { RenderLink } from '@entifix/react-controls';\nimport Link from 'next/link';\nimport { type MouseEvent, useCallback } from 'react';\n\nimport { useEntityNavHost } from '../workspace/entity-nav.js';\nimport { CATALOG_NEW_SLUG } from './slug.js';\n\n/**\n * A click the page may take over: the primary button with no modifier. Anything\n * else — middle-click, ⌘/Ctrl-click, Shift-click — is the visitor asking for the\n * link itself, in a new tab or window, and must be left to the browser.\n */\nconst isPlainClick = (event: MouseEvent<HTMLAnchorElement>): boolean =>\n !event.defaultPrevented &&\n event.button === 0 &&\n !event.metaKey &&\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey;\n\n/**\n * How a generated page renders its Open, New and Back links (#20).\n *\n * A plain anchor was a full document load: the bundle rebuilt, every cache\n * emptied, and inside a workspace tab the click left the workspace for the route\n * page. So every link is `next/link` — a client-side navigation on a route host —\n * and, when a tab host is mounted, a plain click opens the matching tab instead:\n * the record, its create form (`<key>:new`), or the list. The `href` stays real\n * either way, so a modified click still opens the route in a new browser tab.\n */\nexport function useCrudRenderLink(entityKey: string): RenderLink {\n const host = useEntityNavHost();\n\n return useCallback<RenderLink>(\n ({ href, className, children, intent }) => (\n <Link\n href={href}\n className={className}\n onClick={event => {\n // A page of the listing on screen is that listing's own address, so\n // there is nothing for a tab host to open: the link is followed.\n if (\n host === undefined ||\n !isPlainClick(event) ||\n intent.kind === 'page'\n ) {\n return;\n }\n event.preventDefault();\n if (intent.kind === 'open') {\n host.toEntity(entityKey, String(intent.id));\n } else if (intent.kind === 'new') {\n host.toEntity(entityKey, CATALOG_NEW_SLUG);\n } else {\n host.toList(entityKey);\n }\n }}\n >\n {children}\n </Link>\n ),\n [host, entityKey],\n );\n}\n"],"names":["Link","useCallback","useEntityNavHost","CATALOG_NEW_SLUG","isPlainClick","event","defaultPrevented","button","metaKey","ctrlKey","shiftKey","altKey","useCrudRenderLink","entityKey","host","href","className","children","intent","onClick","undefined","kind","preventDefault","toEntity","String","id","toList"],"mappings":"AAAA;;AAGA,OAAOA,UAAU,YAAY;AAC7B,SAA0BC,WAAW,QAAQ,QAAQ;AAErD,SAASC,gBAAgB,QAAQ,6BAA6B;AAC9D,SAASC,gBAAgB,QAAQ,YAAY;AAE7C;;;;CAIC,GACD,MAAMC,eAAe,CAACC,QACpB,CAACA,MAAMC,gBAAgB,IACvBD,MAAME,MAAM,KAAK,KACjB,CAACF,MAAMG,OAAO,IACd,CAACH,MAAMI,OAAO,IACd,CAACJ,MAAMK,QAAQ,IACf,CAACL,MAAMM,MAAM;AAEf;;;;;;;;;CASC,GACD,OAAO,SAASC,kBAAkBC,SAAiB;IACjD,MAAMC,OAAOZ;IAEb,OAAOD,YACL,CAAC,EAAEc,IAAI,EAAEC,SAAS,EAAEC,QAAQ,EAAEC,MAAM,EAAE,iBACpC,KAAClB;YACCe,MAAMA;YACNC,WAAWA;YACXG,SAASd,CAAAA;gBACP,oEAAoE;gBACpE,iEAAiE;gBACjE,IACES,SAASM,aACT,CAAChB,aAAaC,UACda,OAAOG,IAAI,KAAK,QAChB;oBACA;gBACF;gBACAhB,MAAMiB,cAAc;gBACpB,IAAIJ,OAAOG,IAAI,KAAK,QAAQ;oBAC1BP,KAAKS,QAAQ,CAACV,WAAWW,OAAON,OAAOO,EAAE;gBAC3C,OAAO,IAAIP,OAAOG,IAAI,KAAK,OAAO;oBAChCP,KAAKS,QAAQ,CAACV,WAAWV;gBAC3B,OAAO;oBACLW,KAAKY,MAAM,CAACb;gBACd;YACF;sBAECI;YAGL;QAACH;QAAMD;KAAU;AAErB"}
package/package.json CHANGED
@@ -21,7 +21,7 @@
21
21
  }
22
22
  }
23
23
  },
24
- "version": "0.6.0",
24
+ "version": "0.7.1",
25
25
  "description": "Next.js application shell: back-office chrome, workspace tabs, CRUD screens derived from entity metadata, and session and proxy routes.",
26
26
  "license": "MIT",
27
27
  "repository": {
@@ -57,17 +57,17 @@
57
57
  "react": "19.3.1",
58
58
  "react-dom": "19.3.1",
59
59
  "zustand": "^5.0.15",
60
- "@entifix/testing-unit": "0.6.0"
60
+ "@entifix/testing-unit": "0.7.1"
61
61
  },
62
62
  "dependencies": {
63
63
  "idb": "^8.0.4",
64
- "@entifix/authz": "0.6.0",
65
- "@entifix/business": "0.6.0",
66
- "@entifix/i18n": "0.6.0",
67
- "@entifix/core": "0.6.0",
68
- "@entifix/react-integration": "0.6.0",
69
- "@entifix/transactions": "0.6.0",
70
- "@entifix/react-controls": "0.6.0"
64
+ "@entifix/core": "0.7.1",
65
+ "@entifix/react-controls": "0.7.1",
66
+ "@entifix/i18n": "0.7.1",
67
+ "@entifix/transactions": "0.7.1",
68
+ "@entifix/authz": "0.7.1",
69
+ "@entifix/react-integration": "0.7.1",
70
+ "@entifix/business": "0.7.1"
71
71
  },
72
72
  "files": [
73
73
  "dist",