@marktiderman/genesis-core 2.10.0 → 2.12.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 (96) hide show
  1. package/README.md +191 -1
  2. package/dist/{chunk-LGTXQTHA.js → chunk-2VJQVAJD.js} +3 -3
  3. package/dist/{chunk-LGTXQTHA.js.map → chunk-2VJQVAJD.js.map} +1 -1
  4. package/dist/chunk-2WS4LGYU.js +47 -0
  5. package/dist/chunk-2WS4LGYU.js.map +1 -0
  6. package/dist/{chunk-KXVDDDJY.js → chunk-3B5O36DU.js} +105 -13
  7. package/dist/chunk-3B5O36DU.js.map +1 -0
  8. package/dist/{chunk-EHFYSJJA.js → chunk-42QPCDQF.js} +3 -3
  9. package/dist/{chunk-EHFYSJJA.js.map → chunk-42QPCDQF.js.map} +1 -1
  10. package/dist/{chunk-RK365SO2.js → chunk-C62CMLWG.js} +8 -5
  11. package/dist/chunk-C62CMLWG.js.map +1 -0
  12. package/dist/chunk-HYYTAJBG.js +85 -0
  13. package/dist/chunk-HYYTAJBG.js.map +1 -0
  14. package/dist/{chunk-4ZR7472O.js → chunk-LOJGHR5O.js} +4 -4
  15. package/dist/{chunk-4ZR7472O.js.map → chunk-LOJGHR5O.js.map} +1 -1
  16. package/dist/{chunk-ON2V4RXX.js → chunk-OC4OGB2K.js} +19 -11
  17. package/dist/chunk-OC4OGB2K.js.map +1 -0
  18. package/dist/{chunk-HQAVDVIH.js → chunk-POMTRNAL.js} +4 -4
  19. package/dist/{chunk-HQAVDVIH.js.map → chunk-POMTRNAL.js.map} +1 -1
  20. package/dist/{chunk-VDEW4AOS.js → chunk-PSFKIG27.js} +55 -6
  21. package/dist/chunk-PSFKIG27.js.map +1 -0
  22. package/dist/{chunk-37RWGNIO.js → chunk-VFT6QKZW.js} +114 -5
  23. package/dist/chunk-VFT6QKZW.js.map +1 -0
  24. package/dist/{chunk-VDS6REM3.js → chunk-VJGU6E4U.js} +5 -5
  25. package/dist/{chunk-VDS6REM3.js.map → chunk-VJGU6E4U.js.map} +1 -1
  26. package/dist/{chunk-ZCE3CHPX.js → chunk-XVRIWP7B.js} +3 -3
  27. package/dist/{chunk-ZCE3CHPX.js.map → chunk-XVRIWP7B.js.map} +1 -1
  28. package/dist/{chunk-7FVTGKTX.js → chunk-YDMKMNDS.js} +2 -2
  29. package/dist/{chunk-7FVTGKTX.js.map → chunk-YDMKMNDS.js.map} +1 -1
  30. package/dist/{chunk-6WV6ST67.js → chunk-YNXLPOAB.js} +97 -10
  31. package/dist/chunk-YNXLPOAB.js.map +1 -0
  32. package/dist/{chunk-7GW3QR63.js → chunk-ZHC3MDCS.js} +101 -18
  33. package/dist/chunk-ZHC3MDCS.js.map +1 -0
  34. package/dist/conversation/index.d.ts +195 -0
  35. package/dist/conversation/index.js +110 -0
  36. package/dist/conversation/index.js.map +1 -0
  37. package/dist/csv.d.ts +1 -1
  38. package/dist/errors.js +1 -2
  39. package/dist/form-types.d.ts +1 -1
  40. package/dist/gallery/index.d.ts +79 -0
  41. package/dist/gallery/index.js +64 -0
  42. package/dist/gallery/index.js.map +1 -0
  43. package/dist/hooks/index.d.ts +6 -4
  44. package/dist/hooks/index.js +19 -18
  45. package/dist/hooks/mutation-mode.d.ts +29 -2
  46. package/dist/hooks/mutation-mode.js +9 -4
  47. package/dist/hooks/related-keys.d.ts +1 -1
  48. package/dist/hooks/use-capabilities.d.ts +1 -1
  49. package/dist/hooks/use-capabilities.js +2 -2
  50. package/dist/hooks/use-infinite-resource.d.ts +1 -1
  51. package/dist/hooks/use-infinite-resource.js +4 -4
  52. package/dist/hooks/use-link-options.d.ts +1 -1
  53. package/dist/hooks/use-link-options.js +6 -6
  54. package/dist/hooks/use-live.d.ts +1 -1
  55. package/dist/hooks/use-live.js +3 -3
  56. package/dist/hooks/use-one.d.ts +1 -1
  57. package/dist/hooks/use-one.js +4 -4
  58. package/dist/hooks/use-persisted-ui-state.d.ts +12 -0
  59. package/dist/hooks/use-persisted-ui-state.js +5 -0
  60. package/dist/hooks/use-persisted-ui-state.js.map +1 -0
  61. package/dist/hooks/use-relation-label.d.ts +1 -1
  62. package/dist/hooks/use-relation-label.js +2 -2
  63. package/dist/hooks/use-resource-form.d.ts +14 -1
  64. package/dist/hooks/use-resource-form.js +12 -9
  65. package/dist/hooks/use-resource.d.ts +17 -3
  66. package/dist/hooks/use-resource.js +12 -8
  67. package/dist/hooks/use-write.d.ts +1 -1
  68. package/dist/index.d.ts +9 -6
  69. package/dist/index.js +22 -21
  70. package/dist/offline/index.d.ts +84 -0
  71. package/dist/offline/index.js +413 -0
  72. package/dist/offline/index.js.map +1 -0
  73. package/dist/provider/index.d.ts +60 -7
  74. package/dist/provider/index.js +3 -3
  75. package/dist/resource-view/index.d.ts +79 -4
  76. package/dist/resource-view/index.js +141 -19
  77. package/dist/resource-view/index.js.map +1 -1
  78. package/dist/schema/index.d.ts +4 -3
  79. package/dist/schema/index.js +2 -1
  80. package/dist/testing/index.d.ts +2 -2
  81. package/dist/{types-9WnGxZhj.d.ts → types-BzLv8yOm.d.ts} +8 -0
  82. package/dist/types-CsKSAKqs.d.ts +143 -0
  83. package/dist/{viewer-scope-bthEYSOB.d.ts → viewer-scope-Dx0N9AYk.d.ts} +3 -2
  84. package/dist/workspaces.d.ts +1 -1
  85. package/dist/{write-outcome-ZWlhhzRW.d.ts → write-outcome-DC5hORz-.d.ts} +1 -1
  86. package/dist/write-state-DVC4Yq9T.d.ts +58 -0
  87. package/package.json +15 -2
  88. package/dist/chunk-37RWGNIO.js.map +0 -1
  89. package/dist/chunk-6WV6ST67.js.map +0 -1
  90. package/dist/chunk-7GW3QR63.js.map +0 -1
  91. package/dist/chunk-KXVDDDJY.js.map +0 -1
  92. package/dist/chunk-ON2V4RXX.js.map +0 -1
  93. package/dist/chunk-PA6WJE5E.js +0 -115
  94. package/dist/chunk-PA6WJE5E.js.map +0 -1
  95. package/dist/chunk-RK365SO2.js.map +0 -1
  96. package/dist/chunk-VDEW4AOS.js.map +0 -1
@@ -1,5 +1,5 @@
1
+ import { useDataProvider } from './chunk-PSFKIG27.js';
1
2
  import { patchCachedRow, listCouldChange } from './chunk-AUVKRXRC.js';
2
- import { useDataProvider } from './chunk-VDEW4AOS.js';
3
3
  import { useRef, useEffect } from 'react';
4
4
  import { useQueryClient } from '@tanstack/react-query';
5
5
 
@@ -89,5 +89,5 @@ function useLiveInvalidation(resource, live, enabled, params, queryKey, accept)
89
89
  }
90
90
 
91
91
  export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS, useLiveInvalidation };
