@entifix/next-shell 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/lib/config/service-proxy-route.d.ts +4 -7
  2. package/dist/lib/config/service-proxy-route.d.ts.map +1 -1
  3. package/dist/lib/config/service-proxy-route.js +1 -25
  4. package/dist/lib/config/service-proxy-route.js.map +1 -1
  5. package/dist/lib/crud/entity-crud-form.d.ts +5 -3
  6. package/dist/lib/crud/entity-crud-form.d.ts.map +1 -1
  7. package/dist/lib/crud/entity-crud-form.js +2 -1
  8. package/dist/lib/crud/entity-crud-form.js.map +1 -1
  9. package/dist/lib/crud/index.d.ts +0 -1
  10. package/dist/lib/crud/index.d.ts.map +1 -1
  11. package/dist/lib/crud/index.js +0 -1
  12. package/dist/lib/crud/index.js.map +1 -1
  13. package/dist/lib/crud/make-entity-crud.d.ts +7 -12
  14. package/dist/lib/crud/make-entity-crud.d.ts.map +1 -1
  15. package/dist/lib/crud/make-entity-crud.js +154 -114
  16. package/dist/lib/crud/make-entity-crud.js.map +1 -1
  17. package/dist/lib/crud/make-entity-crud.types.d.ts +13 -1
  18. package/dist/lib/crud/make-entity-crud.types.d.ts.map +1 -1
  19. package/dist/lib/crud/make-entity-crud.types.js.map +1 -1
  20. package/dist/lib/session/bearer.d.ts +1 -1
  21. package/dist/lib/session/bearer.js +1 -1
  22. package/dist/lib/session/bearer.js.map +1 -1
  23. package/dist/lib/workspace/index.d.ts +1 -2
  24. package/dist/lib/workspace/index.d.ts.map +1 -1
  25. package/dist/lib/workspace/index.js +1 -2
  26. package/dist/lib/workspace/index.js.map +1 -1
  27. package/dist/lib/workspace/pending-flows.d.ts +48 -0
  28. package/dist/lib/workspace/pending-flows.d.ts.map +1 -0
  29. package/dist/lib/workspace/pending-flows.js +60 -0
  30. package/dist/lib/workspace/pending-flows.js.map +1 -0
  31. package/package.json +11 -11
  32. package/dist/lib/crud/hand-off-write.d.ts +0 -35
  33. package/dist/lib/crud/hand-off-write.d.ts.map +0 -1
  34. package/dist/lib/crud/hand-off-write.js +0 -27
  35. package/dist/lib/crud/hand-off-write.js.map +0 -1
  36. package/dist/lib/crud/pending-notice.d.ts +0 -31
  37. package/dist/lib/crud/pending-notice.d.ts.map +0 -1
  38. package/dist/lib/crud/pending-notice.js +0 -72
  39. package/dist/lib/crud/pending-notice.js.map +0 -1
  40. package/dist/lib/workspace/pending-state.d.ts +0 -85
  41. package/dist/lib/workspace/pending-state.d.ts.map +0 -1
  42. package/dist/lib/workspace/pending-state.js +0 -155
  43. package/dist/lib/workspace/pending-state.js.map +0 -1
  44. package/dist/lib/workspace/pending-transactions.d.ts +0 -44
  45. package/dist/lib/workspace/pending-transactions.d.ts.map +0 -1
  46. package/dist/lib/workspace/pending-transactions.js +0 -114
  47. package/dist/lib/workspace/pending-transactions.js.map +0 -1
@@ -1,35 +1,31 @@
1
1
  'use client';
2
2
  import { _ as _extends } from "@swc/helpers/_/_extends";
3
3
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
4
- import { deleteUCFactory, getUCFactory, loadUCFactory, saveUCFactory } from '@entifix/business';
5
- import { describeEntityColumns, envelopeEntityName, extractMetaEntity, Internal } from '@entifix/core';
4
+ import { deleteUCFactory, EntityIdTag, EntityTag, getUCFactory, loadUCFactory, saveUCFactory } from '@entifix/business';
5
+ import { describeEntityColumns, envelopeEntityName, extractMetaEntity, Internal, isFailure, settled } from '@entifix/core';
6
6
  import { EntityTable, useCasesForSurface } from '@entifix/react-controls';
7
- import { entityQueryScope, useDataLoading, useEntityMutation, useEntityRecord } from '@entifix/react-integration';
8
- import { TransactionSinkTag } from '@entifix/transactions';
7
+ import { entityQueryScope, useDataLoading, useEntityRecord, useOptimisticMutation } from '@entifix/react-integration';
9
8
  import { useQueryClient } from '@tanstack/react-query';
10
9
  import { Cause, Context, Effect, Exit } from 'effect';
11
10
  import { useParams, useRouter } from 'next/navigation';
12
- import { useState } from 'react';
11
+ import { useEffect, useRef } from 'react';
13
12
  import { useLocaleHref } from '../i18n/index.js';
14
13
  import { useEntityNavHost } from '../workspace/entity-nav.js';
15
- import { pendingFor, pendingRecordsFor, usePendingTransactions } from '../workspace/pending-transactions.js';
16
14
  import { EntityCrudForm } from './entity-crud-form.js';
17
- import { handOffWrite } from './hand-off-write.js';
18
- import { PendingNotice } from './pending-notice.js';
19
15
  import { CATALOG_NEW_SLUG, slugToEntityId } from './slug.js';
20
16
  import { useCrudRenderLink } from './use-crud-render-link.js';
21
17
  import { useEntityAffordances } from './use-entity-affordances.js';
22
18
  import { useEntityBulk } from './use-entity-bulk.js';
23
19
  /** What a picker defaults to reading off its target. */ const TARGET_NAME_PROPERTY = 'name';