92
- //# sourceMappingURL=chunk-ZCE3CHPX.js.map
93
- //# sourceMappingURL=chunk-ZCE3CHPX.js.map
92
+ //# sourceMappingURL=chunk-XVRIWP7B.js.map
93
+ //# sourceMappingURL=chunk-XVRIWP7B.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-live.ts"],"names":[],"mappings":";;;;;AA0BO,IAAM,wBAAA,GAA2B;AAOjC,IAAM,sBAAA,GAAyB;AAkBtC,IAAM,iBAAA,uBAAwB,OAAA,EAAgB;AAWvC,SAAS,oBACd,QAAA,EACA,IAAA,EACA,OAAA,EACA,MAAA,EACA,UACA,MAAA,EACM;AACN,EAAA,MAAM,WAAW,eAAA,EAAgB;AACjC,EAAA,MAAM,cAAc,cAAA,EAAe;AACnC,EAAA,MAAM,EAAA,GAAK,CAAC,CAAC,IAAA,IAAQ,OAAA;AACrB,EAAA,MAAM,aAAa,IAAA,CAAK,GAAA;AAAA,IACtB,CAAA;AAAA,IAAA,CACC,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,CAAK,aAAa,MAAA,KAAc;AAAA,GAC9D;AACA,EAAA,MAAM,WAAW,IAAA,CAAK,GAAA;AAAA,IACpB,CAAA;AAAA,IAAA,CACC,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,CAAK,WAAW,MAAA,KAAc;AAAA,GAC5D;AACA,EAAA,MAAM,SAAA,GAAY,IAAA,CAAK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E;AAGA,IAAA,MAAM,MAAA,GACJ,QAAA,GAAW,CAAA,GACP,WAAA,CAAY,MAAM;AAChB,MAAA,IAAI,CAAC,MAAA,EAAQ;AACb,MAAA,IAAI,OAAO,QAAA,KAAa,WAAA,IAAe,QAAA,CAAS,oBAAoB,QAAA,EAAU;AAC9E,MAAA,KAAK,WAAA,CAAY,iBAAA,CAAkB,EAAE,QAAA,EAAU,CAAC,GAAG,MAAA,CAAO,OAAA,CAAQ,QAAQ,CAAA,EAAG,WAAA,EAAa,QAAA,EAAU,CAAA;AAAA,IACtG,CAAA,EAAG,QAAQ,CAAA,GACX,MAAA;AACN,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,GAAS,KAAA;AACT,MAAA,IAAI,MAAA,KAAW,MAAA,EAAW,aAAA,CAAc,MAAM,CAAA;AAC9C,MAAA,IAAI,KAAA,KAAU,MAAA,EAAW,YAAA,CAAa,KAAK,CAAA;AAC3C,MAAA,IAAI;AACF,QAAA,WAAA,IAAc;AAAA,MAChB,SAAS,KAAA,EAAO;AACd,QAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,8BAAA,EAAiC,QAAQ,CAAA,SAAA,CAAA,EAAa,KAAK,CAAA;AAAA,MAC3E;AAAA,IACF,CAAA;AAAA,EAEF,CAAA,EAAG,CAAC,EAAA,EAAI,QAAA,EAAU,WAAA,EAAa,UAAU,UAAA,EAAY,QAAA,EAAU,SAAA,EAAW,MAAM,CAAC,CAAA;AACnF","file":"chunk-ZCE3CHPX.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Live reads — refetch a resource's cached reads when the provider reports a\n// change (`DataProvider.subscribe`).\n//\n// Events are invalidation hints. When an update carries the row (the provider\n// sends one only for a resource read from its own table, under realtime's RLS),\n// the fields cached rows already have are patched at once; the refetch that\n// follows still goes through the provider's normal read, so what a user ends\n// up seeing is what that read (and its RLS) returns. Lists the change can't\n// have touched (its row matches none of their filters and isn't in them) are\n// left alone.\n//\n// Pending optimistic and undoable writes are safe: their patches are\n// re-applied to whatever a refetch brings (see mutation-mode.ts), so a row\n// deleted with undo stays hidden and an edit stays shown until the write\n// settles. The provider drops the echo of this client's own writes, which\n// already refresh through the write path.\n// ---------------------------------------------------------------------------\n\nimport { useEffect, useRef } from \"react\";\nimport { useQueryClient, type QueryKey } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { ResourceChangeEvent, SubscribeParams } from \"../provider/types\";\nimport { listCouldChange, patchCachedRow } from \"./live-cache\";\n\n/** How long a burst of change events is gathered into one refetch. */\nexport const DEFAULT_LIVE_DEBOUNCE_MS = 250;\n\n/**\n * How often a live read refetches anyway while the page is visible. Realtime checks each change\n * against the row's new state, so a row the viewer stops being allowed to see (binned, made a\n * draft, moved to another practice) sends them nothing and would stay on screen.\n */\nexport const DEFAULT_LIVE_RESYNC_MS = 60_000;\n\n/** `live` as an object, to tune it. `live: true` takes the defaults. */\nexport interface LiveOptions {\n /**\n * Events arriving within this many milliseconds of each other cause one\n * refetch, not one each. Default {@link DEFAULT_LIVE_DEBOUNCE_MS}. A\n * steady stream still refetches at least every `4 × debounceMs`.\n */\n debounceMs?: number;\n /**\n * Refetch at least this often while the page is visible, for the changes realtime can't\n * deliver (a row the viewer may no longer read). Default {@link DEFAULT_LIVE_RESYNC_MS}; 0 turns\n * it off.\n */\n resyncMs?: number;\n}\n\nconst warnedNoSubscribe = new WeakSet<object>();\n\n/**\n * Subscribes while mounted and `enabled`, and invalidates `queryKey` (a\n * prefix) once per burst of events that `accept` lets through. While the\n * page is hidden the queries are only marked stale; they refetch when it is\n * shown again (TanStack Query's `refetchOnWindowFocus`) or next used.\n *\n * @internal Used by `useResource` and `useOne`'s `live` option, and by ResourceView's calendar,\n * which loads its own queries. Exported from `/hooks` for those, not for screens.\n */\nexport function useLiveInvalidation(\n resource: string,\n live: boolean | LiveOptions | undefined,\n enabled: boolean,\n params: SubscribeParams,\n queryKey: QueryKey,\n accept?: (event: ResourceChangeEvent) => boolean,\n): void {\n const provider = useDataProvider();\n const queryClient = useQueryClient();\n const on = !!live && enabled;\n const debounceMs = Math.max(\n 0,\n (typeof live === \"object\" ? live.debounceMs : undefined) ?? DEFAULT_LIVE_DEBOUNCE_MS,\n );\n const resyncMs = Math.max(\n 0,\n (typeof live === \"object\" ? live.resyncMs : undefined) ?? DEFAULT_LIVE_RESYNC_MS,\n );\n const paramsKey = JSON.stringify(params);\n const keyKey = JSON.stringify(queryKey);\n\n // The latest values, read when an event arrives, so a new array or\n // callback each render doesn't resubscribe.\n const latest = useRef({ queryKey, accept, params });\n latest.current = { queryKey, accept, params };\n\n useEffect(() => {\n if (!on) return;\n if (typeof provider.subscribe !== \"function\") {\n if (process.env.NODE_ENV !== \"production\" && !warnedNoSubscribe.has(provider)) {\n warnedNoSubscribe.add(provider);\n console.warn(\n `[genesis] \"${resource}\" asked for live updates, but the data provider has no subscribe(); the list will only refresh on its own reads.`,\n );\n }\n return;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n let burstStart = 0;\n // The rows of this burst's updates; null once an event without one (a delete, an insert,\n // `changed`) means every read must refetch.\n let burst: Record<string, unknown>[] | null = [];\n let active = true;\n // A busy table must not postpone the refetch forever.\n const maxWaitMs = debounceMs * 4;\n const fire = () => {\n timer = undefined;\n if (!active) return;\n const hidden = typeof document !== \"undefined\" && document.visibilityState === \"hidden\";\n const rows = burst;\n burst = [];\n void queryClient.invalidateQueries({\n queryKey: [...latest.current.queryKey],\n refetchType: hidden ? \"none\" : \"active\",\n ...(rows && rows.length ? { predicate: (query) => listCouldChange(query, rows) } : {}),\n });\n };\n let unsubscribe: (() => void) | undefined;\n try {\n unsubscribe = provider.subscribe(resource, latest.current.params, (event) => {\n if (!active) return;\n const test = latest.current.accept;\n if (test && event.type !== \"changed\" && !test(event)) return;\n if (event.type === \"updated\" && event.record) {\n patchCachedRow(queryClient, resource, event.record);\n burst?.push(event.record);\n } else {\n burst = null;\n }\n // Coalesce: one refetch per burst, after it goes quiet (or has\n // lasted `maxWaitMs`).\n const now = Date.now();\n if (timer === undefined) burstStart = now;\n else clearTimeout(timer);\n timer = setTimeout(fire, Math.min(debounceMs, Math.max(0, burstStart + maxWaitMs - now)));\n });\n } catch (error) {\n console.error(`[genesis] subscribing to \"${resource}\" failed:`, error);\n }\n // The safety net for changes realtime can't deliver; skipped while the page is hidden (a\n // hidden page refetches when it's shown again).\n const resync =\n resyncMs > 0\n ? setInterval(() => {\n if (!active) return;\n if (typeof document !== \"undefined\" && document.visibilityState === \"hidden\") return;\n void queryClient.invalidateQueries({ queryKey: [...latest.current.queryKey], refetchType: \"active\" });\n }, resyncMs)\n : undefined;\n return () => {\n active = false;\n if (resync !== undefined) clearInterval(resync);\n if (timer !== undefined) clearTimeout(timer);\n try {\n unsubscribe?.();\n } catch (error) {\n console.error(`[genesis] unsubscribing from \"${resource}\" failed:`, error);\n }\n };\n // `paramsKey` / `keyKey` stand for `params` / `queryKey` by value.\n }, [on, provider, queryClient, resource, debounceMs, resyncMs, paramsKey, keyKey]);\n}\n"]}
1
+ {"version":3,"sources":["../src/hooks/use-live.ts"],"names":[],"mappings":";;;;;AA0BO,IAAM,wBAAA,GAA2B;AAOjC,IAAM,sBAAA,GAAyB;AAkBtC,IAAM,iBAAA,uBAAwB,OAAA,EAAgB;AAWvC,SAAS,oBACd,QAAA,EACA,IAAA,EACA,OAAA,EACA,MAAA,EACA,UACA,MAAA,EACM;AACN,EAAA,MAAM,WAAW,eAAA,EAAgB;AACjC,EAAA,MAAM,cAAc,cAAA,EAAe;AACnC,EAAA,MAAM,EAAA,GAAK,CAAC,CAAC,IAAA,IAAQ,OAAA;AACrB,EAAA,MAAM,aAAa,IAAA,CAAK,GAAA;AAAA,IACtB,CAAA;AAAA,IAAA,CACC,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,CAAK,aAAa,MAAA,KAAc;AAAA,GAC9D;AACA,EAAA,MAAM,WAAW,IAAA,CAAK,GAAA;AAAA,IACpB,CAAA;AAAA,IAAA,CACC,OAAO,IAAA,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A,OAAA,CAAQ,KAAA,CAAM,CAAA,0BAAA,EAA6B,QAAQ,CAAA,SAAA,CAAA,EAAa,KAAK,CAAA;AAAA,IACvE;AAGA,IAAA,MAAM,MAAA,GACJ,QAAA,GAAW,CAAA,GACP,WAAA,CAAY,MAAM;AAChB,MAAA,IAAI,CAAC,MAAA,EAAQ;AACb,MAAA,IAAI,OAAO,QAAA,KAAa,WAAA,IAAe,QAAA,CAAS,oBAAoB,QAAA,EAAU;AAC9E,MAAA,KAAK,WAAA,CAAY,iBAAA,CAAkB,EAAE,QAAA,EAAU,CAAC,GAAG,MAAA,CAAO,OAAA,CAAQ,QAAQ,CAAA,EAAG,WAAA,EAAa,QAAA,EAAU,CAAA;AAAA,IACtG,CAAA,EAAG,QAAQ,CAAA,GACX,MAAA;AACN,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,GAAS,KAAA;AACT,MAAA,IAAI,MAAA,KAAW,MAAA,EAAW,aAAA,CAAc,MAAM,CAAA;AAC9C,MAAA,IAAI,KAAA,KAAU,MAAA,EAAW,YAAA,CAAa,KAAK,CAAA;AAC3C,MAAA,IAAI;AACF,QAAA,WAAA,IAAc;AAAA,MAChB,SAAS,KAAA,EAAO;AACd,QAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,8BAAA,EAAiC,QAAQ,CAAA,SAAA,CAAA,EAAa,KAAK,CAAA;AAAA,MAC3E;AAAA,IACF,CAAA;AAAA,EAEF,CAAA,EAAG,CAAC,EAAA,EAAI,QAAA,EAAU,WAAA,EAAa,UAAU,UAAA,EAAY,QAAA,EAAU,SAAA,EAAW,MAAM,CAAC,CAAA;AACnF","file":"chunk-XVRIWP7B.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Live reads — refetch a resource's cached reads when the provider reports a\n// change (`DataProvider.subscribe`).\n//\n// Events are invalidation hints. When an update carries the row (the provider\n// sends one only for a resource read from its own table, under realtime's RLS),\n// the fields cached rows already have are patched at once; the refetch that\n// follows still goes through the provider's normal read, so what a user ends\n// up seeing is what that read (and its RLS) returns. Lists the change can't\n// have touched (its row matches none of their filters and isn't in them) are\n// left alone.\n//\n// Pending optimistic and undoable writes are safe: their patches are\n// re-applied to whatever a refetch brings (see mutation-mode.ts), so a row\n// deleted with undo stays hidden and an edit stays shown until the write\n// settles. The provider drops the echo of this client's own writes, which\n// already refresh through the write path.\n// ---------------------------------------------------------------------------\n\nimport { useEffect, useRef } from \"react\";\nimport { useQueryClient, type QueryKey } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { ResourceChangeEvent, SubscribeParams } from \"../provider/types\";\nimport { listCouldChange, patchCachedRow } from \"./live-cache\";\n\n/** How long a burst of change events is gathered into one refetch. */\nexport const DEFAULT_LIVE_DEBOUNCE_MS = 250;\n\n/**\n * How often a live read refetches anyway while the page is visible. Realtime checks each change\n * against the row's new state, so a row the viewer stops being allowed to see (binned, made a\n * draft, moved to another practice) sends them nothing and would stay on screen.\n */\nexport const DEFAULT_LIVE_RESYNC_MS = 60_000;\n\n/** `live` as an object, to tune it. `live: true` takes the defaults. */\nexport interface LiveOptions {\n /**\n * Events arriving within this many milliseconds of each other cause one\n * refetch, not one each. Default {@link DEFAULT_LIVE_DEBOUNCE_MS}. A\n * steady stream still refetches at least every `4 × debounceMs`.\n */\n debounceMs?: number;\n /**\n * Refetch at least this often while the page is visible, for the changes realtime can't\n * deliver (a row the viewer may no longer read). Default {@link DEFAULT_LIVE_RESYNC_MS}; 0 turns\n * it off.\n */\n resyncMs?: number;\n}\n\nconst warnedNoSubscribe = new WeakSet<object>();\n\n/**\n * Subscribes while mounted and `enabled`, and invalidates `queryKey` (a\n * prefix) once per burst of events that `accept` lets through. While the\n * page is hidden the queries are only marked stale; they refetch when it is\n * shown again (TanStack Query's `refetchOnWindowFocus`) or next used.\n *\n * @internal Used by `useResource` and `useOne`'s `live` option, and by ResourceView's calendar,\n * which loads its own queries. Exported from `/hooks` for those, not for screens.\n */\nexport function useLiveInvalidation(\n resource: string,\n live: boolean | LiveOptions | undefined,\n enabled: boolean,\n params: SubscribeParams,\n queryKey: QueryKey,\n accept?: (event: ResourceChangeEvent) => boolean,\n): void {\n const provider = useDataProvider();\n const queryClient = useQueryClient();\n const on = !!live && enabled;\n const debounceMs = Math.max(\n 0,\n (typeof live === \"object\" ? live.debounceMs : undefined) ?? DEFAULT_LIVE_DEBOUNCE_MS,\n );\n const resyncMs = Math.max(\n 0,\n (typeof live === \"object\" ? live.resyncMs : undefined) ?? DEFAULT_LIVE_RESYNC_MS,\n );\n const paramsKey = JSON.stringify(params);\n const keyKey = JSON.stringify(queryKey);\n\n // The latest values, read when an event arrives, so a new array or\n // callback each render doesn't resubscribe.\n const latest = useRef({ queryKey, accept, params });\n latest.current = { queryKey, accept, params };\n\n useEffect(() => {\n if (!on) return;\n if (typeof provider.subscribe !== \"function\") {\n if (process.env.NODE_ENV !== \"production\" && !warnedNoSubscribe.has(provider)) {\n warnedNoSubscribe.add(provider);\n console.warn(\n `[genesis] \"${resource}\" asked for live updates, but the data provider has no subscribe(); the list will only refresh on its own reads.`,\n );\n }\n return;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n let burstStart = 0;\n // The rows of this burst's updates; null once an event without one (a delete, an insert,\n // `changed`) means every read must refetch.\n let burst: Record<string, unknown>[] | null = [];\n let active = true;\n // A busy table must not postpone the refetch forever.\n const maxWaitMs = debounceMs * 4;\n const fire = () => {\n timer = undefined;\n if (!active) return;\n const hidden = typeof document !== \"undefined\" && document.visibilityState === \"hidden\";\n const rows = burst;\n burst = [];\n void queryClient.invalidateQueries({\n queryKey: [...latest.current.queryKey],\n refetchType: hidden ? \"none\" : \"active\",\n ...(rows && rows.length ? { predicate: (query) => listCouldChange(query, rows) } : {}),\n });\n };\n let unsubscribe: (() => void) | undefined;\n try {\n unsubscribe = provider.subscribe(resource, latest.current.params, (event) => {\n if (!active) return;\n const test = latest.current.accept;\n if (test && event.type !== \"changed\" && !test(event)) return;\n if (event.type === \"updated\" && event.record) {\n patchCachedRow(queryClient, resource, event.record);\n burst?.push(event.record);\n } else {\n burst = null;\n }\n // Coalesce: one refetch per burst, after it goes quiet (or has\n // lasted `maxWaitMs`).\n const now = Date.now();\n if (timer === undefined) burstStart = now;\n else clearTimeout(timer);\n timer = setTimeout(fire, Math.min(debounceMs, Math.max(0, burstStart + maxWaitMs - now)));\n });\n } catch (error) {\n console.error(`[genesis] subscribing to \"${resource}\" failed:`, error);\n }\n // The safety net for changes realtime can't deliver; skipped while the page is hidden (a\n // hidden page refetches when it's shown again).\n const resync =\n resyncMs > 0\n ? setInterval(() => {\n if (!active) return;\n if (typeof document !== \"undefined\" && document.visibilityState === \"hidden\") return;\n void queryClient.invalidateQueries({ queryKey: [...latest.current.queryKey], refetchType: \"active\" });\n }, resyncMs)\n : undefined;\n return () => {\n active = false;\n if (resync !== undefined) clearInterval(resync);\n if (timer !== undefined) clearTimeout(timer);\n try {\n unsubscribe?.();\n } catch (error) {\n console.error(`[genesis] unsubscribing from \"${resource}\" failed:`, error);\n }\n };\n // `paramsKey` / `keyKey` stand for `params` / `queryKey` by value.\n }, [on, provider, queryClient, resource, debounceMs, resyncMs, paramsKey, keyKey]);\n}\n"]}
@@ -4,5 +4,5 @@ function defineResource() {
4
4
  }