24
20
  /**
25
- * Adds the pending-write sink to one repository adapter, giving the context the
26
- * use-cases run against.
21
+ * One repository adapter, by its key, as the context the use-cases run
22
+ * against.
27
23
  *
28
24
  * The cast is the price of naming adapters by key: `AdapterKey` narrows which
29
25
  * names may be *offered*, but TypeScript will not carry that narrowing through
30
26
  * an index access on a generic record.
31
- */ export function mergeCrudContext(adapters, repository, sink) {
32
- return Context.add(adapters[repository], TransactionSinkTag, sink);
27
+ */ export function crudContextOf(adapters, repository) {
28
+ return adapters[repository];
33
29
  }
34
30
  /**
35
31
  * Builds the list page and the single-record page for one entity.
@@ -51,32 +47,71 @@ import { useEntityBulk } from './use-entity-bulk.js';
51
47
  * with the code, so making this spec-driven would trade type safety for nothing;
52
48
  * a vendor-authored `EntitySpecification` renders through a separate path.
53
49
  */ /**
54
- * A rejected verb, as something the form's error slot can render.
50
+ * A rejected write, as something the form's error slot can render.
55
51
  *
56
52
  * A typed failure is kept as it is: `useErrorMessage` translates its own code,
57
- * a business refusal and an outage alike, and the failure toast that tells
58
- * them apart arrives with the optimistic API. Anything else that carries a
59
- * message keeps it rather than being relabelled with a code it never had; a
60
- * thrown value with no message at all is `Internal`.
53
+ * a business refusal and an outage alike. Anything else is a bug that reached
54
+ * the screen, and is shown as `Internal` — never with its own text, which
55
+ * nobody wrote for a user.
61
56
  */ function asFailure(failure) {
62
- // A typed failure is an `Error` too — Effect's tagged errors extend it — so
63
- // one check keeps both it and a legacy error carrying its own message.
64
- return failure instanceof Error ? failure : new Internal();
57
+ return isFailure(failure) ? failure : new Internal();
65
58
  }
66
59
  /**
67
- * A runner's verbs as the promises the screens await, looked up by the key the
68
- * served `$metadata` named. A rejection carries the failure itself, so the
69
- * screen shows its coded message.
60
+ * What a write failed with *synchronously* — before any flow took it — or
61
+ * `undefined`. A flow's own failure is toasted by the `PendingFlowsProvider`
62
+ * that settles it, so showing it in the error slot too would tell the operator
63
+ * twice.
64
+ */ function syncFailure(mutation) {
65
+ return mutation.status === 'failed' && mutation.flowId === undefined ? asFailure(mutation.failure) : undefined;
66
+ }
67
+ /**
68
+ * A runner's verbs, looked up by the key the served `$metadata` named. A
69
+ * single verb answers either settle mode, so it is run through the optimistic
70
+ * API; a bulk run reports per row and is awaited as a promise whose rejection
71
+ * carries the failure itself.
70
72
  */ function verbsOf(runner, served) {
71
73
  if (runner === undefined) return undefined;
72
- const settle = (effect)=>Effect.runPromiseExit(effect).then((exit)=>Exit.isSuccess(exit) ? exit.value : Promise.reject(Cause.squash(exit.cause)));
73
74
  // The key always comes from the served document, so it names a verb in it.
74
75
  const descriptor = (key)=>served == null ? void 0 : served.find((candidate)=>candidate.key === key);
75
76
  return {
76
- run: (key, id)=>settle(runner.run(descriptor(key), id)),
77
- bulk: (key, selection)=>settle(runner.bulk(descriptor(key), selection))
77
+ run: (key, id)=>runner.run(descriptor(key), id),
78
+ bulk: (key, selection)=>Effect.runPromiseExit(runner.bulk(descriptor(key), selection)).then((exit)=>Exit.isSuccess(exit) ? exit.value : Promise.reject(Cause.squash(exit.cause)))
78
79
  };
79
80
  }
81
+ /**
82
+ * One verb on one record, through the optimistic API: `done` runs once the
83
+ * verb took effect — at once when it settled, or when the flow it was handed
84
+ * to completed.
85
+ */ function useVerb(verbs, done) {
86
+ const verb = useOptimisticMutation({
87
+ // Only ever sent from a handler that exists because `verbs` does.
88
+ write: ({ key, id })=>verbs.run(key, id),
89
+ confirm: done
90
+ });
91
+ const run = (key, id)=>{
92
+ void verb.mutate({
93
+ key,
94
+ id
95
+ }).then((result)=>{
96
+ if (result._tag === 'settled') done();
97
+ }, // Shown through `syncFailure`, from the mutation's own state.
98
+ ()=>undefined);
99
+ };
100
+ return {
101
+ verb,
102
+ run
103
+ };
104
+ }
105
+ /** Whether the component is still mounted: a flow can settle after it left. */ function useMounted() {
106
+ const mounted = useRef(true);
107
+ useEffect(()=>{
108
+ mounted.current = true;
109
+ return ()=>{
110
+ mounted.current = false;
111
+ };
112
+ }, []);
113
+ return mounted;
114
+ }
80
115
  /**
81
116
  * Runs each link's `useBaseFiltering` against the record being edited, in link
82
117
  * order, with `undefined` for a link that declares none.
@@ -89,7 +124,7 @@ import { useEntityBulk } from './use-entity-bulk.js';
89
124
  return links.map((link)=>link.useBaseFiltering == null ? void 0 : link.useBaseFiltering.call(link, record));
90
125
  }
91
126
  export function makeEntityCrud(entityConstructor, options) {
92
- const { useAdapters, basePath, catalogKey, repository, hiddenFields = [], columns, toolbar, pageSize, links = [], metadataSource: givenMetadataSource, metadata, useCases } = options;
127
+ const { useAdapters, basePath, catalogKey, repository, hiddenFields = [], columns, toolbar, pageSize, links = [], metadataSource: givenMetadataSource, metadata, useCases, write } = options;
93
128
  if (givenMetadataSource !== undefined && metadata !== undefined) {
94
129
  throw new Error(`${entityConstructor.name} was given both metadataSource and metadata; pass one`);
95
130
  }
@@ -114,9 +149,9 @@ export function makeEntityCrud(entityConstructor, options) {
114
149
  // depends on the record being edited. `linkLabelProperty`/`linkSearchProperty`
115
150
  // are overridden here because a scalar foreign key's `@accessor()` cannot name
116
151
  // the target's members — it may not import the target at all.
117
- // The wire name, which is also what a pending entry records and what
118
- // `entityQueryScopeFor` keys on — one derivation, so a notice and an
119
- // invalidation can never disagree about which entity they mean.
152
+ // The wire name, which is also what a pending flow's intent records and what
153
+ // `entityQueryScopeFor` keys on — one derivation, so the two can never
154
+ // disagree about which entity they mean.
120
155
  const entityName = envelopeEntityName(entityConstructor);
121
156
  const descriptors = describeEntityColumns(entityConstructor);
122
157
  const linkPlans = links.map((link)=>{
@@ -133,11 +168,9 @@ export function makeEntityCrud(entityConstructor, options) {
133
168
  });
134
169
  });
135
170
  function ListPage() {
171
+ var _syncFailure;
136
172
  var _affordances_metadata, _affordances_metadata1, _affordances_metadata2;
137
173
  const adapters = useAdapters();
138
- // Outside a `PendingTransactionsProvider` this watches nothing, so a host
139
- // that has not mounted one behaves exactly as it did before.
140
- const pending = usePendingTransactions();
141
174
  // Every internal href carries the locale. An unprefixed one still resolves —
142
175
  // the middleware redirects it — but the visitor pays a round trip per click.
143
176
  const withLocale = useLocaleHref();
@@ -146,13 +179,9 @@ export function makeEntityCrud(entityConstructor, options) {
146
179
  const metadataSource = metadataSourceOf(adapters);
147
180
  const affordances = useEntityAffordances(entityConstructor, metadataSource);
148
181
  const renderLink = useCrudRenderLink(catalogKey);
149
- // Records this browser has created but the service has not finished
150
- // writing. Prepended below rather than patched into the cache, which a
151
- // refetch would undo.
152
- const optimistic = pendingRecordsFor(pending, entityName);
153
182
  const pager = useDataLoading(_extends({
154
183
  uc: loadUCFactory(),
155
- ctx: mergeCrudContext(adapters, repository, pending),
184
+ ctx: crudContextOf(adapters, repository),
156
185
  // Scoped rather than left to the per-instance fallback, which is correct
157
186
  // but unshared: with the entity's own scope one invalidation refreshes
158
187
  // every page and filter of it, which is what a bulk run needs — and it is
@@ -194,10 +223,14 @@ export function makeEntityCrud(entityConstructor, options) {
194
223
  //
195
224
  // ⚠️ **A row verb and the form's are the same runner with different
196
225
  // arguments.** `EntityTable` hands back the whole record, because that is
197
- // what it has; the runner takes an id, because that is what a route needs
226
+ // what it has; the runner takes an id, because that is what a route needs.
198
227
  // The list has no error slot of its own, so a failure lands in the
199
228
  // table's own error region — the same one a failed page read uses.
200
- const [useCaseError, setUseCaseError] = useState(undefined);
229
+ const rowVerb = useVerb(verbs, ()=>{
230
+ void queryClient.invalidateQueries({
231
+ queryKey: scope
232
+ });
233
+ });
201
234
  // Called unconditionally and the *result* gated, the way the surfaces are
202
235
  // read in `EntityForm`: the name begins with `use`, so short-circuiting it
203
236
  // reads to `react-hooks/rules-of-hooks` as a conditional hook.
@@ -205,38 +238,26 @@ export function makeEntityCrud(entityConstructor, options) {
205
238
  const canRunRowUseCase = verbs !== undefined && rowUseCases.length > 0;
206
239
  const handleRowUseCase = canRunRowUseCase ? (key, item)=>{
207
240
  if (item.id == null) return;
208
- setUseCaseError(undefined);
209
- void (verbs == null ? void 0 : verbs.run(key, item.id).then(()=>queryClient.invalidateQueries({
210
- queryKey: scope
211
- }), (failure)=>setUseCaseError(asFailure(failure))));
241
+ rowVerb.run(key, item.id);
212
242
  } : undefined;
213
- return /*#__PURE__*/ _jsxs("div", {
243
+ return /*#__PURE__*/ _jsx("div", {
214
244
  className: "flex flex-col gap-s",
215
- children: [
216
- /*#__PURE__*/ _jsx(PendingNotice, {
217
- entries: pendingFor(pending, entityName),
218
- onDismiss: pending.dismiss
219
- }),
220
- /*#__PURE__*/ _jsxs(EntityTable, _extends({
221
- entityConstructor: entityConstructor
222
- }, pager, {
223
- items: [
224
- ...optimistic,
225
- ...pager.items
226
- ],
227
- totalItems: pager.totalItems + optimistic.length,
228
- hrefFor: (id)=>withLocale(`${basePath}/${String(id)}`),
229
- newHref: withLocale(`${basePath}/${CATALOG_NEW_SLUG}`),
230
- renderLink: renderLink
231
- }, affordances, bulk.tableProps, {
232
- onUseCase: handleRowUseCase,
233
- error: useCaseError != null ? useCaseError : pager.error,
234
- children: [
235
- columns,
236
- toolbar
237
- ]
238
- }))
239
- ]
245
+ children: /*#__PURE__*/ _jsxs(EntityTable, _extends({
246
+ entityConstructor: entityConstructor
247
+ }, pager, {
248
+ items: pager.items,
249
+ totalItems: pager.totalItems,
250
+ hrefFor: (id)=>withLocale(`${basePath}/${String(id)}`),
251
+ newHref: withLocale(`${basePath}/${CATALOG_NEW_SLUG}`),
252
+ renderLink: renderLink
253
+ }, affordances, bulk.tableProps, {
254
+ onUseCase: handleRowUseCase,
255
+ error: (_syncFailure = syncFailure(rowVerb.verb)) != null ? _syncFailure : pager.error,
256
+ children: [
257
+ columns,
258
+ toolbar
259
+ ]
260
+ }))
240
261
  });
241
262
  }
242
263
  /**
@@ -244,32 +265,24 @@ export function makeEntityCrud(entityConstructor, options) {
244
265
  * on save; in a workspace tab it takes the slug and the post-save action as
245
266
  * props.
246
267
  */ function SingleViewPage({ slug, onSaved, onDeleted, draft } = {}) {
247
- var _ref, _ref1;
268
+ var _ref, _ref1, _ref2;
248
269
  var _affordances_metadata;
249
270
  const adapters = useAdapters();
250
271
  const metadataSource = metadataSourceOf(adapters);
251
272
  // The same served document the form reads its buttons from, so a key the
252
273
  // form hands back always names a verb in it.
253
274
  const affordances = useEntityAffordances(entityConstructor, metadataSource);
254
- const pending = usePendingTransactions();
255
275
  const router = useRouter();
256
276
  const withLocale = useLocaleHref();
257
277
  const params = useParams();
258
- // A verb's failure is this page's, not the record fetch's or the mutation's,
259
- // so it needs a slot of its own to reach the form's error area.
260
- const [useCaseError, setUseCaseError] = useState(undefined);
278
+ const mounted = useMounted();
261
279
  const id = slugToEntityId(slug != null ? slug : params.slug);
262
- const ctx = mergeCrudContext(adapters, repository, pending);
280
+ const ctx = crudContextOf(adapters, repository);
263
281
  const { entity, isLoading, error: loadError, reload } = useEntityRecord({
264
282
  uc: getUCFactory(),
265
283
  ctx,
266
284
  id
267
285
  });
268
- const { save, remove, isSaving, isDeleting, error: writeError } = useEntityMutation({
269
- saveUc: saveUCFactory(),
270
- deleteUc: deleteUCFactory(),
271
- ctx
272
- });
273
286
  // Against the record as loaded, not the draft: the rule is about which
274
287
  // record this is, not what the operator has typed into it.
275
288
  const linkFilters = useLinkFilters(linkPlans, entity);
@@ -283,7 +296,7 @@ export function makeEntityCrud(entityConstructor, options) {
283
296
  entityConstructor: plan.entityConstructor,
284
297
  loadUc: loadUCFactory(),
285
298
  getUc: getUCFactory(),
286
- ctx: mergeCrudContext(adapters, plan.repository, pending),
299
+ ctx: crudContextOf(adapters, plan.repository),
287
300
  // The config's target is erased to `Entity`, and the host's filter to
288
301
  // `any`; the two meet here, where neither type is the real target's.
289
302
  baseFiltering: linkFilters[index]
@@ -295,9 +308,8 @@ export function makeEntityCrud(entityConstructor, options) {
295
308
  const renderLink = useCrudRenderLink(catalogKey);
296
309
  const queryClient = useQueryClient();
297
310
  // The list this page returns to has its page cached, and it is no longer
298
- // true. Invalidated rather than patched, for the reason `handOffWrite`
299
- // gives: a transactional create is not in the service yet, and the pending
300
- // set, not the cache, is what keeps it visible until it is.
311
+ // true. Invalidated rather than patched: the service is the authority on
312
+ // the row it stored.
301
313
  //
302
314
  // ⚠️ Invisible while every Open was a document load, which threw the cache
303
315
  // away anyway (#20): the first client-side navigation back to the list
@@ -308,38 +320,63 @@ export function makeEntityCrud(entityConstructor, options) {
308
320
  const toList = ()=>host === undefined ? router.push(withLocale(basePath)) : host.toList(catalogKey);
309
321
  const afterSave = onSaved != null ? onSaved : toList;
310
322
  const afterDelete = onDeleted != null ? onDeleted : toList;
323
+ // Through the host's writer when it named one, which answers both settle
324
+ // modes; otherwise through the repository, where every write settles.
325
+ const writer = write === undefined ? undefined : adapters[write];
311
326
  // The draft is spent once the write *commits*, and only here is that known:
312
327
  // `useEntityForm` neither fetches nor saves, so it cannot clear its own.
313
- // A failed mutation deliberately keeps the draft — the edit is still the
314
- // user's only copy of what they typed.
328
+ // A failed write — or a failed flow — deliberately keeps the draft and the
329
+ // form: the edit is still the user's only copy of what they typed.
330
+ //
331
+ // ⚠️ A flow can complete after the operator left this page, so leaving it
332
+ // is guarded on still being here: a navigation from a form nobody is
333
+ // looking at would pull them away from wherever they went.
334
+ const saveMutation = useOptimisticMutation({
335
+ write: (next)=>writer === undefined ? Effect.map(Effect.provide(saveUCFactory(), ctx.pipe(Context.add(EntityTag, next))), settled) : writer.save(next),
336
+ intent: ()=>({
337
+ entity: entityName,
338
+ write: 'save'
339
+ }),
340
+ confirm: ()=>{
341
+ draft == null ? void 0 : draft.clear();
342
+ void refreshList();
343
+ if (mounted.current) afterSave();
344
+ }
345
+ });
346
+ const deleteMutation = useOptimisticMutation({
347
+ write: (target)=>writer === undefined ? Effect.as(Effect.provide(deleteUCFactory(), ctx.pipe(Context.add(EntityIdTag, target))), settled(undefined)) : writer.delete(target),
348
+ intent: ()=>({
349
+ entity: entityName,
350
+ write: 'delete'
351
+ }),
352
+ confirm: ()=>{
353
+ draft == null ? void 0 : draft.clear();
354
+ void refreshList();
355
+ if (mounted.current) afterDelete();
356
+ }
357
+ });
315
358
  const handleSave = async (next)=>{
316
- const saved = await save(next);
317
- if (saved === undefined) return;
318
- // ⚠️ Deliberately *not* a `setQueriesData` patch. The list refetches on
319
- // mount — precisely when the operator arrives, having just been navigated
320
- // here — and the server legitimately does not hold the record yet, so the
321
- // refetch would replace the patched page and the row would vanish a
322
- // moment after appearing. The pending set outlives refetches.
323
- handOffWrite({
324
- id: String(saved.id),
325
- record: saved,
326
- pending,
327
- draft
328
- });
359
+ const result = await saveMutation.mutate(next).catch(()=>undefined);
360
+ // Failed, or pending: the form stays, and the mutation says which. A
361
+ // pending write leaves through the mutation's `confirm`, once its flow
362
+ // completed.
363
+ if ((result == null ? void 0 : result._tag) !== 'settled') return;
364
+ draft == null ? void 0 : draft.clear();
329
365
  void refreshList();
330
366
  afterSave();
331
367
  };
332
368
  const handleDelete = async ()=>{
333
- if (await remove(id)) {
334
- draft == null ? void 0 : draft.clear();
335
- void refreshList();
336
- afterDelete();
337
- }
369
+ const result = await deleteMutation.mutate(id).catch(()=>undefined);
370
+ if ((result == null ? void 0 : result._tag) !== 'settled') return;
371
+ draft == null ? void 0 : draft.clear();
372
+ void refreshList();
373
+ afterDelete();
338
374
  };
339
375
  /**
340
376
  * An `entity`-bound verb, on the record being shown.
341
377
  *
342
- * It **reloads** rather than patching what it has: the service decides the
378
+ * It **reloads** — once the verb took effect, which for one the server
379
+ * handed to a flow is when the flow completed — rather than patching what it has: the service decides the
343
380
  * resulting state — a `publish` may land on `published` from four different
344
381
  * places — and a client that assumed the new value would show the wrong one
345
382
  * the first time the rule changed. `id == null` means the create form,
@@ -352,10 +389,8 @@ export function makeEntityCrud(entityConstructor, options) {
352
389
  * the record correctly did not move, and the operator saw a button that
353
390
  * appeared to do nothing at all.
354
391
  */ const verbs = verbsOf(useCases === undefined ? undefined : adapters[useCases], (_affordances_metadata = affordances.metadata) == null ? void 0 : _affordances_metadata.useCases);
355
- const handleUseCase = verbs === undefined || id == null ? undefined : (key)=>{
356
- setUseCaseError(undefined);
357
- void verbs.run(key, id).then(()=>reload(), (failure)=>setUseCaseError(asFailure(failure)));
358
- };
392
+ const recordVerb = useVerb(verbs, ()=>void reload());
393
+ const handleUseCase = verbs === undefined || id == null ? undefined : (key)=>recordVerb.run(key, id);
359
394
  return /*#__PURE__*/ _jsx(EntityCrudForm, {
360
395
  entityConstructor: entityConstructor,
361
396
  catalogKey: catalogKey,
@@ -364,16 +399,21 @@ export function makeEntityCrud(entityConstructor, options) {
364
399
  links: linkSources,
365
400
  entity: entity,
366
401
  isLoading: isLoading,
367
- isSaving: isSaving,
368
- isDeleting: isDeleting,
369
- error: (_ref = loadError != null ? loadError : writeError) != null ? _ref : useCaseError,
402
+ isSaving: saveMutation.status === 'running',
403
+ isPending: [
404
+ saveMutation,
405
+ deleteMutation,
406
+ recordVerb.verb
407
+ ].some((mutation)=>mutation.status === 'pending'),
408
+ isDeleting: deleteMutation.status === 'running',
409
+ error: (_ref = (_ref1 = loadError != null ? loadError : syncFailure(saveMutation)) != null ? _ref1 : syncFailure(deleteMutation)) != null ? _ref : syncFailure(recordVerb.verb),
370
410
  onSave: handleSave,
371
411
  onDelete: id == null ? undefined : handleDelete,
372
412
  onUseCase: handleUseCase,
373
413
  backHref: withLocale(basePath),
374
414
  renderLink: renderLink,
375
415
  draft: draft
376
- }, String((_ref1 = entity == null ? void 0 : entity.id) != null ? _ref1 : CATALOG_NEW_SLUG));
416
+ }, String((_ref2 = entity == null ? void 0 : entity.id) != null ? _ref2 : CATALOG_NEW_SLUG));
377
417
  }
378
418
  return {
379
419
  entityConstructor,
@@ -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 type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityMetadataSource,\n type EntitySelection,\n type EntityUseCaseRunner,\n envelopeEntityName,\n extractMetaEntity,\n type FilterGroup,\n Internal,\n type TransitionalFailure,\n type UseCaseDescriptor,\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 { Cause, Context, Effect, Exit } 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 * A typed failure is kept as it is: `useErrorMessage` translates its own code,\n * a business refusal and an outage alike, and the failure toast that tells\n * them apart arrives with the optimistic API. Anything else that carries a\n * message keeps it rather than being relabelled with a code it never had; a\n * thrown value with no message at all is `Internal`.\n */\nfunction asFailure(failure: unknown): TransitionalFailure {\n // A typed failure is an `Error` too — Effect's tagged errors extend it — so\n // one check keeps both it and a legacy error carrying its own message.\n return failure instanceof Error\n ? (failure as TransitionalFailure)\n : new Internal();\n}\n\n/**\n * A runner's verbs as the promises the screens await, looked up by the key the\n * served `$metadata` named. A rejection carries the failure itself, so the\n * screen shows its coded message.\n */\nfunction verbsOf(\n runner: EntityUseCaseRunner | undefined,\n served: readonly UseCaseDescriptor[] | undefined,\n) {\n if (runner === undefined) return undefined;\n const settle = <A,>(effect: Effect.Effect<A, unknown>): Promise<A> =>\n Effect.runPromiseExit(effect).then(exit =>\n Exit.isSuccess(exit)\n ? exit.value\n : Promise.reject(Cause.squash(exit.cause)),\n );\n // The key always comes from the served document, so it names a verb in it.\n const descriptor = (key: string) =>\n served?.find(candidate => candidate.key === key) as UseCaseDescriptor;\n return {\n run: (key: string, id: EntityId) => settle(runner.run(descriptor(key), id)),\n bulk: (key: string, selection: EntitySelection<Entity>) =>\n settle(runner.bulk(descriptor(key), selection)),\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 useCases,\n } = options;\n\n if (givenMetadataSource !== undefined && metadata !== undefined) {\n throw new Error(\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 Error(\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 Error(\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 Error(\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 verbs = verbsOf(\n useCases === undefined\n ? undefined\n : (adapters[useCases] as EntityUseCaseRunner),\n affordances.metadata?.useCases,\n );\n\n const bulk = useEntityBulk<TEntity>({\n run:\n canRunBulk && verbs !== undefined\n ? (key, selection) =>\n verbs.bulk(key, selection as EntitySelection<Entity>)\n : 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; the runner 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<\n TransitionalFailure | undefined\n >(undefined);\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 = verbs !== 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 verbs?.run(key, item.id).then(\n () => queryClient.invalidateQueries({ queryKey: scope }),\n (failure: unknown) => setUseCaseError(asFailure(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 // The same served document the form reads its buttons from, so a key the\n // form hands back always names a verb in it.\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\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<\n TransitionalFailure | undefined\n >(undefined);\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 verbs = verbsOf(\n useCases === undefined\n ? undefined\n : (adapters[useCases] as EntityUseCaseRunner),\n affordances.metadata?.useCases,\n );\n const handleUseCase =\n verbs === undefined || id == null\n ? undefined\n : (key: string) => {\n setUseCaseError(undefined);\n void verbs.run(key, id).then(\n () => reload(),\n (failure: unknown) => setUseCaseError(asFailure(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","envelopeEntityName","extractMetaEntity","Internal","EntityTable","useCasesForSurface","entityQueryScope","useDataLoading","useEntityMutation","useEntityRecord","TransactionSinkTag","useQueryClient","Cause","Context","Effect","Exit","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","asFailure","failure","Error","verbsOf","runner","served","undefined","settle","effect","runPromiseExit","then","exit","isSuccess","value","Promise","reject","squash","cause","descriptor","key","find","candidate","run","id","bulk","selection","useLinkFilters","links","record","map","link","useBaseFiltering","makeEntityCrud","entityConstructor","options","useAdapters","basePath","catalogKey","hiddenFields","columns","toolbar","pageSize","metadataSource","givenMetadataSource","metadata","useCases","name","metadataSourceOf","meta","String","labelKey","entityLabelKey","pluralKey","entityPluralKey","entityName","descriptors","linkPlans","entry","field","linkLabelProperty","labelProperty","linkSearchProperty","searchProperty","ListPage","affordances","pending","withLocale","queryClient","scope","renderLink","optimistic","pager","uc","ctx","queryKey","initialPageSize","canRunBulk","length","verbs","onCompleted","invalidateQueries","useCaseError","setUseCaseError","rowUseCases","canRunRowUseCase","handleRowUseCase","item","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,EAOrBC,kBAAkB,EAClBC,iBAAiB,EAEjBC,QAAQ,QAGH,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,KAAK,EAAEC,OAAO,EAAEC,MAAM,EAAEC,IAAI,QAAQ,SAAS;AACtD,SAASC,SAAS,EAAEC,SAAS,QAAQ,kBAAkB;AACvD,SAASC,QAAQ,QAAQ,QAAQ;AAEjC,SAASC,aAAa,QAAQ,mBAAmB;AACjD,SAAS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,gBAAO0D,0BAAAA,OAAQpF,EAAE,oBAAIlC;IAmBhC;IAEA,OAAO;QACL4C;QACA2G,WAAWvG;QACXc;QACAE;QACAjB;QACA2B;QACAoC;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/lib/crud/make-entity-crud.tsx"],"sourcesContent":["'use client';\n\nimport {\n deleteUCFactory,\n EntityIdTag,\n type EntityRepositoryTag,\n EntityTag,\n getUCFactory,\n loadUCFactory,\n saveUCFactory,\n} from '@entifix/business';\nimport {\n describeEntityColumns,\n type EntifixFailure,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityMetadataSource,\n type EntitySelection,\n type EntityUseCaseRunner,\n type EntityWriter,\n envelopeEntityName,\n extractMetaEntity,\n type FilterGroup,\n Internal,\n isFailure,\n settled,\n type UseCaseDescriptor,\n} from '@entifix/core';\nimport { EntityTable, useCasesForSurface } from '@entifix/react-controls';\nimport {\n entityQueryScope,\n type OptimisticMutation,\n useDataLoading,\n useEntityRecord,\n useOptimisticMutation,\n} from '@entifix/react-integration';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { Cause, Context, Effect, Exit } from 'effect';\nimport { useParams, useRouter } from 'next/navigation';\nimport { useEffect, useRef } from 'react';\n\nimport { useLocaleHref } from '../i18n/index.js';\nimport { useEntityNavHost } from '../workspace/entity-nav.js';\nimport { EntityCrudForm } from './entity-crud-form.js';\nimport type {\n AnyFilterGroup,\n EntityCrud,\n EntityCrudLinkSource,\n EntityCrudOptions,\n EntityCrudSingleViewProps,\n} from './make-entity-crud.types.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: one repository adapter.\n * Exported because a hand-built screen — a wizard reading records and\n * resolving pickers — runs against exactly the same.\n */\nexport type CrudContext = EntityRepositoryTag;\n\n/**\n * One repository adapter, by its key, as the context the use-cases run\n * 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 crudContextOf<TAdapters>(\n adapters: TAdapters,\n repository: keyof TAdapters,\n): Context.Context<CrudContext> {\n return adapters[repository] as Context.Context<EntityRepositoryTag>;\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 write, as something the form's error slot can render.\n *\n * A typed failure is kept as it is: `useErrorMessage` translates its own code,\n * a business refusal and an outage alike. Anything else is a bug that reached\n * the screen, and is shown as `Internal` — never with its own text, which\n * nobody wrote for a user.\n */\nfunction asFailure(failure: unknown): EntifixFailure {\n return isFailure(failure) ? failure : new Internal();\n}\n\n/**\n * What a write failed with *synchronously* — before any flow took it — or\n * `undefined`. A flow's own failure is toasted by the `PendingFlowsProvider`\n * that settles it, so showing it in the error slot too would tell the operator\n * twice.\n */\nfunction syncFailure(\n mutation: OptimisticMutation<never, unknown>,\n): EntifixFailure | undefined {\n return mutation.status === 'failed' && mutation.flowId === undefined\n ? asFailure(mutation.failure)\n : undefined;\n}\n\n/**\n * A runner's verbs, looked up by the key the served `$metadata` named. A\n * single verb answers either settle mode, so it is run through the optimistic\n * API; a bulk run reports per row and is awaited as a promise whose rejection\n * carries the failure itself.\n */\nfunction verbsOf(\n runner: EntityUseCaseRunner | undefined,\n served: readonly UseCaseDescriptor[] | undefined,\n) {\n if (runner === undefined) return undefined;\n // The key always comes from the served document, so it names a verb in it.\n const descriptor = (key: string) =>\n served?.find(candidate => candidate.key === key) as UseCaseDescriptor;\n return {\n run: (key: string, id: EntityId) => runner.run(descriptor(key), id),\n bulk: (key: string, selection: EntitySelection<Entity>) =>\n Effect.runPromiseExit(runner.bulk(descriptor(key), selection)).then(\n exit =>\n Exit.isSuccess(exit)\n ? exit.value\n : Promise.reject(Cause.squash(exit.cause)),\n ),\n };\n}\n\ntype Verbs = NonNullable<ReturnType<typeof verbsOf>>;\n\n/**\n * One verb on one record, through the optimistic API: `done` runs once the\n * verb took effect — at once when it settled, or when the flow it was handed\n * to completed.\n */\nfunction useVerb(verbs: Verbs | undefined, done: () => void) {\n const verb = useOptimisticMutation<\n { readonly key: string; readonly id: EntityId },\n unknown\n >({\n // Only ever sent from a handler that exists because `verbs` does.\n write: ({ key, id }) => (verbs as Verbs).run(key, id),\n confirm: done,\n });\n const run = (key: string, id: EntityId) => {\n void verb.mutate({ key, id }).then(\n result => {\n if (result._tag === 'settled') done();\n },\n // Shown through `syncFailure`, from the mutation's own state.\n () => undefined,\n );\n };\n return { verb, run };\n}\n\n/** Whether the component is still mounted: a flow can settle after it left. */\nfunction useMounted() {\n const mounted = useRef(true);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n return mounted;\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 useCases,\n write,\n } = options;\n\n if (givenMetadataSource !== undefined && metadata !== undefined) {\n throw new Error(\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 Error(\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 Error(\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 flow's intent records and what\n // `entityQueryScopeFor` keys on — one derivation, so the two can never\n // 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 Error(\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 // 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 const pager = useDataLoading<TEntity, CrudContext>({\n uc: loadUCFactory<TEntity>(),\n ctx: crudContextOf(adapters, repository),\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 verbs = verbsOf(\n useCases === undefined\n ? undefined\n : (adapters[useCases] as EntityUseCaseRunner),\n affordances.metadata?.useCases,\n );\n\n const bulk = useEntityBulk<TEntity>({\n run:\n canRunBulk && verbs !== undefined\n ? (key, selection) =>\n verbs.bulk(key, selection as EntitySelection<Entity>)\n : 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; the runner 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 rowVerb = useVerb(verbs, () => {\n void queryClient.invalidateQueries({ queryKey: scope });\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 = verbs !== undefined && rowUseCases.length > 0;\n\n const handleRowUseCase = canRunRowUseCase\n ? (key: string, item: TEntity) => {\n if (item.id == null) return;\n rowVerb.run(key, item.id);\n }\n : undefined;\n\n return (\n <div className=\"flex flex-col gap-s\">\n <EntityTable\n entityConstructor={entityConstructor}\n {...pager}\n items={pager.items}\n totalItems={pager.totalItems}\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={syncFailure(rowVerb.verb) ?? 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 // The same served document the form reads its buttons from, so a key the\n // form hands back always names a verb in it.\n const affordances = useEntityAffordances(entityConstructor, metadataSource);\n const router = useRouter();\n const withLocale = useLocaleHref();\n const params = useParams<{ slug: string }>();\n const mounted = useMounted();\n const id = slugToEntityId(slug ?? params.slug);\n\n const ctx = crudContextOf(adapters, repository);\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 // 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: crudContextOf(adapters, plan.repository),\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: the service is the authority on\n // the row it stored.\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 // Through the host's writer when it named one, which answers both settle\n // modes; otherwise through the repository, where every write settles.\n const writer =\n write === undefined ? undefined : (adapters[write] as EntityWriter);\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 write — or a failed flow — deliberately keeps the draft and the\n // form: the edit is still the user's only copy of what they typed.\n //\n // ⚠️ A flow can complete after the operator left this page, so leaving it\n // is guarded on still being here: a navigation from a form nobody is\n // looking at would pull them away from wherever they went.\n const saveMutation = useOptimisticMutation<TEntity, TEntity>({\n write: next =>\n writer === undefined\n ? Effect.map(\n Effect.provide(\n saveUCFactory<TEntity>(),\n ctx.pipe(Context.add(EntityTag, next)),\n ),\n settled,\n )\n : writer.save(next),\n intent: () => ({ entity: entityName, write: 'save' }),\n confirm: () => {\n draft?.clear();\n void refreshList();\n if (mounted.current) afterSave();\n },\n });\n const deleteMutation = useOptimisticMutation<EntityId, void>({\n write: target =>\n writer === undefined\n ? Effect.as(\n Effect.provide(\n deleteUCFactory<TEntity>(),\n ctx.pipe(Context.add(EntityIdTag, target)),\n ),\n settled(undefined),\n )\n : writer.delete(target),\n intent: () => ({ entity: entityName, write: 'delete' }),\n confirm: () => {\n draft?.clear();\n void refreshList();\n if (mounted.current) afterDelete();\n },\n });\n\n const handleSave = async (next: TEntity) => {\n const result = await saveMutation.mutate(next).catch(() => undefined);\n // Failed, or pending: the form stays, and the mutation says which. A\n // pending write leaves through the mutation's `confirm`, once its flow\n // completed.\n if (result?._tag !== 'settled') return;\n draft?.clear();\n void refreshList();\n afterSave();\n };\n\n const handleDelete = async () => {\n const result = await deleteMutation.mutate(id).catch(() => undefined);\n if (result?._tag !== 'settled') return;\n draft?.clear();\n void refreshList();\n afterDelete();\n };\n\n /**\n * An `entity`-bound verb, on the record being shown.\n *\n * It **reloads** — once the verb took effect, which for one the server\n * handed to a flow is when the flow completed — 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 verbs = verbsOf(\n useCases === undefined\n ? undefined\n : (adapters[useCases] as EntityUseCaseRunner),\n affordances.metadata?.useCases,\n );\n const recordVerb = useVerb(verbs, () => void reload());\n const handleUseCase =\n verbs === undefined || id == null\n ? undefined\n : (key: string) => recordVerb.run(key, id);\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={saveMutation.status === 'running'}\n isPending={[saveMutation, deleteMutation, recordVerb.verb].some(\n mutation => mutation.status === 'pending',\n )}\n isDeleting={deleteMutation.status === 'running'}\n error={\n loadError ??\n syncFailure(saveMutation) ??\n syncFailure(deleteMutation) ??\n syncFailure(recordVerb.verb)\n }\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","EntityIdTag","EntityTag","getUCFactory","loadUCFactory","saveUCFactory","describeEntityColumns","envelopeEntityName","extractMetaEntity","Internal","isFailure","settled","EntityTable","useCasesForSurface","entityQueryScope","useDataLoading","useEntityRecord","useOptimisticMutation","useQueryClient","Cause","Context","Effect","Exit","useParams","useRouter","useEffect","useRef","useLocaleHref","useEntityNavHost","EntityCrudForm","CATALOG_NEW_SLUG","slugToEntityId","useCrudRenderLink","useEntityAffordances","useEntityBulk","TARGET_NAME_PROPERTY","crudContextOf","adapters","repository","asFailure","failure","syncFailure","mutation","status","flowId","undefined","verbsOf","runner","served","descriptor","key","find","candidate","run","id","bulk","selection","runPromiseExit","then","exit","isSuccess","value","Promise","reject","squash","cause","useVerb","verbs","done","verb","write","confirm","mutate","result","_tag","useMounted","mounted","current","useLinkFilters","links","record","map","link","useBaseFiltering","makeEntityCrud","entityConstructor","options","useAdapters","basePath","catalogKey","hiddenFields","columns","toolbar","pageSize","metadataSource","givenMetadataSource","metadata","useCases","Error","name","metadataSourceOf","meta","String","labelKey","entityLabelKey","pluralKey","entityPluralKey","entityName","descriptors","linkPlans","entry","field","linkLabelProperty","labelProperty","linkSearchProperty","searchProperty","ListPage","affordances","withLocale","queryClient","scope","renderLink","pager","uc","ctx","queryKey","initialPageSize","canRunBulk","length","onCompleted","invalidateQueries","rowVerb","rowUseCases","canRunRowUseCase","handleRowUseCase","item","div","className","items","totalItems","hrefFor","newHref","tableProps","onUseCase","error","SingleViewPage","slug","onSaved","onDeleted","draft","loadError","router","params","entity","isLoading","reload","linkFilters","linkSources","plan","index","config","loadUc","getUc","baseFiltering","host","refreshList","toList","push","afterSave","afterDelete","writer","saveMutation","next","provide","pipe","add","save","intent","clear","deleteMutation","target","as","delete","handleSave","catch","handleDelete","recordVerb","handleUseCase","isSaving","isPending","some","isDeleting","onSave","onDelete","backHref","entityKey"],"mappings":"AAAA;;;AAEA,SACEA,eAAe,EACfC,WAAW,EAEXC,SAAS,EACTC,YAAY,EACZC,aAAa,EACbC,aAAa,QACR,oBAAoB;AAC3B,SACEC,qBAAqB,EASrBC,kB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