5
5
 
6
6
  export { defineResource };
7
- //# sourceMappingURL=chunk-7FVTGKTX.js.map
8
- //# sourceMappingURL=chunk-7FVTGKTX.js.map
7
+ //# sourceMappingURL=chunk-YDMKMNDS.js.map
8
+ //# sourceMappingURL=chunk-YDMKMNDS.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schema/types.ts"],"names":[],"mappings":";AA+IO,SAAS,cAAA,GAAsC;AACpD,EAAA,OAAO,CACL,QAAA,KACiC,QAAA;AACrC","file":"chunk-7FVTGKTX.js","sourcesContent":["// ---------------------------------------------------------------------------\n// The one schema model (docs/DATA-STUDIO.md decisions 11, 12, 13, 30)\n//\n// Promoted from @marktiderman/genesis-switchboard, which keeps deprecated\n// aliases for one deprecation window. Everything here is a type or a pure\n// helper with no React, no runtime dependency and no I/O, so a server, an\n// edge function or the switchboard can import it without pulling in the\n// React half of this package.\n// ---------------------------------------------------------------------------\n\nimport type { FieldType as WidgetHint } from \"../form-types\";\n\nexport type { WidgetHint };\n\n/**\n * Portable storage type of a field — what kind of value the store holds,\n * independent of how a UI should edit it. The exact native type, when the\n * store reports one, is on {@link FieldSchema.dbType}.\n *\n * Exactly the six types the switchboard shipped as `FieldType`, so existing\n * exhaustive maps over it keep compiling. Finer distinctions (date versus\n * timestamp, enum, uuid) live in `dbType` and `widget`, not here.\n */\nexport type StorageType = \"string\" | \"number\" | \"boolean\" | \"datetime\" | \"json\" | \"relation\";\n\n/** A canonical, provider-agnostic row. Keys are field names from the schema. */\nexport type DataRow = Record<string, unknown>;\n\n/**\n * What the CURRENT user may do with one field. Reported by a provider's\n * `describe()`; never inferred in the browser.\n *\n * `read: false` means the value is never sent to this user, so the column\n * must not render at all (an answer key, a payout amount). `update: false`\n * with `read: true` renders the column read-only.\n */\nexport interface FieldPermissions {\n readonly read: boolean;\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n}\n\n/** A foreign-key style link from this field to another resource's field. */\nexport interface FieldReference {\n readonly resource: string;\n readonly field: string;\n}\n\nexport interface FieldSchema {\n /** Canonical field name in the resource's shape (provider-agnostic). */\n readonly name: string;\n /** Portable storage type. */\n readonly type: StorageType;\n /** True when a row may omit this field. */\n readonly optional?: boolean;\n /**\n * True when the field holds an ORDERED LIST of `type` values (e.g. a\n * multi-relation like `deps`/`serves`). Promotion emits a Postgres ARRAY\n * column (`<base>[]`) instead of a lossy scalar, so the cardinality survives\n * L1→L3 (CMT-1742-014).\n */\n readonly array?: boolean;\n /** Human note (surfaces in describe()/drift reports). */\n readonly description?: string;\n /** Human label, e.g. \"Date of birth\". Absent means a UI derives one from `name`. */\n readonly label?: string;\n /** The store's exact type, e.g. `timestamp with time zone` or `public.status`. */\n readonly dbType?: string;\n /** Which control fits this field. A hint: a UI may still choose another. */\n readonly widget?: WidgetHint;\n /** True when the store accepts null for this field. */\n readonly nullable?: boolean;\n /** True when the store fills the field itself on insert. */\n readonly hasDefault?: boolean;\n /** True when the store computes the field; it is never written. */\n readonly generated?: boolean;\n /** Allowed values, for enum-like fields. */\n readonly enumValues?: readonly string[];\n /** The resource and field this one points at, when it is a link. */\n readonly references?: FieldReference;\n /** The current user's rights on this field, when a provider reports them. */\n readonly permissions?: FieldPermissions;\n /**\n * The server owns this field (a status it derives, a total, an audit stamp): clients never write\n * it, so a UI shows it read-only. Declared once (`@genesis {\"readonly\": true}`); the database's\n * own guards still enforce it.\n */\n readonly readOnly?: boolean;\n /**\n * The value is sensitive (a note for staff, a health detail): a UI leaves it out of lists, exports\n * and previews unless a screen asks for it. Hiding it from a user is the database's job.\n */\n readonly sensitive?: boolean;\n}\n\n/**\n * One declaration of a resource: its fields and its identity.\n *\n * `key` names the identity field, or several for a composite key (a junction\n * table keyed on `(team_id, user_id)`). Use {@link keyFields} to read it as\n * a list without caring which form it took.\n */\nexport interface ResourceContract<Row extends DataRow = DataRow> {\n /** Resource name the app addresses, e.g. \"tickets\" or \"public.tickets\". */\n readonly name: string;\n /**\n * Identity field name, or names for a composite key, in key order.\n *\n * Typed `string` (not `keyof Row & string`) on purpose: `keyof Row` is a\n * dependent type that TypeScript checks contravariantly, which would make\n * `ResourceContract<WorkCycleRow>` non-assignable to the erased\n * `ResourceContract<DataRow>` that generic consumers accept. The key is\n * validated against the field schema at runtime instead.\n */\n readonly key: string | readonly string[];\n readonly fields: readonly FieldSchema[];\n /** Optional doc string. */\n readonly description?: string;\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** What one row is called in sentences (\"brand\"), and several (\"brands\") when not `noun` + \"s\". */\n readonly noun?: string;\n readonly nounPlural?: string;\n /** Phantom marker so `Row` is inferable from a contract. */\n readonly __row?: Row;\n}\n\n/** The row type a contract describes (its phantom `__row`), or `DataRow` when it carries none. */\nexport type RowOf<C> = C extends { readonly __row?: infer R } ? (unknown extends R ? DataRow : NonNullable<R>) : DataRow;\n\n/**\n * Declares a resource contract for a row type, keeping the literal contract (field names, key,\n * labelField) and attaching the row type so views can read it with `RowOf`. `labelField` must be\n * one of the row's fields.\n *\n * ```ts\n * export const publicBrands = defineResource<PublicBrandsRow>()({ name: \"public.brands\", key: \"id\", fields: [...] });\n * type Row = RowOf<typeof publicBrands>; // PublicBrandsRow\n * ```\n */\nexport function defineResource<Row extends DataRow>() {\n return <const C extends ResourceContract<Row> & { readonly labelField?: keyof Row & string }>(\n contract: C,\n ): C & { readonly __row?: Row } => contract;\n}\n\n/** What the current user may do with a whole resource. */\nexport interface ResourceAccess {\n readonly read: boolean;\n /** True when at least one field can be updated on rows this user can see. */\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n /** True when this user may add rows. Absent means the provider doesn't say. */\n readonly create?: boolean;\n /** True when this user may delete rows they can see. */\n readonly delete?: boolean;\n /** True when this user may read a row's audit history. */\n readonly history?: boolean;\n /** True when this user may read and add comments on rows they can see. */\n readonly comment?: boolean;\n /** Why `create`, `delete`, `history` or `comment` is false, in one human sentence each. */\n readonly reasons?: {\n readonly create?: string;\n readonly delete?: string;\n readonly history?: string;\n readonly comment?: string;\n };\n}\n\n/**\n * How another resource relates to this one, from the store's foreign keys.\n *\n * - `one`: a field on THIS resource points at one row of `resource`.\n * - `many`: rows of `resource` point at this row through their `field`.\n * - `through`: many rows of `resource`, linked by the junction resource in\n * `through` (a table whose key is two foreign keys).\n */\nexport interface ResourceRelation {\n readonly kind: \"one\" | \"many\" | \"through\";\n /** The related resource. */\n readonly resource: string;\n /**\n * `one`: the field on this resource. `many`: the field on `resource` that\n * holds this row's key. `through`: the junction's field holding this row's key.\n */\n readonly field: string;\n /** For `through`: the junction resource, and its field pointing at `resource`. */\n readonly through?: { readonly resource: string; readonly otherField: string };\n /** True when at most one related row can exist (a unique foreign key). */\n readonly unique?: boolean;\n}\n\n/**\n * The column a provider checks on every update so an edit never silently\n * overwrites someone else's. Only reported when the store itself advances it\n * on every successful update (a trigger such as `moddatetime`), because a\n * column nothing advances detects nothing.\n */\nexport interface VersionField {\n /**\n * The field holding the version. A provider with versioned writes returns\n * each row with its exact version token in this field, as a string, and\n * `expectedVersion` echoes `String(row[field])` back unchanged.\n */\n readonly field: string;\n /**\n * `row`: no column tracks versions, so the token is a fingerprint of the\n * row's values, and `field` is a name the provider adds to each record\n * (it is not one of the resource's fields).\n */\n readonly kind: \"integer\" | \"timestamp\" | \"row\";\n}\n\n/**\n * A resource as `describe()` reports it for the CURRENT user: the contract,\n * plus what this user may do. Fields the user may not read are left out\n * entirely, not marked hidden.\n */\nexport interface ResourceSchema<Row extends DataRow = DataRow> extends ResourceContract<Row> {\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n readonly access: ResourceAccess;\n /** Present only when writes can be version-checked. */\n readonly version?: VersionField;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** Resources this one links to or is linked from. Only ones this user may see. */\n readonly relations?: readonly ResourceRelation[];\n /** Fields the user may set when creating a row. Absent when creating isn't allowed. */\n readonly createFields?: readonly string[];\n /** Row actions this user may run: each calls the app's own function on one row. */\n readonly actions?: readonly RowAction[];\n}\n\n/** A named operation on one row, carried out by the app's own database function. */\nexport interface RowAction {\n readonly name: string;\n readonly label: string;\n /** Ask before running, with this question. */\n readonly confirm?: string;\n /** One sentence on what it does. */\n readonly description?: string;\n}\n\n/** A comment on a record. */\nexport interface RecordComment {\n readonly id: string;\n /** The signed-in user who wrote it (the token's `sub`). */\n readonly author: string;\n readonly body: string;\n /** ISO 8601, as the store recorded it. */\n readonly createdAt: string;\n}\n\n/** One entry of `listResources()`: enough to draw a sidebar. */\nexport interface ResourceSummary {\n readonly name: string;\n readonly label?: string;\n readonly description?: string;\n readonly access: ResourceAccess;\n}\n\n/** Filter operators a provider may support. Mirrors `FilterParam[\"operator\"]`. */\nexport type FilterOperator =\n | \"eq\"\n | \"neq\"\n | \"gt\"\n | \"lt\"\n | \"gte\"\n | \"lte\"\n | \"contains\"\n | \"in\"\n | \"between\"\n | \"is_null\"\n | \"is_not_null\";\n\n/**\n * What a provider can do. A UI hides any control the provider cannot serve,\n * instead of letting it error (DATA-STUDIO.md decision 9).\n */\nexport interface ProviderCapabilities {\n /** Server-side text search across fields. */\n readonly search: boolean;\n /** Server-side sort. */\n readonly sort: boolean;\n /** Server-side filter operators. Empty means no server filtering. */\n readonly filterOperators: readonly FilterOperator[];\n /** `updateMany` / `deleteMany` in one transaction. */\n readonly bulkWrites: boolean;\n /** Updates honour `expectedVersion` and reject stale writes. */\n readonly versionedWrites: boolean;\n /** Records may be keyed by more than one field. */\n readonly compositeKeys: boolean;\n /** Server-side sort by several fields at once (`ListParams.sorts`). */\n readonly multiSort?: boolean;\n /** `create` and `deleteOne` are served, subject to each resource's access. */\n readonly create?: boolean;\n readonly delete?: boolean;\n /** `history` is served, subject to each resource's access. */\n readonly history?: boolean;\n /** `importRows` is served, with a dry run. */\n readonly import?: boolean;\n /** `undo` is served. */\n readonly undo?: boolean;\n /** `runAction` is served. */\n readonly actions?: boolean;\n /** `comments` and `addComment` are served. */\n readonly comments?: boolean;\n /**\n * The most rows one `getList` page may ask for. A request for more is\n * refused (it is not cut short, which would shift later page boundaries),\n * so a client that wants every row must page at this size or less.\n */\n readonly maxPerPage?: number;\n /**\n * A delete moves the record to a recycle bin (it can be restored) instead\n * of removing it. Asked per resource: `capabilities(resource)`.\n */\n readonly softDelete?: boolean;\n /**\n * `create`, `update` and `deleteOne` honour `keepalive: true` in their\n * params (e.g. `fetch(url, { keepalive: true })`), so a write sent while\n * the page unloads still reaches the server. Without it, closing the tab\n * while an optimistic or undoable write is being sent shows the browser's\n * \"Leave site?\" prompt.\n */\n readonly keepaliveWrites?: boolean;\n /**\n * `getList` serves cursor (keyset) paging: `pagination.cursor` in,\n * `nextCursor` out. Pages stay correct while rows are added or removed,\n * and a deep page costs no more than the first.\n */\n readonly cursorPagination?: boolean;\n /**\n * `subscribe` reports changes to this resource (asked per resource:\n * `capabilities(resource)`), so `live` lists and records refresh when\n * someone else changes them.\n */\n readonly realtime?: boolean;\n}\n\n/** One audit record, as committed alongside the edit it describes. */\nexport interface AuditEntry {\n readonly id: string;\n /** ISO 8601 timestamp, as the store recorded it. */\n readonly occurredAt: string;\n /** The signed-in user who made the edit (the token's `sub`). */\n readonly actor: string | null;\n readonly resource: string;\n /** The record's key, field name → value. */\n readonly key: DataRow;\n /** `run` is a row action; `rowAction` names it. */\n readonly action: \"create\" | \"update\" | \"delete\" | \"run\";\n /** For `run`: which row action. */\n readonly rowAction?: string;\n /** Values of the changed fields before the edit. */\n readonly before: DataRow | null;\n /** Values of the changed fields after the edit. */\n readonly after: DataRow | null;\n}\n"]}
1
+ {"version":3,"sources":["../src/schema/types.ts"],"names":[],"mappings":";AA+IO,SAAS,cAAA,GAAsC;AACpD,EAAA,OAAO,CACL,QAAA,KACiC,QAAA;AACrC","file":"chunk-YDMKMNDS.js","sourcesContent":["// ---------------------------------------------------------------------------\n// The one schema model (docs/DATA-STUDIO.md decisions 11, 12, 13, 30)\n//\n// Promoted from @marktiderman/genesis-switchboard, which keeps deprecated\n// aliases for one deprecation window. Everything here is a type or a pure\n// helper with no React, no runtime dependency and no I/O, so a server, an\n// edge function or the switchboard can import it without pulling in the\n// React half of this package.\n// ---------------------------------------------------------------------------\n\nimport type { FieldType as WidgetHint } from \"../form-types\";\n\nexport type { WidgetHint };\n\n/**\n * Portable storage type of a field — what kind of value the store holds,\n * independent of how a UI should edit it. The exact native type, when the\n * store reports one, is on {@link FieldSchema.dbType}.\n *\n * Exactly the six types the switchboard shipped as `FieldType`, so existing\n * exhaustive maps over it keep compiling. Finer distinctions (date versus\n * timestamp, enum, uuid) live in `dbType` and `widget`, not here.\n */\nexport type StorageType = \"string\" | \"number\" | \"boolean\" | \"datetime\" | \"json\" | \"relation\";\n\n/** A canonical, provider-agnostic row. Keys are field names from the schema. */\nexport type DataRow = Record<string, unknown>;\n\n/**\n * What the CURRENT user may do with one field. Reported by a provider's\n * `describe()`; never inferred in the browser.\n *\n * `read: false` means the value is never sent to this user, so the column\n * must not render at all (an answer key, a payout amount). `update: false`\n * with `read: true` renders the column read-only.\n */\nexport interface FieldPermissions {\n readonly read: boolean;\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n}\n\n/** A foreign-key style link from this field to another resource's field. */\nexport interface FieldReference {\n readonly resource: string;\n readonly field: string;\n}\n\nexport interface FieldSchema {\n /** Canonical field name in the resource's shape (provider-agnostic). */\n readonly name: string;\n /** Portable storage type. */\n readonly type: StorageType;\n /** True when a row may omit this field. */\n readonly optional?: boolean;\n /**\n * True when the field holds an ORDERED LIST of `type` values (e.g. a\n * multi-relation like `deps`/`serves`). Promotion emits a Postgres ARRAY\n * column (`<base>[]`) instead of a lossy scalar, so the cardinality survives\n * L1→L3 (CMT-1742-014).\n */\n readonly array?: boolean;\n /** Human note (surfaces in describe()/drift reports). */\n readonly description?: string;\n /** Human label, e.g. \"Date of birth\". Absent means a UI derives one from `name`. */\n readonly label?: string;\n /** The store's exact type, e.g. `timestamp with time zone` or `public.status`. */\n readonly dbType?: string;\n /** Which control fits this field. A hint: a UI may still choose another. */\n readonly widget?: WidgetHint;\n /** True when the store accepts null for this field. */\n readonly nullable?: boolean;\n /** True when the store fills the field itself on insert. */\n readonly hasDefault?: boolean;\n /** True when the store computes the field; it is never written. */\n readonly generated?: boolean;\n /** Allowed values, for enum-like fields. */\n readonly enumValues?: readonly string[];\n /** The resource and field this one points at, when it is a link. */\n readonly references?: FieldReference;\n /** The current user's rights on this field, when a provider reports them. */\n readonly permissions?: FieldPermissions;\n /**\n * The server owns this field (a status it derives, a total, an audit stamp): clients never write\n * it, so a UI shows it read-only. Declared once (`@genesis {\"readonly\": true}`); the database's\n * own guards still enforce it.\n */\n readonly readOnly?: boolean;\n /**\n * The value is sensitive (a note for staff, a health detail): a UI leaves it out of lists, exports\n * and previews unless a screen asks for it. Hiding it from a user is the database's job.\n */\n readonly sensitive?: boolean;\n}\n\n/**\n * One declaration of a resource: its fields and its identity.\n *\n * `key` names the identity field, or several for a composite key (a junction\n * table keyed on `(team_id, user_id)`). Use {@link keyFields} to read it as\n * a list without caring which form it took.\n */\nexport interface ResourceContract<Row extends DataRow = DataRow> {\n /** Resource name the app addresses, e.g. \"tickets\" or \"public.tickets\". */\n readonly name: string;\n /**\n * Identity field name, or names for a composite key, in key order.\n *\n * Typed `string` (not `keyof Row & string`) on purpose: `keyof Row` is a\n * dependent type that TypeScript checks contravariantly, which would make\n * `ResourceContract<WorkCycleRow>` non-assignable to the erased\n * `ResourceContract<DataRow>` that generic consumers accept. The key is\n * validated against the field schema at runtime instead.\n */\n readonly key: string | readonly string[];\n readonly fields: readonly FieldSchema[];\n /** Optional doc string. */\n readonly description?: string;\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** What one row is called in sentences (\"brand\"), and several (\"brands\") when not `noun` + \"s\". */\n readonly noun?: string;\n readonly nounPlural?: string;\n /** Phantom marker so `Row` is inferable from a contract. */\n readonly __row?: Row;\n}\n\n/** The row type a contract describes (its phantom `__row`), or `DataRow` when it carries none. */\nexport type RowOf<C> = C extends { readonly __row?: infer R } ? (unknown extends R ? DataRow : NonNullable<R>) : DataRow;\n\n/**\n * Declares a resource contract for a row type, keeping the literal contract (field names, key,\n * labelField) and attaching the row type so views can read it with `RowOf`. `labelField` must be\n * one of the row's fields.\n *\n * ```ts\n * export const publicBrands = defineResource<PublicBrandsRow>()({ name: \"public.brands\", key: \"id\", fields: [...] });\n * type Row = RowOf<typeof publicBrands>; // PublicBrandsRow\n * ```\n */\nexport function defineResource<Row extends DataRow>() {\n return <const C extends ResourceContract<Row> & { readonly labelField?: keyof Row & string }>(\n contract: C,\n ): C & { readonly __row?: Row } => contract;\n}\n\n/** What the current user may do with a whole resource. */\nexport interface ResourceAccess {\n readonly read: boolean;\n /** True when at least one field can be updated on rows this user can see. */\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n /** True when this user may add rows. Absent means the provider doesn't say. */\n readonly create?: boolean;\n /** True when this user may delete rows they can see. */\n readonly delete?: boolean;\n /** True when this user may read a row's audit history. */\n readonly history?: boolean;\n /** True when this user may read and add comments on rows they can see. */\n readonly comment?: boolean;\n /** Why `create`, `delete`, `history` or `comment` is false, in one human sentence each. */\n readonly reasons?: {\n readonly create?: string;\n readonly delete?: string;\n readonly history?: string;\n readonly comment?: string;\n };\n}\n\n/**\n * How another resource relates to this one, from the store's foreign keys.\n *\n * - `one`: a field on THIS resource points at one row of `resource`.\n * - `many`: rows of `resource` point at this row through their `field`.\n * - `through`: many rows of `resource`, linked by the junction resource in\n * `through` (a table whose key is two foreign keys).\n */\nexport interface ResourceRelation {\n readonly kind: \"one\" | \"many\" | \"through\";\n /** The related resource. */\n readonly resource: string;\n /**\n * `one`: the field on this resource. `many`: the field on `resource` that\n * holds this row's key. `through`: the junction's field holding this row's key.\n */\n readonly field: string;\n /** For `through`: the junction resource, and its field pointing at `resource`. */\n readonly through?: { readonly resource: string; readonly otherField: string };\n /** True when at most one related row can exist (a unique foreign key). */\n readonly unique?: boolean;\n}\n\n/**\n * The column a provider checks on every update so an edit never silently\n * overwrites someone else's. Only reported when the store itself advances it\n * on every successful update (a trigger such as `moddatetime`), because a\n * column nothing advances detects nothing.\n */\nexport interface VersionField {\n /**\n * The field holding the version. A provider with versioned writes returns\n * each row with its exact version token in this field, as a string, and\n * `expectedVersion` echoes `String(row[field])` back unchanged.\n */\n readonly field: string;\n /**\n * `row`: no column tracks versions, so the token is a fingerprint of the\n * row's values, and `field` is a name the provider adds to each record\n * (it is not one of the resource's fields).\n */\n readonly kind: \"integer\" | \"timestamp\" | \"row\";\n}\n\n/**\n * A resource as `describe()` reports it for the CURRENT user: the contract,\n * plus what this user may do. Fields the user may not read are left out\n * entirely, not marked hidden.\n */\nexport interface ResourceSchema<Row extends DataRow = DataRow> extends ResourceContract<Row> {\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n readonly access: ResourceAccess;\n /** Present only when writes can be version-checked. */\n readonly version?: VersionField;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** Resources this one links to or is linked from. Only ones this user may see. */\n readonly relations?: readonly ResourceRelation[];\n /** Fields the user may set when creating a row. Absent when creating isn't allowed. */\n readonly createFields?: readonly string[];\n /** Row actions this user may run: each calls the app's own function on one row. */\n readonly actions?: readonly RowAction[];\n}\n\n/** A named operation on one row, carried out by the app's own database function. */\nexport interface RowAction {\n readonly name: string;\n readonly label: string;\n /** Ask before running, with this question. */\n readonly confirm?: string;\n /** One sentence on what it does. */\n readonly description?: string;\n}\n\n/** A comment on a record. */\nexport interface RecordComment {\n readonly id: string;\n /** The signed-in user who wrote it (the token's `sub`). */\n readonly author: string;\n readonly body: string;\n /** ISO 8601, as the store recorded it. */\n readonly createdAt: string;\n}\n\n/** One entry of `listResources()`: enough to draw a sidebar. */\nexport interface ResourceSummary {\n readonly name: string;\n readonly label?: string;\n readonly description?: string;\n readonly access: ResourceAccess;\n}\n\n/** Filter operators a provider may support. Mirrors `FilterParam[\"operator\"]`. */\nexport type FilterOperator =\n | \"eq\"\n | \"neq\"\n | \"gt\"\n | \"lt\"\n | \"gte\"\n | \"lte\"\n | \"contains\"\n | \"in\"\n | \"between\"\n | \"is_null\"\n | \"is_not_null\";\n\n/**\n * What a provider can do. A UI hides any control the provider cannot serve,\n * instead of letting it error (DATA-STUDIO.md decision 9).\n */\nexport interface ProviderCapabilities {\n /** Server-side text search across fields. */\n readonly search: boolean;\n /** Server-side sort. */\n readonly sort: boolean;\n /** Server-side filter operators. Empty means no server filtering. */\n readonly filterOperators: readonly FilterOperator[];\n /** `updateMany` / `deleteMany` in one transaction. */\n readonly bulkWrites: boolean;\n /** Updates honour `expectedVersion` and reject stale writes. */\n readonly versionedWrites: boolean;\n /**\n * The version field the resource's writes are checked against, asked per\n * resource (`capabilities(resource)`). Present only with `versionedWrites`.\n * The Genesis write hooks send `String(row[version.field])` from the row\n * they last read as `expectedVersion`, so an edit made on a stale copy is\n * refused as a `conflict` instead of overwriting someone else's.\n */\n readonly version?: VersionField;\n /** Records may be keyed by more than one field. */\n readonly compositeKeys: boolean;\n /** Server-side sort by several fields at once (`ListParams.sorts`). */\n readonly multiSort?: boolean;\n /** `create` and `deleteOne` are served, subject to each resource's access. */\n readonly create?: boolean;\n readonly delete?: boolean;\n /** `history` is served, subject to each resource's access. */\n readonly history?: boolean;\n /** `importRows` is served, with a dry run. */\n readonly import?: boolean;\n /** `undo` is served. */\n readonly undo?: boolean;\n /** `runAction` is served. */\n readonly actions?: boolean;\n /** `comments` and `addComment` are served. */\n readonly comments?: boolean;\n /**\n * The most rows one `getList` page may ask for. A request for more is\n * refused (it is not cut short, which would shift later page boundaries),\n * so a client that wants every row must page at this size or less.\n */\n readonly maxPerPage?: number;\n /**\n * A delete moves the record to a recycle bin (it can be restored) instead\n * of removing it. Asked per resource: `capabilities(resource)`.\n */\n readonly softDelete?: boolean;\n /**\n * `create`, `update` and `deleteOne` honour `keepalive: true` in their\n * params (e.g. `fetch(url, { keepalive: true })`), so a write sent while\n * the page unloads still reaches the server. Without it, closing the tab\n * while an optimistic or undoable write is being sent shows the browser's\n * \"Leave site?\" prompt.\n */\n readonly keepaliveWrites?: boolean;\n /**\n * `getList` serves cursor (keyset) paging: `pagination.cursor` in,\n * `nextCursor` out. Pages stay correct while rows are added or removed,\n * and a deep page costs no more than the first.\n */\n readonly cursorPagination?: boolean;\n /**\n * `subscribe` reports changes to this resource (asked per resource:\n * `capabilities(resource)`), so `live` lists and records refresh when\n * someone else changes them.\n */\n readonly realtime?: boolean;\n}\n\n/** One audit record, as committed alongside the edit it describes. */\nexport interface AuditEntry {\n readonly id: string;\n /** ISO 8601 timestamp, as the store recorded it. */\n readonly occurredAt: string;\n /** The signed-in user who made the edit (the token's `sub`). */\n readonly actor: string | null;\n readonly resource: string;\n /** The record's key, field name → value. */\n readonly key: DataRow;\n /** `run` is a row action; `rowAction` names it. */\n readonly action: \"create\" | \"update\" | \"delete\" | \"run\";\n /** For `run`: which row action. */\n readonly rowAction?: string;\n /** Values of the changed fields before the edit. */\n readonly before: DataRow | null;\n /** Values of the changed fields after the edit. */\n readonly after: DataRow | null;\n}\n"]}
@@ -1,6 +1,8 @@
1
- import { capabilitiesQueryKey } from './chunk-LGTXQTHA.js';
2
- import { resourceKeys } from './chunk-7PUFVNPB.js';
1
+ import { capabilitiesQueryKey } from './chunk-2VJQVAJD.js';
3
2
  import { pageWindow } from './chunk-AJGVLF37.js';
3
+ import { resourceKeys } from './chunk-7PUFVNPB.js';
4
+ import { patchCachedRow } from './chunk-AUVKRXRC.js';
5
+ import { reportError } from './chunk-VFT6QKZW.js';
4
6
 
5
7
  // src/hooks/mutation-mode.ts
6
8
  var DEFAULT_UNDO_DELAY_MS = 5e3;
@@ -66,6 +68,14 @@ function cachedRecord(queryClient, resource, id) {
66
68
  for (const [key, value] of queryClient.getQueriesData({ queryKey: resourceKeys(resource).details })) {
67
69
  if (isDetailKeyFor(key, resource, id) && value && typeof value === "object") return value;
68
70
  }
71
+ return cachedRow(queryClient, resource, id, false);
72
+ }
73
+ function cachedRow(queryClient, resource, id, details = true) {
74
+ if (details) {
75
+ for (const [key, value] of queryClient.getQueriesData({ queryKey: resourceKeys(resource).details })) {
76
+ if (isDetailKeyFor(key, resource, id) && key[3] === void 0 && value && typeof value === "object") return value;
77
+ }
78
+ }
69
79
  for (const [key, value] of queryClient.getQueriesData({ queryKey: [resource] })) {
70
80
  for (const list of listsIn(key, value)) {
71
81
  const found = list.data.find((row) => sameId(row.id, id));
@@ -84,6 +94,7 @@ function registryFor(queryClient) {
84
94
  patches: [],
85
95
  writes: [],
86
96
  rowTails: /* @__PURE__ */ new Map(),
97
+ rowVersions: /* @__PURE__ */ new Map(),
87
98
  produced: /* @__PURE__ */ new WeakSet(),
88
99
  writing: false
89
100
  };
@@ -387,11 +398,87 @@ async function providerServesUndo(queryClient, provider, resource) {
387
398
  return false;
388
399
  }
389
400
  }
401
+ function cachedVersionField(queryClient, provider, resource) {
402
+ return queryClient.getQueryData(capabilitiesQueryKey(provider, resource))?.version?.field;
403
+ }
404
+ function versionToken(row, field) {
405
+ const value = row?.[field];
406
+ return value == null ? void 0 : String(value);
407
+ }
408
+ var warnedNoVersion = /* @__PURE__ */ new Set();
409
+ function cachedVersion(queryClient, provider, resource, id) {
410
+ const field = cachedVersionField(queryClient, provider, resource);
411
+ return field ? versionToken(cachedRow(queryClient, resource, id), field) : void 0;
412
+ }
413
+ function recordNewVersion(queryClient, resource, id, field, record) {
414
+ if (!record || typeof record !== "object") return void 0;
415
+ const value = record[field];
416
+ if (value == null) return void 0;
417
+ patchCachedRow(queryClient, resource, { id, [field]: value });
418
+ return String(value);
419
+ }
420
+ function releaseRow(reg, rowKey) {
421
+ if (!reg.rowTails.has(rowKey) && !reg.writes.some((w) => w.rowKey === rowKey)) reg.rowVersions.delete(rowKey);
422
+ }
390
423
  var DROPPED_WRITE_MESSAGE = "This change was not saved: it was made on top of an earlier change that was undone or failed. Please make it again.";
391
424
  async function executeWrite(args) {
392
- const { queryClient, provider, resource, kind, id, mode, send, committed, failedLater } = args;
425
+ const { queryClient, provider, resource, kind, id, mode, committed, failedLater } = args;
426
+ const reg = registryFor(queryClient);
427
+ const hasRow = kind !== "create" && id != null;
428
+ const rowKey = hasRow ? `${resource}\0${String(id)}` : void 0;
429
+ const seen = hasRow ? args.base ?? cachedRow(queryClient, resource, id) : void 0;
430
+ const behind = rowKey !== void 0 && (reg.rowTails.has(rowKey) || reg.writes.some((w) => w.rowKey === rowKey && w.state !== "done"));
431
+ const versioned = hasRow && !!provider.capabilities;
432
+ const send = async (context) => {
433
+ let field;
434
+ if (versioned) {
435
+ if (!queryClient.getQueryData(capabilitiesQueryKey(provider, resource))) {
436
+ await queryClient.fetchQuery(CAPABILITIES_QUERY(provider, resource)).catch(() => void 0);
437
+ }
438
+ field = cachedVersionField(queryClient, provider, resource);
439
+ }
440
+ let expectedVersion = args.expectedVersion !== void 0 ? (behind ? reg.rowVersions.get(rowKey) : void 0) ?? args.expectedVersion : void 0;
441
+ if (field && expectedVersion === void 0) {
442
+ expectedVersion = (behind ? reg.rowVersions.get(rowKey) : void 0) ?? versionToken(seen, field);
443
+ if (seen && !(field in seen) && !warnedNoVersion.has(resource)) {
444
+ warnedNoVersion.add(resource);
445
+ reportError(
446
+ new Error(
447
+ `"${resource}" has a version (${field}), but its rows as read here don't carry it, so its writes go unchecked. Read the version column (add it to the resource's select or source view).`
448
+ ),
449
+ { source: "core:versioned-writes", tags: { resource } }
450
+ );
451
+ }
452
+ }
453
+ const result = await args.send(expectedVersion === void 0 ? context : { ...context, expectedVersion });
454
+ if (field && kind === "update") {
455
+ const next = recordNewVersion(queryClient, resource, id, field, result.record);
456
+ if (next !== void 0) reg.rowVersions.set(rowKey, next);
457
+ else void invalidateResource(queryClient, resource);
458
+ }
459
+ return result;
460
+ };
393
461
  if (mode === "pessimistic") {
394
- const { record } = await send({ data: args.data, keepalive: false });
462
+ const run = () => send({ data: args.data, keepalive: false });
463
+ let sending;
464
+ if (rowKey) {
465
+ const previous = reg.rowTails.get(rowKey);
466
+ sending = previous ? previous.then(run, run) : run();
467
+ const tail = sending.then(
468
+ () => {
469
+ },
470
+ () => {
471
+ }
472
+ );
473
+ reg.rowTails.set(rowKey, tail);
474
+ void tail.finally(() => {
475
+ if (reg.rowTails.get(rowKey) === tail) reg.rowTails.delete(rowKey);
476
+ releaseRow(reg, rowKey);
477
+ });
478
+ } else {
479
+ sending = run();
480
+ }
481
+ const { record } = await sending;
395
482
  await committed(record);
396
483
  return { status: "committed", record };
397
484
  }
@@ -399,8 +486,6 @@ async function executeWrite(args) {
399
486
  if (provider.capabilities && !queryClient.getQueryData(capabilitiesQueryKey(provider, resource))) {
400
487
  void queryClient.prefetchQuery(CAPABILITIES_QUERY(provider, resource));
401
488
  }
402
- const reg = registryFor(queryClient);
403
- const hasRow = kind !== "create" && id != null;
404
489
  const data = args.data ? { ...args.data } : void 0;
405
490
  let patch;
406
491
  if (hasRow && kind === "update" && data) patch = { resource, id, kind: "update", data, before: /* @__PURE__ */ new Map() };
@@ -418,7 +503,7 @@ async function executeWrite(args) {
418
503
  provider,
419
504
  resource,
420
505
  kind,
421
- rowKey: hasRow ? `${resource}\0${String(id)}` : void 0,
506
+ rowKey,
422
507
  patch,
423
508
  data: kind === "update" ? data : void 0,
424
509
  baseline: hasRow ? cachedRecord(queryClient, resource, id) : void 0,
@@ -440,6 +525,7 @@ async function executeWrite(args) {
440
525
  if (at >= 0) reg.writes.splice(at, 1);
441
526
  untrack(write);
442
527
  endPending(reg, resource);
528
+ if (rowKey) releaseRow(reg, rowKey);
443
529
  };
444
530
  const sendNow = async (keepalive) => {
445
531
  if (write.state !== "queued") return;
@@ -477,6 +563,7 @@ async function executeWrite(args) {
477
563
  reg.rowTails.set(key, next);
478
564
  void next.finally(() => {
479
565
  if (reg.rowTails.get(key) === next) reg.rowTails.delete(key);
566
+ releaseRow(reg, key);
480
567
  });
481
568
  };
482
569
  write.flush = (unloading = false) => {
@@ -579,6 +666,6 @@ async function executeWrite(args) {
579
666
  return { status: "applied" };
580
667
  }
581
668
 
582
- export { DEFAULT_UNDO_DELAY_MS, DROPPED_WRITE_MESSAGE, cachedRecord, dropPendingWrites, executeWrite, flushPendingWrites, invalidateResource, pendingWriteCount, providerServesUndo, sameValue };
583
- //# sourceMappingURL=chunk-6WV6ST67.js.map
584
- //# sourceMappingURL=chunk-6WV6ST67.js.map
669
+ export { DEFAULT_UNDO_DELAY_MS, DROPPED_WRITE_MESSAGE, cachedRecord, cachedVersion, dropPendingWrites, executeWrite, flushPendingWrites, invalidateResource, pendingWriteCount, providerServesUndo, sameValue };
670
+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,UAAA,MAAA,GAAS,IAAA;AACT,UAAA,IAAI,EAAA,GAAK,IAAA;AACT,UAAA,IAAI;AACF,YAAA,MAAM,QAAA,CAAS,IAAA,CAAM,QAAA,EAAU,EAAE,SAAS,CAAA;AAAA,UAC5C,SAAS,KAAA,EAAO;AACd,YAAA,EAAA,GAAK,KAAA;AACL,YAAA,WAAA,CAAY,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,UAC5B;AACA,UAAA,MAAM,kBAAA,CAAmB,aAAa,QAAQ,CAAA;AAC9C,UAAA,OAAO,EAAA;AAAA,QACT;AAAA,OACD,CAAA;AAAA,IACH,CAAC,CAAA;AACD,IAAA,OAAO,EAAE,QAAQ,SAAA,EAAU;AAAA,EAC7B;AAGA,EAAA,KAAA,CAAM,KAAA,GAAQ,SAAA;AACd,EAAA,KAAA,GAAQ,UAAA,CAAW,MAAM,KAAA,CAAM,KAAA,IAAS,OAAO,CAAA;AAE/C,EAAA,IAAA,CAAK,UAAA,GAAa;AAAA,IAChB,QAAA;AAAA,IACA,IAAA;AAAA,IACA,EAAA;AAAA,IACA,QAAA,EAAU,OAAA;AAAA,IACV,OAAA;AAAA,IACA,MAAA,EAAQ,MAAM,KAAA,CAAM,KAAA,EAAM;AAAA,IAC1B,MAAM,YAAY;AAChB,MAAA,IAAI,KAAA,CAAM,SAAS,OAAO,IAAA;AAC1B,MAAA,IAAI,KAAA,CAAM,KAAA,KAAU,SAAA,EAAW,OAAO,KAAA;AACtC,MAAA,MAAA,EAAO;AACP,MAAA,QAAA,CAAS,KAAK,KAAK,CAAA;AACnB,MAAA,KAAK,kBAAA,CAAmB,aAAa,QAAQ,CAAA;AAC7C,MAAA,WAAA,CAAY,MAAS,CAAA;AACrB,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,GACD,CAAA;AAED,EAAA,OAAO,EAAE,QAAQ,SAAA,EAAU;AAC7B","file":"chunk-YNXLPOAB.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Mutation modes — when a write reaches the cache, and when the provider.\n//\n// - `pessimistic` (default): wait for the provider, then refetch. Today's\n// behaviour.\n// - `optimistic`: patch the TanStack Query cache at once, send the write, and\n// put the cache back (and report the error) if it fails.\n// - `undoable`: patch the cache at once and offer an undo (`onUndoable`);\n// the write is sent after a delay unless undone. A provider that serves\n// `undo` (capabilities `undo: true`) gets the write at once instead, and\n// the undo asks the provider to reverse it.\n//\n// Core has no UI: the undo toast is the caller's (`onUndoable`). genesis-ui's\n// ResourceForm and ResourcePage show a sonner toast.\n//\n// Pending writes belong to the QueryClient, not to the hook that started\n// them: a form that closes on success can still be undone from its toast.\n// ---------------------------------------------------------------------------\n\nimport type { QueryClient, QueryKey } from \"@tanstack/react-query\";\nimport type { BaseRecord, DataProvider, Identifier, ListResult } from \"../provider/types\";\nimport type { AuditEntry, ProviderCapabilities } from \"../schema/types\";\nimport { capabilitiesQueryKey } from \"./use-capabilities\";\nimport { resourceKeys } from \"../query-keys\";\nimport { pageWindow, type PageWindow } from \"./page-window\";\nimport { patchCachedRow } from \"./live-cache\";\nimport { reportError } from \"../errors\";\n\nexport type MutationMode = \"pessimistic\" | \"optimistic\" | \"undoable\";\n\n/** How long an `undoable` write waits for an undo before it is sent. */\nexport const DEFAULT_UNDO_DELAY_MS = 5000;\n\n/** An undoable write, as handed to `onUndoable` so a UI can offer the undo. */\nexport interface UndoableWrite {\n resource: string;\n kind: \"create\" | \"update\" | \"delete\";\n /** The record's id; absent for a create (it has none until it is sent). */\n id?: Identifier;\n /**\n * - `delay`: the write has not been sent. `undo()` discards it; `commit()`\n * sends it now instead of waiting.\n * - `provider`: the write was sent at once, because the provider serves\n * `undo`. `undo()` asks the provider to reverse it; `commit()` does\n * nothing.\n */\n strategy: \"delay\" | \"provider\";\n /** How long the undo is offered, in ms (the toast's duration). */\n delayMs: number;\n /**\n * Take the write back. Resolves true when it was undone (or will never be\n * sent), false when it could not be: already sent under `delay` (the\n * window closed, it was committed, a later write on the same record sent\n * it first, or the page unloaded), already undone, or the provider's undo\n * failed (reported through `onError`). Works after the hook that made the\n * write has unmounted. Safe to call more than once.\n */\n undo: () => Promise<boolean>;\n /** Send a `delay` write now. */\n commit: () => void;\n}\n\nexport interface MutationModeOptions {\n /** Default `\"pessimistic\"`. */\n mutationMode?: MutationMode;\n /** How long an `undoable` write waits, in ms. Default 5000. */\n undoDelayMs?: number;\n /** Called with every `undoable` write, to show an undo control. */\n onUndoable?: (write: UndoableWrite) => void;\n}\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nfunction sameId(a: unknown, b: unknown): boolean {\n return a != null && b != null && String(a) === String(b);\n}\n\nfunction isListResult(value: unknown): value is ListResult<BaseRecord> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Array.isArray((value as { data?: unknown }).data)\n );\n}\n\n/** TanStack infinite-query data whose pages are list results. */\ninterface InfiniteLists {\n pages: unknown[];\n pageParams: unknown[];\n}\n\nfunction isInfiniteLists(value: unknown): value is InfiniteLists {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Array.isArray((value as { pages?: unknown }).pages) &&\n Array.isArray((value as { pageParams?: unknown }).pageParams)\n );\n}\n\n/**\n * Runs `fn` on every list a cache entry holds: a `[resource, \"list\", …]`\n * entry is one list (keyed by its query hash); a `[resource, \"infinite\",\n * …]` entry (useInfiniteResource) is one list per loaded page (keyed\n * `hash#page`). Returns the entry rebuilt, or the same object when `fn`\n * changed nothing. Rows added or removed change every page's `total`,\n * since each page reports the whole list's count.\n */\nfunction mapLists(\n key: QueryKey,\n hash: string,\n value: unknown,\n fn: (list: ListResult<BaseRecord>, hash: string) => ListResult<BaseRecord>,\n): unknown {\n if (key[1] === \"list\") return isListResult(value) ? fn(value, hash) : value;\n if (key[1] !== \"infinite\" || !isInfiniteLists(value)) return value;\n let changed = false;\n // Rows added or removed across pages, applied to every page's count: a\n // page after the first may report -1 (not counted), so its own total\n // can't carry the change.\n let rowDelta = 0;\n const pages = value.pages.map((page, i) => {\n if (!isListResult(page)) return page;\n const next = fn(page, `${hash}#${i}`);\n if (next !== page) {\n changed = true;\n rowDelta += next.data.length - page.data.length;\n }\n return next;\n });\n if (!changed) return value;\n const withTotals = value.pages.map((orig, i) => {\n const page = pages[i];\n if (!isListResult(page) || !isListResult(orig) || typeof orig.total !== \"number\") return page;\n return { ...page, total: orig.total < 0 ? orig.total : Math.max(0, orig.total + rowDelta) };\n });\n return { ...value, pages: withTotals };\n}\n\n/** Every list result a cache entry holds (see `mapLists`). */\nfunction listsIn(key: QueryKey, value: unknown): ListResult<BaseRecord>[] {\n if (key[1] === \"list\") return isListResult(value) ? [value] : [];\n if (key[1] === \"infinite\" && isInfiniteLists(value)) return value.pages.filter(isListResult);\n return [];\n}\n\nfunction isDetailKeyFor(key: QueryKey, resource: string, id: Identifier): boolean {\n return key[0] === resource && key[1] === \"detail\" && sameId(key[2], id);\n}\n\n/** Structural equality for row values (JSON-like data, Dates). */\nexport function sameValue(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a)) {\n const other = b as unknown[];\n return a.length === other.length && a.every((item, i) => sameValue(item, other[i]));\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every(\n (k) => Object.prototype.hasOwnProperty.call(b, k) &&\n sameValue((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n );\n}\n\nfunction asError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\n/** The record as the cache has it now, from a detail entry or any list. */\nexport function cachedRecord(\n queryClient: QueryClient,\n resource: string,\n id: Identifier,\n): BaseRecord | undefined {\n for (const [key, value] of queryClient.getQueriesData<unknown>({ queryKey: resourceKeys(resource).details })) {\n if (isDetailKeyFor(key, resource, id) && value && typeof value === \"object\") return value as BaseRecord;\n }\n return cachedRow(queryClient, resource, id, false);\n}\n\n/**\n * The record as a whole row: a detail read without a `select` (one with a\n * `select` is reshaped, and isn't kept current after writes), else any list.\n */\nfunction cachedRow(queryClient: QueryClient, resource: string, id: Identifier, details = true): BaseRecord | undefined {\n if (details) {\n for (const [key, value] of queryClient.getQueriesData<unknown>({ queryKey: resourceKeys(resource).details })) {\n if (isDetailKeyFor(key, resource, id) && key[3] === undefined && value && typeof value === \"object\") return value as BaseRecord;\n }\n }\n for (const [key, value] of queryClient.getQueriesData<unknown>({ queryKey: [resource] })) {\n for (const list of listsIn(key, value)) {\n const found = list.data.find((row) => sameId(row.id, id));\n if (found) return found;\n }\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// The registry — one per QueryClient\n//\n// Holds every optimistic/undoable write not yet settled, and the cache\n// patches they made. Patches are re-applied to any `[resource, \"list\" |\n// \"infinite\" | \"detail\", …]` data that arrives while they are pending (a refetch, a new\n// page, filter or search), so a deleted row stays gone and an edit stays\n// shown until the write settles. Because of that, refetching is always safe\n// and nothing waits for pending writes before invalidating.\n// ---------------------------------------------------------------------------\n\n/** One record's change, kept applied to the cache while its write is pending. */\ninterface Patch {\n resource: string;\n id: Identifier;\n kind: \"update\" | \"delete\";\n /** An update's values; the same object its write sends, so a rebase changes both. */\n data?: Record<string, unknown>;\n /** Per cache entry (query hash): the row just before this patch, and its list index. */\n before: Map<string, { row: BaseRecord; index: number }>;\n}\n\n/** One optimistic or undoable write that has not settled. */\ninterface Tracked {\n seq: number;\n queryClient: QueryClient;\n provider: DataProvider;\n resource: string;\n kind: \"create\" | \"update\" | \"delete\";\n /** `resource` + id: writes on the same record are sent in order. */\n rowKey?: string;\n patch?: Patch;\n /** Row-shaped values it will send (update); undefined when not row-shaped. */\n data?: Record<string, unknown>;\n /** The cached row just before this write's patch. */\n baseline?: BaseRecord;\n /**\n * - waiting: an undoable write in its delay\n * - queued: to be sent, behind earlier writes on the same record\n * - sending / done\n */\n state: \"waiting\" | \"queued\" | \"sending\" | \"done\";\n /** Sent with `keepalive` (because the page was unloading). */\n keepalive: boolean;\n /** Set when it was dropped because an earlier write it built on was taken back. */\n dropped: boolean;\n /** Send now: a waiting write skips its delay; `unloading` also skips the row queue. */\n flush: (unloading?: boolean) => void;\n /** Drop a waiting or queued write (see `dropped`). */\n drop: () => void;\n /** Drop a waiting or queued write without a word: its viewer is gone. */\n discard: () => void;\n /** Settles once the write was sent, failed or dropped. */\n sent: Promise<unknown>;\n}\n\ninterface Registry {\n pending: Map<string, number>;\n patches: Patch[];\n writes: Tracked[];\n rowTails: Map<string, Promise<void>>;\n /**\n * Per record: the version its last write here committed at, while more\n * writes on it are unsettled, so a write made behind another is checked\n * against the version that one left.\n */\n rowVersions: Map<string, string>;\n /** Cache data this module wrote, so the cache listener does not re-patch it. */\n produced: WeakSet<object>;\n /** True while this module is writing to the cache. */\n writing: boolean;\n unsubscribe?: () => void;\n}\n\nconst registries = new WeakMap<QueryClient, Registry>();\nlet nextSeq = 0;\n\nfunction registryFor(queryClient: QueryClient): Registry {\n let reg = registries.get(queryClient);\n if (!reg) {\n reg = {\n pending: new Map(),\n patches: [],\n writes: [],\n rowTails: new Map(),\n rowVersions: new Map(),\n produced: new WeakSet(),\n writing: false,\n };\n registries.set(queryClient, reg);\n }\n return reg;\n}\n\n/**\n * Sends every optimistic or undoable write still waiting on this client now,\n * and resolves once all have settled. Call it while the session that made\n * them still holds (a sign-out action, before signing out).\n */\nexport async function flushPendingWrites(queryClient: QueryClient): Promise<void> {\n const reg = registries.get(queryClient);\n if (!reg) return;\n for (const write of [...reg.writes].sort((a, b) => a.seq - b.seq)) {\n if (write.state === \"waiting\") write.flush();\n }\n await Promise.allSettled(reg.writes.map((write) => write.sent));\n}\n\n/**\n * Drops every write on this client not yet sent, without reporting them: the\n * viewer who made them is gone, so they must never be sent (or re-applied)\n * under the next one. Writes already sending finish under the old session.\n */\nexport function dropPendingWrites(queryClient: QueryClient): void {\n const reg = registries.get(queryClient);\n if (!reg) return;\n for (const write of [...reg.writes].sort((a, b) => b.seq - a.seq)) write.discard();\n}\n\n/** Optimistic or undoable writes on `resource` not yet settled. */\nexport function pendingWriteCount(queryClient: QueryClient, resource: string): number {\n return registries.get(queryClient)?.pending.get(resource) ?? 0;\n}\n\nfunction beginPending(reg: Registry, resource: string): void {\n reg.pending.set(resource, (reg.pending.get(resource) ?? 0) + 1);\n}\n\nfunction endPending(reg: Registry, resource: string): void {\n const left = Math.max(0, (reg.pending.get(resource) ?? 0) - 1);\n if (left === 0) reg.pending.delete(resource);\n else reg.pending.set(resource, left);\n}\n\n/**\n * Invalidate `[resource]`. Safe while optimistic/undoable writes on it are\n * pending: their patches are re-applied to whatever the refetch brings.\n */\nexport function invalidateResource(queryClient: QueryClient, resource: string): Promise<void> {\n return queryClient.invalidateQueries({ queryKey: resourceKeys(resource).all });\n}\n\nfunction setProduced(reg: Registry, queryClient: QueryClient, key: QueryKey, value: unknown): void {\n const wasWriting = reg.writing;\n reg.writing = true;\n try {\n queryClient.setQueryData(key, value);\n } finally {\n reg.writing = wasWriting;\n }\n // Structural sharing may store a different object than `value`.\n const stored: unknown = queryClient.getQueryData(key);\n if (stored && typeof stored === \"object\") reg.produced.add(stored);\n}\n\nfunction applyUpdate(row: BaseRecord, data: Record<string, unknown>): BaseRecord {\n return { ...row, ...data, id: row.id };\n}\n\n/** `row` with `data`'s fields put back to what they were in `before`. */\nfunction revertFields(row: BaseRecord, data: Record<string, unknown>, before: BaseRecord): BaseRecord {\n const out: Record<string, unknown> = { ...row };\n for (const k of Object.keys(data)) {\n if (k === \"id\") continue;\n if (k in before) out[k] = before[k];\n else delete out[k];\n }\n return out as BaseRecord;\n}\n\n/**\n * Applies `patches`, in order, to one cache entry's data, recording each\n * patch's before-row for that entry. Returns the same object when nothing\n * applied.\n */\nfunction applyPatches(key: QueryKey, hash: string, value: unknown, patches: Patch[]): unknown {\n if (key[1] === \"list\" || key[1] === \"infinite\") {\n return mapLists(key, hash, value, (list, listHash) => {\n let rows = list.data;\n let total = list.total;\n let changed = false;\n for (const p of patches) {\n const index = rows.findIndex((row) => sameId(row.id, p.id));\n if (index < 0) continue;\n p.before.set(listHash, { row: rows[index]!, index });\n if (p.kind === \"update\") {\n rows = rows.slice();\n rows[index] = applyUpdate(rows[index]!, p.data ?? {});\n } else {\n rows = rows.filter((_, i) => i !== index);\n if (typeof total === \"number\" && total >= 0) total = Math.max(0, total - 1);\n }\n changed = true;\n }\n if (!changed) return list;\n return typeof total === \"number\" ? { ...list, data: rows, total } : { ...list, data: rows };\n });\n }\n if (key[1] === \"detail\" && value && typeof value === \"object\") {\n let row = value as BaseRecord;\n let changed = false;\n for (const p of patches) {\n if (p.kind !== \"update\" || !sameId(key[2], p.id)) continue;\n p.before.set(hash, { row, index: -1 });\n row = applyUpdate(row, p.data ?? {});\n changed = true;\n }\n return changed ? row : value;\n }\n return value;\n}\n\n/** Re-applies pending patches to data that just landed in the cache. */\nfunction ensureListener(reg: Registry, queryClient: QueryClient): void {\n if (reg.unsubscribe) return;\n reg.unsubscribe = queryClient.getQueryCache().subscribe((event) => {\n if (reg.writing || event.type !== \"updated\" || event.action.type !== \"success\") return;\n const { queryKey: key, queryHash: hash } = event.query;\n const resource = key[0];\n if (typeof resource !== \"string\") return;\n const data: unknown = event.query.state.data;\n if (!data || typeof data !== \"object\" || reg.produced.has(data)) return;\n const patches = reg.patches.filter((p) => p.resource === resource);\n if (patches.length === 0) return;\n const next = applyPatches(key, hash, data, patches);\n if (next !== data) setProduced(reg, queryClient, key, next);\n });\n}\n\nfunction addPatch(reg: Registry, queryClient: QueryClient, patch: Patch): void {\n reg.patches.push(patch);\n ensureListener(reg, queryClient);\n for (const query of queryClient.getQueryCache().findAll({ queryKey: [patch.resource] })) {\n const value: unknown = query.state.data;\n const next = applyPatches(query.queryKey, query.queryHash, value, [patch]);\n if (next !== value) setProduced(reg, queryClient, query.queryKey, next);\n }\n}\n\nfunction dropPatchRecord(reg: Registry, patch: Patch): number {\n const index = reg.patches.indexOf(patch);\n if (index >= 0) reg.patches.splice(index, 1);\n if (reg.patches.length === 0 && reg.unsubscribe) {\n reg.unsubscribe();\n reg.unsubscribe = undefined;\n }\n return index;\n}\n\nfunction firstBefore(patch: Patch): { row: BaseRecord; index: number } | undefined {\n for (const value of patch.before.values()) return value;\n return undefined;\n}\n\n/**\n * Takes a patch back out of the cache, keeping every other pending patch on\n * the same record applied (field by field, not by restoring a whole saved\n * row).\n */\nfunction retractPatch(reg: Registry, queryClient: QueryClient, patch: Patch): void {\n const index = dropPatchRecord(reg, patch);\n if (index < 0) return;\n const onRow = (p: Patch) => p.resource === patch.resource && sameId(p.id, patch.id);\n const remaining = reg.patches.filter(onRow);\n\n // Later patches on the record recorded their before-rows on top of this\n // one: take its values out of them too.\n if (patch.kind === \"update\" && patch.data) {\n for (const later of reg.patches.slice(index).filter(onRow)) {\n for (const [hash, b] of later.before) {\n const src = patch.before.get(hash) ?? firstBefore(patch);\n if (src) later.before.set(hash, { ...b, row: revertFields(b.row, patch.data, src.row) });\n }\n }\n }\n\n const reapply = (row: BaseRecord) =>\n remaining.reduce((r, p) => (p.kind === \"update\" ? applyUpdate(r, p.data ?? {}) : r), row);\n\n for (const query of queryClient.getQueryCache().findAll({ queryKey: [patch.resource] })) {\n const key = query.queryKey;\n const value: unknown = query.state.data;\n let next: unknown = value;\n if (key[1] === \"list\" || key[1] === \"infinite\") {\n next = mapLists(key, query.queryHash, value, (list, listHash) => {\n const b = patch.before.get(listHash);\n const at = list.data.findIndex((row) => sameId(row.id, patch.id));\n if (patch.kind === \"update\") {\n const src = b ?? firstBefore(patch);\n if (at < 0 || !src || !patch.data) return list;\n const rows = list.data.slice();\n rows[at] = reapply(revertFields(rows[at]!, patch.data, src.row));\n return { ...list, data: rows };\n }\n // A delete puts the row back where it was, unless a later delete of\n // the same record still hides it.\n if (at >= 0 || !b || remaining.some((p) => p.kind === \"delete\")) return list;\n const rows = list.data.slice();\n rows.splice(Math.min(b.index, rows.length), 0, reapply(b.row));\n return {\n ...list,\n data: rows,\n ...(typeof list.total === \"number\" && list.total >= 0 ? { total: list.total + 1 } : {}),\n };\n });\n } else if (\n key[1] === \"detail\" &&\n patch.kind === \"update\" &&\n patch.data &&\n sameId(key[2], patch.id) &&\n value &&\n typeof value === \"object\"\n ) {\n const src = patch.before.get(query.queryHash) ?? firstBefore(patch);\n if (!src) continue;\n next = reapply(revertFields(value as BaseRecord, patch.data, src.row));\n }\n if (next !== value) setProduced(reg, queryClient, key, next);\n }\n}\n\n/**\n * A write was taken back (undone, or it failed): retract its patch, and fix\n * the later writes on the same record that have not been sent. A later\n * update that kept this write's values unchanged (its form opened from the\n * patched cache) gets them put back to what they were before; one whose\n * values are not row-shaped cannot be fixed, so it is dropped.\n */\nfunction takeBack(reg: Registry, write: Tracked): void {\n if (write.patch) retractPatch(reg, write.queryClient, write.patch);\n if (!write.rowKey || write.kind !== \"update\" || !write.patch?.data) return;\n const undone = write.patch.data;\n const before = write.baseline ?? firstBefore(write.patch)?.row ?? ({} as BaseRecord);\n const later = reg.writes.filter(\n (w) =>\n w.seq > write.seq &&\n w.rowKey === write.rowKey &&\n w.kind === \"update\" &&\n (w.state === \"waiting\" || w.state === \"queued\"),\n );\n for (const w of later) {\n if (!w.data) {\n w.drop();\n continue;\n }\n const rebased: Record<string, unknown> = {};\n const removed: string[] = [];\n for (const k of Object.keys(undone)) {\n if (k === \"id\" || !(k in w.data)) continue;\n const kept = sameValue(w.data[k], undone[k]) && w.baseline != null && sameValue(w.baseline[k], undone[k]);\n if (!kept) continue;\n if (k in before) rebased[k] = before[k];\n else removed.push(k);\n }\n if (Object.keys(rebased).length === 0 && removed.length === 0) continue;\n // w.data is also w.patch.data: rebase it in place, then show it.\n Object.assign(w.data, rebased);\n for (const k of removed) delete w.data[k];\n if (w.baseline) w.baseline = revertFields(w.baseline, undone, before);\n if (w.patch) refreshFields(reg, w.queryClient, w.patch, [...Object.keys(rebased), ...removed]);\n }\n}\n\n/**\n * After a patch's values changed in place: shows its new values for `keys`\n * in every cached copy of the record, except where a later patch on the\n * record sets the same field.\n */\nfunction refreshFields(reg: Registry, queryClient: QueryClient, patch: Patch, keys: string[]): void {\n const index = reg.patches.indexOf(patch);\n if (index < 0 || !patch.data) return;\n const data = patch.data;\n const overridden = new Set<string>();\n for (const p of reg.patches.slice(index + 1)) {\n if (p.resource === patch.resource && sameId(p.id, patch.id) && p.data) {\n for (const k of Object.keys(p.data)) overridden.add(k);\n }\n }\n const fields = keys.filter((k) => !overridden.has(k));\n if (fields.length === 0) return;\n const fix = (row: BaseRecord, hash: string): BaseRecord => {\n const out: Record<string, unknown> = { ...row };\n const before = (patch.before.get(hash) ?? firstBefore(patch))?.row;\n for (const k of fields) {\n if (k in data) out[k] = data[k];\n else if (before && k in before) out[k] = before[k];\n else delete out[k];\n }\n return out as BaseRecord;\n };\n for (const query of queryClient.getQueryCache().findAll({ queryKey: [patch.resource] })) {\n const key = query.queryKey;\n const value: unknown = query.state.data;\n let next: unknown = value;\n if (key[1] === \"list\" || key[1] === \"infinite\") {\n next = mapLists(key, query.queryHash, value, (list, listHash) => {\n const at = list.data.findIndex((row) => sameId(row.id, patch.id));\n if (at < 0) return list;\n const rows = list.data.slice();\n rows[at] = fix(rows[at]!, listHash);\n return { ...list, data: rows };\n });\n } else if (key[1] === \"detail\" && sameId(key[2], patch.id) && value && typeof value === \"object\") {\n next = fix(value as BaseRecord, query.queryHash);\n }\n if (next !== value) setProduced(reg, queryClient, key, next);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Page unload\n//\n// Waiting writes are sent when the page goes away (`beforeunload`, and\n// `pagehide` for mobile tab kills and bfcache), with `keepalive: true` in\n// their params so a fetch-based provider can let them outlive the page. The\n// \"Leave site?\" prompt shows only while a write is being sent without that\n// guarantee: its provider does not report `keepaliveWrites`, or it was\n// already on its way without keepalive.\n// ---------------------------------------------------------------------------\n\nconst allWrites = new Set<Tracked>();\n\nfunction servesKeepalive(write: Tracked): boolean {\n const caps = write.queryClient.getQueryData<ProviderCapabilities>(\n capabilitiesQueryKey(write.provider, write.resource),\n );\n return caps?.keepaliveWrites === true;\n}\n\nfunction flushForUnload(): void {\n const writes = [...allWrites].sort((a, b) => a.seq - b.seq);\n for (const write of writes) {\n if (write.state === \"waiting\" || write.state === \"queued\") write.flush(true);\n }\n}\n\nfunction onBeforeUnload(event: BeforeUnloadEvent): void {\n flushForUnload();\n const atRisk = [...allWrites].some((w) => w.state === \"sending\" && !(w.keepalive && servesKeepalive(w)));\n if (!atRisk) return;\n event.preventDefault();\n // Older browsers need returnValue set to show the prompt.\n event.returnValue = \"\";\n}\n\nfunction onPageHide(): void {\n flushForUnload();\n}\n\n// The window the listeners went on, so they come off the same one. React\n// Native has a `window` with no listener methods: there is no page to leave.\nlet unloadTarget: PageWindow | undefined;\n\nfunction track(write: Tracked): void {\n allWrites.add(write);\n if (allWrites.size === 1 && !unloadTarget) {\n unloadTarget = pageWindow();\n unloadTarget?.addEventListener(\"beforeunload\", onBeforeUnload);\n unloadTarget?.addEventListener(\"pagehide\", onPageHide);\n }\n}\n\nfunction untrack(write: Tracked): void {\n if (!allWrites.delete(write)) return;\n if (allWrites.size === 0 && unloadTarget) {\n unloadTarget.removeEventListener(\"beforeunload\", onBeforeUnload);\n unloadTarget.removeEventListener(\"pagehide\", onPageHide);\n unloadTarget = undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// The engine\n// ---------------------------------------------------------------------------\n\n/** What `send` is given when the write goes out. */\nexport interface SendContext {\n /**\n * The row-shaped values to send, when `data` was given. They can differ\n * from `data`: an earlier write on the record that this one built on was\n * taken back, and its values were put back. Send these.\n */\n data?: Record<string, unknown>;\n /** The page is unloading: pass `keepalive: true` to the provider. */\n keepalive: boolean;\n /**\n * The version of the row this write was made on (`base`, else the cached\n * row when the write was made), or, for a write made behind another on the\n * same record, the version that one committed at. The field is the one the\n * provider's capabilities name (`version`). Pass it as `expectedVersion`, so\n * a write made on a stale copy is refused as a `conflict`. Undefined when\n * the resource has no version or the row isn't known: send the write\n * unchecked, as before.\n */\n expectedVersion?: string;\n}\n\nexport interface ExecuteWriteArgs<R extends BaseRecord | void> {\n queryClient: QueryClient;\n provider: DataProvider;\n resource: string;\n kind: \"create\" | \"update\" | \"delete\";\n id?: Identifier;\n /**\n * The values to merge into the cached row (update). Leave out to patch\n * nothing, e.g. when the values are form-shaped and the row is not.\n */\n data?: Record<string, unknown>;\n /**\n * The row as the person saw it when they made this change (an edit form's\n * loaded record). Its version is what the write is checked against.\n * Defaults to the cached row at the moment `executeWrite` is called.\n */\n base?: BaseRecord;\n /**\n * The version to check this write against, overriding `base` and the\n * cache: \"keep mine\" after a conflict sends at the version the conflict\n * reported (`WriteConflict.currentVersion`).\n */\n expectedVersion?: string;\n mode: MutationMode;\n undoDelayMs?: number;\n onUndoable?: (write: UndoableWrite) => void;\n /** Sends the write. */\n send: (context: SendContext) => Promise<{ record: R; audit?: AuditEntry }>;\n /** After the write committed. Invalidates and calls success callbacks. */\n committed: (record: R) => Promise<void> | void;\n /** A write that failed (or was dropped) after the caller was told it went through. */\n failedLater: (error: Error) => void;\n}\n\nexport type ExecuteWriteResult<R> =\n | { status: \"committed\"; record: R }\n | { status: \"applied\" };\n\nconst CAPABILITIES_QUERY = (provider: DataProvider, resource: string) => ({\n // The same key as useCapabilities, so the answer is shared.\n queryKey: capabilitiesQueryKey(provider, resource),\n queryFn: () => provider.capabilities!(resource),\n staleTime: Infinity,\n // A write may wait on this answer; an app's default retries would hold\n // it for seconds.\n retry: false as const,\n});\n\n/**\n * Whether `provider` serves `undo` for `resource`, from its capabilities\n * (useCapabilities' key, so the answer is shared, and scoped to this\n * provider: a swapped-out provider's capabilities never offer undo).\n * @internal Exported for tests.\n */\nexport async function providerServesUndo(\n queryClient: QueryClient,\n provider: DataProvider,\n resource: string,\n): Promise<boolean> {\n if (!provider.undo || !provider.capabilities) return false;\n try {\n const caps = await queryClient.fetchQuery<ProviderCapabilities>(CAPABILITIES_QUERY(provider, resource));\n return caps?.undo === true;\n } catch {\n return false;\n }\n}\n\n/** The version field `provider` names for `resource`, from capabilities already cached. */\nfunction cachedVersionField(queryClient: QueryClient, provider: DataProvider, resource: string): string | undefined {\n return queryClient.getQueryData<ProviderCapabilities>(capabilitiesQueryKey(provider, resource))?.version?.field;\n}\n\n/** `row`'s version as a token for `expectedVersion`. */\nfunction versionToken(row: BaseRecord | undefined, field: string): string | undefined {\n const value = row?.[field];\n return value == null ? undefined : String(value);\n}\n\nconst warnedNoVersion = new Set<string>();\n\n/**\n * The version `id`'s cached row is at, as a token for `expectedVersion`.\n * @internal Exported for tests.\n */\nexport function cachedVersion(\n queryClient: QueryClient,\n provider: DataProvider,\n resource: string,\n id: Identifier,\n): string | undefined {\n const field = cachedVersionField(queryClient, provider, resource);\n return field ? versionToken(cachedRow(queryClient, resource, id), field) : undefined;\n}\n\n/**\n * After an update committed: put the row's new version into every cached\n * copy at once, so the next write on it (before any refetch lands) is\n * checked against the version this one left, not the one before it.\n * Returns the new version.\n */\nfunction recordNewVersion(\n queryClient: QueryClient,\n resource: string,\n id: Identifier,\n field: string,\n record: unknown,\n): string | undefined {\n if (!record || typeof record !== \"object\") return undefined;\n const value = (record as Record<string, unknown>)[field];\n if (value == null) return undefined;\n patchCachedRow(queryClient, resource, { id, [field]: value });\n return String(value);\n}\n\n/** Forget a record's chained version once nothing on it is unsettled. */\nfunction releaseRow(reg: Registry, rowKey: string): void {\n if (!reg.rowTails.has(rowKey) && !reg.writes.some((w) => w.rowKey === rowKey)) reg.rowVersions.delete(rowKey);\n}\n\n/** A later write that built on one that was taken back. */\nexport const DROPPED_WRITE_MESSAGE =\n \"This change was not saved: it was made on top of an earlier change that was undone or failed. Please make it again.\";\n\n/**\n * Runs one write in the given mode.\n *\n * - `pessimistic`: sends it and waits; a failure rejects.\n * - `optimistic` / `undoable`: resolves `{ status: \"applied\" }` as soon as\n * the cache is patched. A later failure rolls the patch back and goes to\n * `failedLater`, never to the returned promise.\n *\n * Writes on the same record are sent one after another, in the order they\n * were made; sending one first sends the earlier ones still waiting.\n */\nexport async function executeWrite<R extends BaseRecord | void>(\n args: ExecuteWriteArgs<R>,\n): Promise<ExecuteWriteResult<R>> {\n const { queryClient, provider, resource, kind, id, mode, committed, failedLater } = args;\n const reg = registryFor(queryClient);\n const hasRow = kind !== \"create\" && id != null;\n const rowKey = hasRow ? `${resource}\\u0000${String(id)}` : undefined;\n\n // A versioned resource checks every update and delete against the version\n // of the row the person changed: the one they saw (`base`), else the row\n // cached now, before this write patches it or a refetch replaces it. A write\n // made while another on the record is unsettled builds on that one, so it\n // is checked against the version that one commits at.\n const seen = hasRow ? (args.base ?? cachedRow(queryClient, resource, id!)) : undefined;\n const behind = rowKey !== undefined && (reg.rowTails.has(rowKey) || reg.writes.some((w) => w.rowKey === rowKey && w.state !== \"done\"));\n const versioned = hasRow && !!provider.capabilities;\n const send = async (context: SendContext) => {\n let field: string | undefined;\n if (versioned) {\n // Cached for the provider's life, so only the first write on a resource waits for it.\n if (!queryClient.getQueryData(capabilitiesQueryKey(provider, resource))) {\n await queryClient.fetchQuery(CAPABILITIES_QUERY(provider, resource)).catch(() => undefined);\n }\n field = cachedVersionField(queryClient, provider, resource);\n }\n // A version the caller names (\"keep mine\" after a conflict, which proves the row has one) goes\n // as is, unless a write on the row made since has committed a newer one.\n let expectedVersion: string | undefined =\n args.expectedVersion !== undefined ? ((behind ? reg.rowVersions.get(rowKey!) : undefined) ?? args.expectedVersion) : undefined;\n if (field && expectedVersion === undefined) {\n expectedVersion = (behind ? reg.rowVersions.get(rowKey!) : undefined) ?? versionToken(seen, field);\n if (seen && !(field in seen) && !warnedNoVersion.has(resource)) {\n warnedNoVersion.add(resource);\n reportError(\n new Error(\n `\"${resource}\" has a version (${field}), but its rows as read here don't carry it, so its writes go unchecked. ` +\n `Read the version column (add it to the resource's select or source view).`,\n ),\n { source: \"core:versioned-writes\", tags: { resource } },\n );\n }\n }\n const result = await args.send(expectedVersion === undefined ? context : { ...context, expectedVersion });\n if (field && kind === \"update\") {\n const next = recordNewVersion(queryClient, resource, id!, field, result.record);\n // Kept while more writes on the row are unsettled (releaseRow clears it).\n if (next !== undefined) reg.rowVersions.set(rowKey!, next);\n // The saved row didn't say its new version (an update rule that returned only an id):\n // read it again, so the next edit isn't checked against the old one.\n else void invalidateResource(queryClient, resource);\n }\n return result;\n };\n\n if (mode === \"pessimistic\") {\n // Writes on one record go one after another here too, so a second save made while the first\n // is on its way is checked against the version the first leaves, not the one before it.\n const run = () => send({ data: args.data, keepalive: false });\n let sending: Promise<{ record: R; audit?: AuditEntry }>;\n if (rowKey) {\n const previous = reg.rowTails.get(rowKey);\n sending = previous ? previous.then(run, run) : run();\n const tail = sending.then(\n () => {},\n () => {},\n );\n reg.rowTails.set(rowKey, tail);\n void tail.finally(() => {\n if (reg.rowTails.get(rowKey) === tail) reg.rowTails.delete(rowKey);\n releaseRow(reg, rowKey);\n });\n } else {\n sending = run();\n }\n const { record } = await sending;\n await committed(record);\n return { status: \"committed\", record };\n }\n\n const viaProviderUndo = mode === \"undoable\" && (await providerServesUndo(queryClient, provider, resource));\n // Warm the capabilities answer, so the unload handler can tell (without\n // waiting) whether this provider keeps writes alive.\n if (provider.capabilities && !queryClient.getQueryData(capabilitiesQueryKey(provider, resource))) {\n void queryClient.prefetchQuery(CAPABILITIES_QUERY(provider, resource));\n }\n\n const data = args.data ? { ...args.data } : undefined;\n let patch: Patch | undefined;\n if (hasRow && kind === \"update\" && data) patch = { resource, id: id!, kind: \"update\", data, before: new Map() };\n else if (hasRow && kind === \"delete\") patch = { resource, id: id!, kind: \"delete\", before: new Map() };\n // A create has no cache entry yet: its id and its place in each sorted,\n // filtered list are the server's to say.\n\n const delayMs = Math.max(0, args.undoDelayMs ?? DEFAULT_UNDO_DELAY_MS);\n let timer: ReturnType<typeof setTimeout> | undefined;\n let resolveSent: (result: { record: R; audit?: AuditEntry } | undefined) => void = () => {};\n const sent = new Promise<{ record: R; audit?: AuditEntry } | undefined>((resolve) => {\n resolveSent = resolve;\n });\n\n const write: Tracked = {\n seq: ++nextSeq,\n queryClient,\n provider,\n resource,\n kind,\n rowKey,\n patch,\n data: kind === \"update\" ? data : undefined,\n baseline: hasRow ? cachedRecord(queryClient, resource, id!) : undefined,\n state: \"queued\",\n keepalive: false,\n dropped: false,\n flush: () => {},\n drop: () => {},\n discard: () => {},\n sent,\n };\n\n const settle = () => {\n write.state = \"done\";\n clearTimeout(timer);\n const at = reg.writes.indexOf(write);\n if (at >= 0) reg.writes.splice(at, 1);\n untrack(write);\n endPending(reg, resource);\n if (rowKey) releaseRow(reg, rowKey);\n };\n\n const sendNow = async (keepalive: boolean): Promise<void> => {\n if (write.state !== \"queued\") return;\n write.state = \"sending\";\n write.keepalive = keepalive;\n let result: { record: R; audit?: AuditEntry };\n try {\n result = await send({ data: write.data, keepalive });\n } catch (error) {\n settle();\n takeBack(reg, write);\n void invalidateResource(queryClient, resource);\n failedLater(asError(error));\n resolveSent(undefined);\n return;\n }\n // The server has it now; the refetch `committed` starts replaces the patch.\n if (patch) dropPatchRecord(reg, patch);\n settle();\n try {\n await committed(result.record);\n } catch (error) {\n // The write did commit; only a callback failed.\n console.error(`[genesis] after-write callback failed for \"${resource}\":`, error);\n }\n resolveSent(result);\n };\n\n const enqueue = () => {\n if (!write.rowKey) {\n void sendNow(false);\n return;\n }\n const key = write.rowKey;\n const previous = reg.rowTails.get(key);\n const run = () => sendNow(false);\n const next = previous ? previous.then(run, run) : run();\n reg.rowTails.set(key, next);\n void next.finally(() => {\n if (reg.rowTails.get(key) === next) reg.rowTails.delete(key);\n releaseRow(reg, key);\n });\n };\n\n write.flush = (unloading = false) => {\n if (write.state === \"waiting\") {\n clearTimeout(timer);\n // Earlier writes on the record go first, so the server sees them in order.\n if (!unloading) {\n for (const earlier of reg.writes) {\n if (earlier.seq < write.seq && earlier.rowKey === write.rowKey && earlier.rowKey && earlier.state === \"waiting\") {\n earlier.flush();\n }\n }\n }\n write.state = \"queued\";\n if (unloading) void sendNow(true);\n else enqueue();\n } else if (write.state === \"queued\" && unloading) {\n // Behind an earlier write on the record; the page will not wait for it.\n void sendNow(true);\n }\n };\n\n write.drop = () => {\n if (write.state !== \"waiting\" && write.state !== \"queued\") return;\n write.dropped = true;\n settle();\n takeBack(reg, write);\n void invalidateResource(queryClient, resource);\n failedLater(new Error(DROPPED_WRITE_MESSAGE));\n resolveSent(undefined);\n };\n\n write.discard = () => {\n if (write.state !== \"waiting\" && write.state !== \"queued\") return;\n write.dropped = true;\n settle();\n // The cache is being emptied: forget the patch rather than put values back.\n if (patch) dropPatchRecord(reg, patch);\n resolveSent(undefined);\n };\n\n beginPending(reg, resource);\n reg.writes.push(write);\n track(write);\n if (patch) addPatch(reg, queryClient, patch);\n\n if (mode === \"optimistic\") {\n enqueue();\n return { status: \"applied\" };\n }\n\n if (viaProviderUndo) {\n enqueue();\n void sent.then((result) => {\n const auditId = result?.audit?.id;\n if (!result || !args.onUndoable) return;\n if (!auditId) {\n console.warn(\n `[genesis] \"${resource}\" serves undo, but its ${kind} returned no audit entry; no undo offered.`,\n );\n return;\n }\n let undone = false;\n args.onUndoable({\n resource,\n kind,\n id: id ?? (result.record as BaseRecord | undefined)?.id,\n strategy: \"provider\",\n delayMs,\n commit: () => {},\n undo: async () => {\n if (undone) return false;\n undone = true;\n let ok = true;\n try {\n await provider.undo!(resource, { auditId });\n } catch (error) {\n ok = false;\n failedLater(asError(error));\n }\n await invalidateResource(queryClient, resource);\n return ok;\n },\n });\n });\n return { status: \"applied\" };\n }\n\n // Delayed: wait, then send unless undone or flushed first.\n write.state = \"waiting\";\n timer = setTimeout(() => write.flush(), delayMs);\n\n args.onUndoable?.({\n resource,\n kind,\n id,\n strategy: \"delay\",\n delayMs,\n commit: () => write.flush(),\n undo: async () => {\n if (write.dropped) return true;\n if (write.state !== \"waiting\") return false;\n settle();\n takeBack(reg, write);\n void invalidateResource(queryClient, resource);\n resolveSent(undefined);\n return true;\n },\n });\n\n return { status: \"applied\" };\n}\n"]}