kaafil-react-uikit 0.7.0 → 0.8.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 (49) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/admin/index.cjs +468 -446
  3. package/dist/admin/index.cjs.map +1 -1
  4. package/dist/admin/index.js +128 -106
  5. package/dist/admin/index.js.map +1 -1
  6. package/dist/{chunk-53ITV6GF.cjs → chunk-4R7QBTNL.cjs} +4 -4
  7. package/dist/{chunk-53ITV6GF.cjs.map → chunk-4R7QBTNL.cjs.map} +1 -1
  8. package/dist/{chunk-HNENKHHJ.js → chunk-57DYMIWS.js} +5 -5
  9. package/dist/{chunk-HNENKHHJ.js.map → chunk-57DYMIWS.js.map} +1 -1
  10. package/dist/{chunk-XPF737RG.cjs → chunk-7COMKJTM.cjs} +9 -9
  11. package/dist/{chunk-XPF737RG.cjs.map → chunk-7COMKJTM.cjs.map} +1 -1
  12. package/dist/{chunk-OOHU3ECL.cjs → chunk-7O3TPYK4.cjs} +17 -17
  13. package/dist/{chunk-OOHU3ECL.cjs.map → chunk-7O3TPYK4.cjs.map} +1 -1
  14. package/dist/{chunk-4QMYUKW4.cjs → chunk-ASFUY3IE.cjs} +5368 -5358
  15. package/dist/chunk-ASFUY3IE.cjs.map +1 -0
  16. package/dist/{chunk-CJMUPBZ7.js → chunk-DYOAKTGJ.js} +5 -5
  17. package/dist/{chunk-CJMUPBZ7.js.map → chunk-DYOAKTGJ.js.map} +1 -1
  18. package/dist/{chunk-JHLPO6LZ.js → chunk-E3KOQYY2.js} +3 -3
  19. package/dist/{chunk-JHLPO6LZ.js.map → chunk-E3KOQYY2.js.map} +1 -1
  20. package/dist/{chunk-F6B4CDUL.js → chunk-GKR52SVU.js} +3 -3
  21. package/dist/{chunk-F6B4CDUL.js.map → chunk-GKR52SVU.js.map} +1 -1
  22. package/dist/chunk-LBTAK5JA.cjs +12 -0
  23. package/dist/{chunk-V45VFRBI.cjs.map → chunk-LBTAK5JA.cjs.map} +1 -1
  24. package/dist/{chunk-77RKNRNH.cjs → chunk-MP4IMAPF.cjs} +55 -55
  25. package/dist/{chunk-77RKNRNH.cjs.map → chunk-MP4IMAPF.cjs.map} +1 -1
  26. package/dist/{chunk-AWOKWGTB.cjs → chunk-PQJGV3RE.cjs} +83 -83
  27. package/dist/{chunk-AWOKWGTB.cjs.map → chunk-PQJGV3RE.cjs.map} +1 -1
  28. package/dist/{chunk-F6YBM6EE.js → chunk-Q4B25EZO.js} +3 -3
  29. package/dist/{chunk-F6YBM6EE.js.map → chunk-Q4B25EZO.js.map} +1 -1
  30. package/dist/{chunk-XPCCR7OH.cjs → chunk-TDFM563X.cjs} +12 -12
  31. package/dist/{chunk-XPCCR7OH.cjs.map → chunk-TDFM563X.cjs.map} +1 -1
  32. package/dist/{chunk-PWZNUXKT.js → chunk-VU5BCK2P.js} +3 -3
  33. package/dist/{chunk-PWZNUXKT.js.map → chunk-VU5BCK2P.js.map} +1 -1
  34. package/dist/{chunk-4BPCKBLP.js → chunk-YHGAFRN6.js} +3 -3
  35. package/dist/{chunk-4BPCKBLP.js.map → chunk-YHGAFRN6.js.map} +1 -1
  36. package/dist/{chunk-SEPFCHBJ.js → chunk-ZURCZQQ7.js} +5368 -5358
  37. package/dist/chunk-ZURCZQQ7.js.map +1 -0
  38. package/dist/core/index.cjs +107 -107
  39. package/dist/core/index.js +10 -10
  40. package/dist/index.css +1 -1
  41. package/dist/manager/index.cjs +239 -239
  42. package/dist/manager/index.js +6 -6
  43. package/dist/tokens.json +7 -1
  44. package/dist/traveller/index.cjs +35 -35
  45. package/dist/traveller/index.js +5 -5
  46. package/package.json +1 -1
  47. package/dist/chunk-4QMYUKW4.cjs.map +0 -1
  48. package/dist/chunk-SEPFCHBJ.js.map +0 -1
  49. package/dist/chunk-V45VFRBI.cjs +0 -12
@@ -1,16 +1,16 @@
1
1
  'use strict';
2
2
 
3
- var chunk4QMYUKW4_cjs = require('./chunk-4QMYUKW4.cjs');
3
+ var chunkASFUY3IE_cjs = require('./chunk-ASFUY3IE.cjs');
4
4
  var react = require('react');
5
5
 
6
6
  function isVersionConflict(op) {
7
7
  return op.status === "parked" && op.parkReason?.code === "CONFLICT_VERSION";
8
8
  }
9
9
  function useConflicts(tripRef) {
10
- const engine = react.useContext(chunk4QMYUKW4_cjs.OfflineEngineContext);
10
+ const engine = react.useContext(chunkASFUY3IE_cjs.OfflineEngineContext);
11
11
  const [tick, forceRefresh] = react.useState(0);
12
- chunk4QMYUKW4_cjs.useOfflineEvent("sync.error", () => forceRefresh((current) => current + 1));
13
- chunk4QMYUKW4_cjs.useOfflineEvent("sync.drained", () => forceRefresh((current) => current + 1));
12
+ chunkASFUY3IE_cjs.useOfflineEvent("sync.error", () => forceRefresh((current) => current + 1));
13
+ chunkASFUY3IE_cjs.useOfflineEvent("sync.drained", () => forceRefresh((current) => current + 1));
14
14
  const conflictOps = react.useMemo(
15
15
  () => engine === null ? [] : engine.outbox.all().filter((op) => op.tripRef === tripRef && isVersionConflict(op)),
16
16
  // eslint-disable-next-line react-hooks/exhaustive-deps -- same reasoning, see the biome-ignore comment above.
@@ -47,8 +47,8 @@ function useConflicts(tripRef) {
47
47
  var lastKnown = /* @__PURE__ */ new WeakMap();
48
48
  var READ_CACHE_KEY = "manager.me.trips";
49
49
  function useManagerMe() {
50
- const client = chunk4QMYUKW4_cjs.useKaafilClient();
51
- const engine = react.useContext(chunk4QMYUKW4_cjs.OfflineEngineContext);
50
+ const client = chunkASFUY3IE_cjs.useKaafilClient();
51
+ const engine = react.useContext(chunkASFUY3IE_cjs.OfflineEngineContext);
52
52
  const [result, setResult] = react.useState(
53
53
  () => lastKnown.get(client) ?? readCached(engine) ?? { status: "loading" }
54
54
  );
@@ -87,7 +87,7 @@ function isTombstone(item) {
87
87
  return "_tombstone" in item && item._tombstone === true;
88
88
  }
89
89
  function useNotifications() {
90
- const client = chunk4QMYUKW4_cjs.useKaafilClient();
90
+ const client = chunkASFUY3IE_cjs.useKaafilClient();
91
91
  const [result, setResult] = react.useState({ status: "loading" });
92
92
  react.useEffect(() => {
93
93
  let cancelled = false;
@@ -123,5 +123,5 @@ function useNotifications() {
123
123
  exports.useConflicts = useConflicts;
124
124
  exports.useManagerMe = useManagerMe;
125
125
  exports.useNotifications = useNotifications;
126
- //# sourceMappingURL=chunk-XPF737RG.cjs.map
127
- //# sourceMappingURL=chunk-XPF737RG.cjs.map
126
+ //# sourceMappingURL=chunk-7COMKJTM.cjs.map
127
+ //# sourceMappingURL=chunk-7COMKJTM.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/hooks/useConflicts.ts","../src/core/hooks/useManagerMe.ts","../src/core/hooks/useNotifications.ts"],"names":["useContext","OfflineEngineContext","useState","useOfflineEvent","useMemo","useKaafilClient","useEffect"],"mappings":";;;;;AA4BA,SAAS,kBAAkB,EAAA,EAAuB;AAChD,EAAA,OAAO,EAAA,CAAG,MAAA,KAAW,QAAA,IAAY,EAAA,CAAG,YAAY,IAAA,KAAS,kBAAA;AAC3D;AAEO,SAAS,aAAa,OAAA,EAAkC;AAK7D,EAAA,MAAM,MAAA,GAASA,iBAAWC,sCAAoB,CAAA;AAM9C,EAAA,MAAM,CAAC,IAAA,EAAM,YAAY,CAAA,GAAIC,eAAS,CAAC,CAAA;AAEvC,EAAAC,iCAAA,CAAgB,cAAc,MAAM,YAAA,CAAa,CAAC,OAAA,KAAY,OAAA,GAAU,CAAC,CAAC,CAAA;AAC1E,EAAAA,iCAAA,CAAgB,gBAAgB,MAAM,YAAA,CAAa,CAAC,OAAA,KAAY,OAAA,GAAU,CAAC,CAAC,CAAA;AAG5E,EAAA,MAAM,WAAA,GAAcC,aAAA;AAAA,IAClB,MACE,MAAA,KAAW,IAAA,GACP,EAAC,GACD,OAAO,MAAA,CAAO,GAAA,EAAI,CAAE,MAAA,CAAO,CAAC,EAAA,KAAO,EAAA,CAAG,YAAY,OAAA,IAAW,iBAAA,CAAkB,EAAE,CAAC,CA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Q,SAAA,EAAW,CAAA;AAC/B,IAAA,MAAA,CAAO,aAAA,CACJ,IAAA,EAAK,CACL,IAAA,CAAK,CAAC,QAAA,KAAa;AAClB,MAAA,IAAI,SAAA,EAAW;AACb,QAAA;AAAA,MACF;AACA,MAAA,MAAM,aAAA,GAAgB,SAAS,KAAA,CAAM,MAAA;AAAA,QACnC,CAAC,IAAA,KAAsC,CAAC,WAAA,CAAY,IAAI;AAAA,OAC1D;AACA,MAAA,SAAA,CAAU;AAAA,QACR,MAAA,EAAQ,OAAA;AAAA,QACR,aAAA;AAAA,QACA,WAAA,EAAa,cAAc,MAAA,CAAO,CAAC,MAAM,CAAA,CAAE,MAAA,KAAW,IAAI,CAAA,CAAE,MAAA;AAAA,QAC5D,QAAA,EAAU,OAAO,EAAA,KAAe;AAC9B,UAAA,MAAM,MAAA,CAAO,aAAA,CAAc,QAAA,CAAS,EAAE,IAAI,CAAA;AAAA,QAC5C,CAAA;AAAA,QACA,QAAA,EAAU,SAAS,IAAA,CAAK;AAAA,OACzB,CAAA;AAAA,IACH,CAAC,CAAA,CACA,KAAA,CAAM,MAAM;AACX,MAAA,IAAI,CAAC,SAAA,EAAW;AACd,QAAA,SAAA,CAAU,EAAE,MAAA,EAAQ,OAAA,EAAS,CAAA;AAAA,MAC/B;AAAA,IACF,CAAC,CAAA;AACH,IAAA,OAAO,MAAM;AACX,MAAA,SAAA,GAAY,IAAA;AAAA,IACd,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,MAAM,CAAC,CAAA;AAEX,EAAA,OAAO,MAAA;AACT","file":"chunk-XPF737RG.cjs","sourcesContent":["'use client';\n\n// `08-core-hooks.md §2.7`. Every `409 CONFLICT_VERSION` op currently parked\n// and awaiting a human choice for this trip — entity-agnostic on purpose, so\n// the one shared `ConflictResolver` UI covers rooming/seating/checklist/\n// every versioned entity (`07-offline-and-sync.md §6`).\n//\n// VERIFIED SHAPE (`kaafil-js/src/offline/{outbox,reconcile}.ts`, this\n// session): a \"surface\" conflict reaches `Outbox.park()` with only\n// `{ status, code: 'CONFLICT_VERSION', userMessage }` — no row of either\n// side. The fresh server row, however, was already written into\n// `SnapshotStore` by `reconcileConflict()` before the park (its own \"why the\n// entity is re-pulled first\" header) whenever `op.entity` was set and the\n// re-read succeeded. `currentValue` below is read from there — the snapshot\n// — rather than invented on this hook's own read. `queuedValue` is the\n// parked op's own `body`, the intent that was never applied.\n\nimport type { OutboxOp } from 'kaafil-js/client';\nimport { useContext, useMemo, useState } from 'react';\nimport { OfflineEngineContext } from '../internal/contexts';\nimport type { ConflictRecord } from '../types/offline.types';\nimport { useOfflineEvent } from './useOfflineEvent';\n\nexport interface ConflictsResult {\n readonly conflicts: readonly ConflictRecord[];\n readonly resolve: (opId: string, choice: 'keep-queued' | 'keep-current') => Promise<void>;\n}\n\nfunction isVersionConflict(op: OutboxOp): boolean {\n return op.status === 'parked' && op.parkReason?.code === 'CONFLICT_VERSION';\n}\n\nexport function useConflicts(tripRef: string): ConflictsResult {\n // NOT `useOfflineEngine()` (its throwing form) — called from inside a\n // domain hook's unconditional `build()` (`createDomainHook.ts`), including\n // the render(s) before `OfflineShell` has opened an engine. No engine yet\n // means no ops to have conflicted yet — `conflicts: []`, never a crash.\n const engine = useContext(OfflineEngineContext);\n // `tick` itself is never read below beyond being a `useMemo` dependency —\n // `engine.outbox.all()` is a plain synchronous read with no reactive\n // identity of its own, so bumping this on every `sync.error`/`sync.drained`\n // is what makes the memo below re-run on the events that can change what\n // it returns.\n const [tick, forceRefresh] = useState(0);\n\n useOfflineEvent('sync.error', () => forceRefresh((current) => current + 1));\n useOfflineEvent('sync.drained', () => forceRefresh((current) => current + 1));\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: tick is a deliberate side-channel dep, forcing a re-run against the outbox's own non-reactive state on every sync event (see its declaration above).\n const conflictOps = useMemo(\n () =>\n engine === null\n ? []\n : engine.outbox.all().filter((op) => op.tripRef === tripRef && isVersionConflict(op)),\n // eslint-disable-next-line react-hooks/exhaustive-deps -- same reasoning, see the biome-ignore comment above.\n [engine, tripRef, tick],\n );\n\n const conflicts: readonly ConflictRecord[] =\n engine === null\n ? []\n : conflictOps.map((op) => {\n const currentValue =\n op.entity !== undefined\n ? engine.snapshot\n .list(op.tripRef, op.entity.listName)\n .find((row) => row.id === op.entity?.id)\n : undefined;\n return {\n opId: op.id,\n entity: op.entity?.listName ?? op.path,\n queuedValue: op.body,\n currentValue,\n };\n });\n\n async function resolve(opId: string, choice: 'keep-queued' | 'keep-current'): Promise<void> {\n if (engine === null) {\n return;\n }\n const op = engine.outbox.get(opId);\n if (op === undefined) {\n return;\n }\n if (choice === 'keep-current') {\n // `engine.discard()`, NOT `outbox.drop()`. The queue knows nothing about\n // the snapshot, so dropping a CREATE through it leaves the row the\n // manager just chose to discard on screen permanently: it is keyed on an\n // id only this device ever knew, so no pull, no delta and no tombstone\n // can ever remove it. `discard()` takes the optimistic row with the op.\n await engine.discard(opId);\n return;\n }\n // `keep-queued`: re-issue with the fresh version. The fresh row's own\n // `version` field is what `07-offline-and-sync.md §6` calls\n // `details.currentVersion`; reading it off the snapshot row this hook\n // already fetched above is the same value, sourced from the same\n // re-read `reconcileConflict()` already performed.\n const freshRow =\n op.entity !== undefined\n ? engine.snapshot\n .list(op.tripRef, op.entity.listName)\n .find((row) => row.id === op.entity?.id)\n : undefined;\n const freshVersion = freshRow?.version;\n await engine.outbox.reissue(opId, freshVersion !== undefined ? { ifMatch: freshVersion } : {});\n engine.drainer.kick();\n }\n\n return { conflicts, resolve };\n}\n","'use client';\n\n// `families/manager/01-surface.md`'s own \"trip-discovery gap\" note is now\n// stale — verified against the real engine: `GET /manager/me/trips`\n// (`client.managerMe.listTrips()`) resolves a manager's own live trip\n// assignments plus a sensible `defaultTripId`, and now also the manager's\n// own `fullName` (this build's own small engine addition —\n// `manager-me.dto.ts`'s `manager` field). This session's own product\n// decision overrides that spec note for `ManagerNowSection` and any future\n// manager composite that needs \"which trip(s) does THIS manager see\" —\n// never a host-supplied `assignedTrips` prop for those composites (that\n// prop still exists for `KaafilManagerApp`/`MyTripsScreen` themselves, per\n// spec, since a Surface's own trip-list PANE is a separate, larger\n// decision this hook does not revisit).\n//\n// Same deliberately minimal shape as `useManagerToday.ts`: a plain\n// `client.managerMe.listTrips()` call behind `useEffect`/`useState`, no\n// offline/outbox machinery (this is a live read with no mutation of its\n// own to queue), no capability gate (which trips a manager is assigned to\n// is an ingest fact, not a capability — `01-surface.md`'s own \"Gating\"\n// field, cited).\n\nimport type {\n KaafilClient,\n ManagerOwnTrip,\n ManagerOwnTripsResponse,\n OfflineEngine,\n} from 'kaafil-js/client';\nimport { useContext, useEffect, useState } from 'react';\nimport { OfflineEngineContext } from '../internal/contexts';\nimport { useKaafilClient } from './useKaafilClient';\n\n// Re-exported so a composite (`ManagerTripSection.types.ts`, `TripHero.tsx`)\n// can name one trip row's shape without importing `kaafil-js/client`\n// directly — hard rule #1.\nexport type { ManagerOwnTrip };\n\nexport interface ManagerMeLoading {\n readonly status: 'loading';\n}\n\nexport interface ManagerMeError {\n readonly status: 'error';\n}\n\nexport interface ManagerMeReady extends ManagerOwnTripsResponse {\n readonly status: 'ready';\n /** The server timestamp this read landed with (`meta.serverTime`) — never\n * a local clock read (hard rule #6). */\n readonly syncedAt: string;\n}\n\nexport type ManagerMeResult = ManagerMeLoading | ManagerMeError | ManagerMeReady;\n\n/**\n * The last answer this read actually got, per open client — the same\n * module-level, instance-keyed `WeakMap` shape `../internal/ensureTripPulled.ts`\n * already uses, and for the same reason: five composites\n * (`KaafilManagerApp`, `ManagerNowSection`, `ManagerTripSection`,\n * `ManagerChecklistSection`, `ManagerMeSection`) call this hook, and the\n * field surface mounts and unmounts them as the manager moves between tabs.\n *\n * Without this, EVERY tab switch was a fresh network read that the field\n * persona is by definition not guaranteed to be able to make. On a manager's\n * phone with no signal the read rejected, the hook reported `'error'`, and\n * every one of those composites renders nothing at all for that status — so\n * losing the network and then touching a tab emptied the trip screen, with\n * no way back short of a page reload (`architecture/06-offline-first.md`:\n * the field half must serve what it last knew rather than blank).\n *\n * It is not a cache in front of `kaafil-js` (hard rule #3): nothing is\n * reconciled, no cursor is kept, no event is subscribed to, and a live read\n * still fires on every mount so \"re-mount to refresh\" keeps working. It only\n * stops a failed read from erasing an answer the session already has.\n *\n * It dies with the tab, which is the whole reason for the durable lane below.\n */\nconst lastKnown = new WeakMap<KaafilClient, ManagerMeReady>();\n\n/**\n * The key this hook's answer is cached under in the engine's durable read\n * cache (`kaafil-js`'s `engine.reads`, credential-scoped by the engine).\n *\n * The `WeakMap` above survives a tab switch; it does not survive a RELOAD, and\n * a reload is the field surface's normal case rather than an edge one — a\n * manager's phone discards a backgrounded tab on its own. So an offline\n * manager who reloaded got `'error'` from the very first read, and every\n * composite that reads this hook renders nothing for that status: a blank\n * trip list, with their queued writes sitting intact in IndexedDB behind a\n * screen with no way into them. Durable writes the manager could not reach\n * are indistinguishable, from where they are standing, from lost ones.\n *\n * This response cannot live in the snapshot store: its rows carry a\n * `tripRef`, a name and a status but no `id` and no `version`, so there is\n * nothing for a version-guarded merge to guard (`kaafil-js/src/offline/\n * reads.ts` explains the split at length). It is a whole answer or nothing,\n * which is exactly the promise `engine.reads` makes.\n */\nconst READ_CACHE_KEY = 'manager.me.trips';\n\n/** What is actually persisted — the response plus the `meta.serverTime` it\n * landed with. The store keeps `syncedAt` itself, so only the body goes in. */\ntype CachedManagerMe = ManagerOwnTripsResponse;\n\n/**\n * `client.managerMe.listTrips()` behind a plain fetch-on-mount effect —\n * this read takes no parameter (it resolves entirely off the authenticated\n * principal, `manager-me.routes.ts`'s own header, cited), so it never\n * re-fetches on a prop change the way `useManagerToday(tripRef)` does.\n * A caller wanting \"refresh now\" re-mounts this hook's owning component.\n */\nexport function useManagerMe(): ManagerMeResult {\n const client = useKaafilClient();\n // The raw context, not `useOfflineEngine()`'s throwing form: this hook is\n // read by desk composites too, and a desk mount has no `OfflineShell` and\n // therefore no engine. With none, everything below degrades to exactly the\n // in-memory behaviour this hook had before — which is right for a surface\n // that is online by definition.\n const engine = useContext(OfflineEngineContext);\n\n // Seeded from what is already known, in order: this session's own answer,\n // then the durable one from a previous session. Both beat a skeleton, and\n // the durable one is the only one that exists after a reload.\n const [result, setResult] = useState<ManagerMeResult>(\n () => lastKnown.get(client) ?? readCached(engine) ?? { status: 'loading' },\n );\n\n useEffect(() => {\n let cancelled = false;\n setResult(lastKnown.get(client) ?? readCached(engine) ?? { status: 'loading' });\n client.managerMe\n .listTrips()\n .then((response) => {\n const { meta, ...data } = response;\n const ready: ManagerMeReady = { status: 'ready', ...data, syncedAt: meta.serverTime };\n // Recorded before the cancellation check: a response that landed is\n // true regardless of whether THIS component is still mounted to\n // render it, and the next mount should not have to re-ask.\n lastKnown.set(client, ready);\n // Fire-and-forget, and deliberately not awaited before the state is\n // set: painting the fresh answer must not wait on a disk write, and a\n // failed write costs the NEXT reload's first paint rather than this\n // one's correctness. `meta.serverTime`, never a device clock — the\n // store has no setter that would accept one (hard rule #6).\n void engine?.reads.set(READ_CACHE_KEY, data, meta.serverTime).catch(() => {\n // A full or unavailable store is not this read's problem to report.\n // The live answer above is already rendered and already correct.\n });\n if (!cancelled) {\n setResult(ready);\n }\n })\n .catch(() => {\n if (cancelled) {\n return;\n }\n // `'error'` ONLY when NOTHING is known — not this session, not the\n // last one. A read that failed after one succeeded means the device\n // is offline or the engine is unreachable, not that the manager\n // stopped being assigned to their trips; reporting `'error'` there is\n // what blanked the field surface, and after a reload it blanked it\n // from the very first read. `syncedAt` on the held value already\n // tells a caller how old the reading is.\n setResult(lastKnown.get(client) ?? readCached(engine) ?? { status: 'error' });\n });\n return () => {\n cancelled = true;\n };\n }, [client, engine]);\n\n return result;\n}\n\n/**\n * The last answer a PREVIOUS session got, if this surface has a durable store\n * at all. Returns `undefined` rather than an `'error'` so every call site can\n * fall through to the next-best source in one expression.\n */\nfunction readCached(engine: OfflineEngine | null): ManagerMeReady | undefined {\n const cached = engine?.reads.get<CachedManagerMe>(READ_CACHE_KEY);\n if (cached === undefined) {\n return undefined;\n }\n return { status: 'ready', ...cached.value, syncedAt: cached.syncedAt };\n}\n","'use client';\n\n// `08-core-hooks.md §3` table, row `useNotifications()`. Primary SDK surface\n// (verified, `kaafil-js/src/resources/notifications.ts`):\n// `notifications.list` (`managerAuth`-only), `notifications.markRead`\n// (likewise `managerAuth`-only). NOT trip-scoped — the only hook in this\n// table taking no `tripRef`. `managerAuth` is the ONLY scheme either\n// operation accepts, so this hook is structurally unreachable from the\n// `admin`/`traveller` families. `list` takes an optional `?since=` delta\n// cursor passed straight through, never a UIKit-invented filter language.\n//\n// Deliberately the same minimal shape as `useManagerToday.ts`/\n// `useManagerMe.ts`: a plain fetch-on-mount effect, no offline/outbox\n// machinery. `families/manager/11-offline-sync-and-notifications.md\n// §NotificationsFeed`'s own \"write: markRead enqueues through the outbox\n// with a fixed idempotency key\" contract is that COMPOSITE's job once it\n// is built — this hook exists now only so `ManagerNowSection`'s header\n// bell can show a real (honestly zero, until something writes a\n// notification) unread count, which needs `list()` alone. `markRead` is\n// still exposed as a direct SDK call (never mints its own idempotency key,\n// hard rule #4 — mark-read is naturally idempotent server-side per the\n// SDK's own doc comment, so no key is needed here at all) so an early\n// caller isn't blocked, but a future `NotificationsFeed` composite should\n// route its OWN write through the outbox instead of reusing this hook's\n// `markRead` as-is.\n//\n// The wire's `items` array is a discriminated union (a live row, or a\n// `{ _tombstone: true; id; version; deletedAt }` delete marker) — this hook\n// filters tombstones out of `notifications` (a plain unread-count/list\n// consumer has no use for a deleted row) rather than exposing the union to\n// every caller.\n\nimport type { NotificationsResource } from 'kaafil-js/client';\nimport { useEffect, useState } from 'react';\nimport { useKaafilClient } from './useKaafilClient';\n\n// `notifications.ts`'s resource module exports no named response type of its\n// own (unlike `manager-me.ts`'s `ManagerOwnTripsResponse`) — derived off the\n// resource's own method signature instead, `useFiles.ts`/`useExpenses.ts`'s\n// established precedent for this exact situation.\ntype NotificationListResponse = Awaited<ReturnType<NotificationsResource['list']>>;\ntype NotificationListItem = NotificationListResponse['items'][number];\n\n/** The live-row half of `NotificationListItem`'s union — a tombstone never\n * reaches a caller of this hook (see this file's own header). */\nexport type ManagerNotification = Exclude<NotificationListItem, { _tombstone: true }>;\n\nexport interface NotificationsLoading {\n readonly status: 'loading';\n}\n\nexport interface NotificationsError {\n readonly status: 'error';\n}\n\nexport interface NotificationsReady {\n readonly status: 'ready';\n readonly notifications: readonly ManagerNotification[];\n /** `notifications.filter((n) => n.readAt === null).length` — the wire\n * carries no numeric unread field of its own (verified against\n * `NotificationListResponse`), so this is a real derivation off real\n * rows, never a fabricated count. */\n readonly unreadCount: number;\n readonly markRead: (id: string) => Promise<void>;\n /** The server timestamp this read landed with (`meta.serverTime`) —\n * never a local clock read (hard rule #6). */\n readonly syncedAt: string;\n}\n\nexport type NotificationsResult = NotificationsLoading | NotificationsError | NotificationsReady;\n\nfunction isTombstone(\n item: NotificationListItem,\n): item is Extract<NotificationListItem, { _tombstone: true }> {\n return '_tombstone' in item && item._tombstone === true;\n}\n\nexport function useNotifications(): NotificationsResult {\n const client = useKaafilClient();\n const [result, setResult] = useState<NotificationsResult>({ status: 'loading' });\n\n useEffect(() => {\n let cancelled = false;\n setResult({ status: 'loading' });\n client.notifications\n .list()\n .then((response) => {\n if (cancelled) {\n return;\n }\n const notifications = response.items.filter(\n (item): item is ManagerNotification => !isTombstone(item),\n );\n setResult({\n status: 'ready',\n notifications,\n unreadCount: notifications.filter((n) => n.readAt === null).length,\n markRead: async (id: string) => {\n await client.notifications.markRead({ id });\n },\n syncedAt: response.meta.serverTime,\n });\n })\n .catch(() => {\n if (!cancelled) {\n setResult({ status: 'error' });\n }\n });\n return () => {\n cancelled = true;\n };\n }, [client]);\n\n return result;\n}\n"]}
1
+ {"version":3,"sources":["../src/core/hooks/useConflicts.ts","../src/core/hooks/useManagerMe.ts","../src/core/hooks/useNotifications.ts"],"names":["useContext","OfflineEngineContext","useState","useOfflineEvent","useMemo","useKaafilClient","useEffect"],"mappings":";;;;;AA4BA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aAAA,CAAc,QAAA,CAAS,EAAE,IAAI,CAAA;AAAA,QAC5C,CAAA;AAAA,QACA,QAAA,EAAU,SAAS,IAAA,CAAK;AAAA,OACzB,CAAA;AAAA,IACH,CAAC,CAAA,CACA,KAAA,CAAM,MAAM;AACX,MAAA,IAAI,CAAC,SAAA,EAAW;AACd,QAAA,SAAA,CAAU,EAAE,MAAA,EAAQ,OAAA,EAAS,CAAA;AAAA,MAC/B;AAAA,IACF,CAAC,CAAA;AACH,IAAA,OAAO,MAAM;AACX,MAAA,SAAA,GAAY,IAAA;AAAA,IACd,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,MAAM,CAAC,CAAA;AAEX,EAAA,OAAO,MAAA;AACT","file":"chunk-7COMKJTM.cjs","sourcesContent":["'use client';\n\n// `08-core-hooks.md §2.7`. Every `409 CONFLICT_VERSION` op currently parked\n// and awaiting a human choice for this trip — entity-agnostic on purpose, so\n// the one shared `ConflictResolver` UI covers rooming/seating/checklist/\n// every versioned entity (`07-offline-and-sync.md §6`).\n//\n// VERIFIED SHAPE (`kaafil-js/src/offline/{outbox,reconcile}.ts`, this\n// session): a \"surface\" conflict reaches `Outbox.park()` with only\n// `{ status, code: 'CONFLICT_VERSION', userMessage }` — no row of either\n// side. The fresh server row, however, was already written into\n// `SnapshotStore` by `reconcileConflict()` before the park (its own \"why the\n// entity is re-pulled first\" header) whenever `op.entity` was set and the\n// re-read succeeded. `currentValue` below is read from there — the snapshot\n// — rather than invented on this hook's own read. `queuedValue` is the\n// parked op's own `body`, the intent that was never applied.\n\nimport type { OutboxOp } from 'kaafil-js/client';\nimport { useContext, useMemo, useState } from 'react';\nimport { OfflineEngineContext } from '../internal/contexts';\nimport type { ConflictRecord } from '../types/offline.types';\nimport { useOfflineEvent } from './useOfflineEvent';\n\nexport interface ConflictsResult {\n readonly conflicts: readonly ConflictRecord[];\n readonly resolve: (opId: string, choice: 'keep-queued' | 'keep-current') => Promise<void>;\n}\n\nfunction isVersionConflict(op: OutboxOp): boolean {\n return op.status === 'parked' && op.parkReason?.code === 'CONFLICT_VERSION';\n}\n\nexport function useConflicts(tripRef: string): ConflictsResult {\n // NOT `useOfflineEngine()` (its throwing form) — called from inside a\n // domain hook's unconditional `build()` (`createDomainHook.ts`), including\n // the render(s) before `OfflineShell` has opened an engine. No engine yet\n // means no ops to have conflicted yet — `conflicts: []`, never a crash.\n const engine = useContext(OfflineEngineContext);\n // `tick` itself is never read below beyond being a `useMemo` dependency —\n // `engine.outbox.all()` is a plain synchronous read with no reactive\n // identity of its own, so bumping this on every `sync.error`/`sync.drained`\n // is what makes the memo below re-run on the events that can change what\n // it returns.\n const [tick, forceRefresh] = useState(0);\n\n useOfflineEvent('sync.error', () => forceRefresh((current) => current + 1));\n useOfflineEvent('sync.drained', () => forceRefresh((current) => current + 1));\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: tick is a deliberate side-channel dep, forcing a re-run against the outbox's own non-reactive state on every sync event (see its declaration above).\n const conflictOps = useMemo(\n () =>\n engine === null\n ? []\n : engine.outbox.all().filter((op) => op.tripRef === tripRef && isVersionConflict(op)),\n // eslint-disable-next-line react-hooks/exhaustive-deps -- same reasoning, see the biome-ignore comment above.\n [engine, tripRef, tick],\n );\n\n const conflicts: readonly ConflictRecord[] =\n engine === null\n ? []\n : conflictOps.map((op) => {\n const currentValue =\n op.entity !== undefined\n ? engine.snapshot\n .list(op.tripRef, op.entity.listName)\n .find((row) => row.id === op.entity?.id)\n : undefined;\n return {\n opId: op.id,\n entity: op.entity?.listName ?? op.path,\n queuedValue: op.body,\n currentValue,\n };\n });\n\n async function resolve(opId: string, choice: 'keep-queued' | 'keep-current'): Promise<void> {\n if (engine === null) {\n return;\n }\n const op = engine.outbox.get(opId);\n if (op === undefined) {\n return;\n }\n if (choice === 'keep-current') {\n // `engine.discard()`, NOT `outbox.drop()`. The queue knows nothing about\n // the snapshot, so dropping a CREATE through it leaves the row the\n // manager just chose to discard on screen permanently: it is keyed on an\n // id only this device ever knew, so no pull, no delta and no tombstone\n // can ever remove it. `discard()` takes the optimistic row with the op.\n await engine.discard(opId);\n return;\n }\n // `keep-queued`: re-issue with the fresh version. The fresh row's own\n // `version` field is what `07-offline-and-sync.md §6` calls\n // `details.currentVersion`; reading it off the snapshot row this hook\n // already fetched above is the same value, sourced from the same\n // re-read `reconcileConflict()` already performed.\n const freshRow =\n op.entity !== undefined\n ? engine.snapshot\n .list(op.tripRef, op.entity.listName)\n .find((row) => row.id === op.entity?.id)\n : undefined;\n const freshVersion = freshRow?.version;\n await engine.outbox.reissue(opId, freshVersion !== undefined ? { ifMatch: freshVersion } : {});\n engine.drainer.kick();\n }\n\n return { conflicts, resolve };\n}\n","'use client';\n\n// `families/manager/01-surface.md`'s own \"trip-discovery gap\" note is now\n// stale — verified against the real engine: `GET /manager/me/trips`\n// (`client.managerMe.listTrips()`) resolves a manager's own live trip\n// assignments plus a sensible `defaultTripId`, and now also the manager's\n// own `fullName` (this build's own small engine addition —\n// `manager-me.dto.ts`'s `manager` field). This session's own product\n// decision overrides that spec note for `ManagerNowSection` and any future\n// manager composite that needs \"which trip(s) does THIS manager see\" —\n// never a host-supplied `assignedTrips` prop for those composites (that\n// prop still exists for `KaafilManagerApp`/`MyTripsScreen` themselves, per\n// spec, since a Surface's own trip-list PANE is a separate, larger\n// decision this hook does not revisit).\n//\n// Same deliberately minimal shape as `useManagerToday.ts`: a plain\n// `client.managerMe.listTrips()` call behind `useEffect`/`useState`, no\n// offline/outbox machinery (this is a live read with no mutation of its\n// own to queue), no capability gate (which trips a manager is assigned to\n// is an ingest fact, not a capability — `01-surface.md`'s own \"Gating\"\n// field, cited).\n\nimport type {\n KaafilClient,\n ManagerOwnTrip,\n ManagerOwnTripsResponse,\n OfflineEngine,\n} from 'kaafil-js/client';\nimport { useContext, useEffect, useState } from 'react';\nimport { OfflineEngineContext } from '../internal/contexts';\nimport { useKaafilClient } from './useKaafilClient';\n\n// Re-exported so a composite (`ManagerTripSection.types.ts`, `TripHero.tsx`)\n// can name one trip row's shape without importing `kaafil-js/client`\n// directly — hard rule #1.\nexport type { ManagerOwnTrip };\n\nexport interface ManagerMeLoading {\n readonly status: 'loading';\n}\n\nexport interface ManagerMeError {\n readonly status: 'error';\n}\n\nexport interface ManagerMeReady extends ManagerOwnTripsResponse {\n readonly status: 'ready';\n /** The server timestamp this read landed with (`meta.serverTime`) — never\n * a local clock read (hard rule #6). */\n readonly syncedAt: string;\n}\n\nexport type ManagerMeResult = ManagerMeLoading | ManagerMeError | ManagerMeReady;\n\n/**\n * The last answer this read actually got, per open client — the same\n * module-level, instance-keyed `WeakMap` shape `../internal/ensureTripPulled.ts`\n * already uses, and for the same reason: five composites\n * (`KaafilManagerApp`, `ManagerNowSection`, `ManagerTripSection`,\n * `ManagerChecklistSection`, `ManagerMeSection`) call this hook, and the\n * field surface mounts and unmounts them as the manager moves between tabs.\n *\n * Without this, EVERY tab switch was a fresh network read that the field\n * persona is by definition not guaranteed to be able to make. On a manager's\n * phone with no signal the read rejected, the hook reported `'error'`, and\n * every one of those composites renders nothing at all for that status — so\n * losing the network and then touching a tab emptied the trip screen, with\n * no way back short of a page reload (`architecture/06-offline-first.md`:\n * the field half must serve what it last knew rather than blank).\n *\n * It is not a cache in front of `kaafil-js` (hard rule #3): nothing is\n * reconciled, no cursor is kept, no event is subscribed to, and a live read\n * still fires on every mount so \"re-mount to refresh\" keeps working. It only\n * stops a failed read from erasing an answer the session already has.\n *\n * It dies with the tab, which is the whole reason for the durable lane below.\n */\nconst lastKnown = new WeakMap<KaafilClient, ManagerMeReady>();\n\n/**\n * The key this hook's answer is cached under in the engine's durable read\n * cache (`kaafil-js`'s `engine.reads`, credential-scoped by the engine).\n *\n * The `WeakMap` above survives a tab switch; it does not survive a RELOAD, and\n * a reload is the field surface's normal case rather than an edge one — a\n * manager's phone discards a backgrounded tab on its own. So an offline\n * manager who reloaded got `'error'` from the very first read, and every\n * composite that reads this hook renders nothing for that status: a blank\n * trip list, with their queued writes sitting intact in IndexedDB behind a\n * screen with no way into them. Durable writes the manager could not reach\n * are indistinguishable, from where they are standing, from lost ones.\n *\n * This response cannot live in the snapshot store: its rows carry a\n * `tripRef`, a name and a status but no `id` and no `version`, so there is\n * nothing for a version-guarded merge to guard (`kaafil-js/src/offline/\n * reads.ts` explains the split at length). It is a whole answer or nothing,\n * which is exactly the promise `engine.reads` makes.\n */\nconst READ_CACHE_KEY = 'manager.me.trips';\n\n/** What is actually persisted — the response plus the `meta.serverTime` it\n * landed with. The store keeps `syncedAt` itself, so only the body goes in. */\ntype CachedManagerMe = ManagerOwnTripsResponse;\n\n/**\n * `client.managerMe.listTrips()` behind a plain fetch-on-mount effect —\n * this read takes no parameter (it resolves entirely off the authenticated\n * principal, `manager-me.routes.ts`'s own header, cited), so it never\n * re-fetches on a prop change the way `useManagerToday(tripRef)` does.\n * A caller wanting \"refresh now\" re-mounts this hook's owning component.\n */\nexport function useManagerMe(): ManagerMeResult {\n const client = useKaafilClient();\n // The raw context, not `useOfflineEngine()`'s throwing form: this hook is\n // read by desk composites too, and a desk mount has no `OfflineShell` and\n // therefore no engine. With none, everything below degrades to exactly the\n // in-memory behaviour this hook had before — which is right for a surface\n // that is online by definition.\n const engine = useContext(OfflineEngineContext);\n\n // Seeded from what is already known, in order: this session's own answer,\n // then the durable one from a previous session. Both beat a skeleton, and\n // the durable one is the only one that exists after a reload.\n const [result, setResult] = useState<ManagerMeResult>(\n () => lastKnown.get(client) ?? readCached(engine) ?? { status: 'loading' },\n );\n\n useEffect(() => {\n let cancelled = false;\n setResult(lastKnown.get(client) ?? readCached(engine) ?? { status: 'loading' });\n client.managerMe\n .listTrips()\n .then((response) => {\n const { meta, ...data } = response;\n const ready: ManagerMeReady = { status: 'ready', ...data, syncedAt: meta.serverTime };\n // Recorded before the cancellation check: a response that landed is\n // true regardless of whether THIS component is still mounted to\n // render it, and the next mount should not have to re-ask.\n lastKnown.set(client, ready);\n // Fire-and-forget, and deliberately not awaited before the state is\n // set: painting the fresh answer must not wait on a disk write, and a\n // failed write costs the NEXT reload's first paint rather than this\n // one's correctness. `meta.serverTime`, never a device clock — the\n // store has no setter that would accept one (hard rule #6).\n void engine?.reads.set(READ_CACHE_KEY, data, meta.serverTime).catch(() => {\n // A full or unavailable store is not this read's problem to report.\n // The live answer above is already rendered and already correct.\n });\n if (!cancelled) {\n setResult(ready);\n }\n })\n .catch(() => {\n if (cancelled) {\n return;\n }\n // `'error'` ONLY when NOTHING is known — not this session, not the\n // last one. A read that failed after one succeeded means the device\n // is offline or the engine is unreachable, not that the manager\n // stopped being assigned to their trips; reporting `'error'` there is\n // what blanked the field surface, and after a reload it blanked it\n // from the very first read. `syncedAt` on the held value already\n // tells a caller how old the reading is.\n setResult(lastKnown.get(client) ?? readCached(engine) ?? { status: 'error' });\n });\n return () => {\n cancelled = true;\n };\n }, [client, engine]);\n\n return result;\n}\n\n/**\n * The last answer a PREVIOUS session got, if this surface has a durable store\n * at all. Returns `undefined` rather than an `'error'` so every call site can\n * fall through to the next-best source in one expression.\n */\nfunction readCached(engine: OfflineEngine | null): ManagerMeReady | undefined {\n const cached = engine?.reads.get<CachedManagerMe>(READ_CACHE_KEY);\n if (cached === undefined) {\n return undefined;\n }\n return { status: 'ready', ...cached.value, syncedAt: cached.syncedAt };\n}\n","'use client';\n\n// `08-core-hooks.md §3` table, row `useNotifications()`. Primary SDK surface\n// (verified, `kaafil-js/src/resources/notifications.ts`):\n// `notifications.list` (`managerAuth`-only), `notifications.markRead`\n// (likewise `managerAuth`-only). NOT trip-scoped — the only hook in this\n// table taking no `tripRef`. `managerAuth` is the ONLY scheme either\n// operation accepts, so this hook is structurally unreachable from the\n// `admin`/`traveller` families. `list` takes an optional `?since=` delta\n// cursor passed straight through, never a UIKit-invented filter language.\n//\n// Deliberately the same minimal shape as `useManagerToday.ts`/\n// `useManagerMe.ts`: a plain fetch-on-mount effect, no offline/outbox\n// machinery. `families/manager/11-offline-sync-and-notifications.md\n// §NotificationsFeed`'s own \"write: markRead enqueues through the outbox\n// with a fixed idempotency key\" contract is that COMPOSITE's job once it\n// is built — this hook exists now only so `ManagerNowSection`'s header\n// bell can show a real (honestly zero, until something writes a\n// notification) unread count, which needs `list()` alone. `markRead` is\n// still exposed as a direct SDK call (never mints its own idempotency key,\n// hard rule #4 — mark-read is naturally idempotent server-side per the\n// SDK's own doc comment, so no key is needed here at all) so an early\n// caller isn't blocked, but a future `NotificationsFeed` composite should\n// route its OWN write through the outbox instead of reusing this hook's\n// `markRead` as-is.\n//\n// The wire's `items` array is a discriminated union (a live row, or a\n// `{ _tombstone: true; id; version; deletedAt }` delete marker) — this hook\n// filters tombstones out of `notifications` (a plain unread-count/list\n// consumer has no use for a deleted row) rather than exposing the union to\n// every caller.\n\nimport type { NotificationsResource } from 'kaafil-js/client';\nimport { useEffect, useState } from 'react';\nimport { useKaafilClient } from './useKaafilClient';\n\n// `notifications.ts`'s resource module exports no named response type of its\n// own (unlike `manager-me.ts`'s `ManagerOwnTripsResponse`) — derived off the\n// resource's own method signature instead, `useFiles.ts`/`useExpenses.ts`'s\n// established precedent for this exact situation.\ntype NotificationListResponse = Awaited<ReturnType<NotificationsResource['list']>>;\ntype NotificationListItem = NotificationListResponse['items'][number];\n\n/** The live-row half of `NotificationListItem`'s union — a tombstone never\n * reaches a caller of this hook (see this file's own header). */\nexport type ManagerNotification = Exclude<NotificationListItem, { _tombstone: true }>;\n\nexport interface NotificationsLoading {\n readonly status: 'loading';\n}\n\nexport interface NotificationsError {\n readonly status: 'error';\n}\n\nexport interface NotificationsReady {\n readonly status: 'ready';\n readonly notifications: readonly ManagerNotification[];\n /** `notifications.filter((n) => n.readAt === null).length` — the wire\n * carries no numeric unread field of its own (verified against\n * `NotificationListResponse`), so this is a real derivation off real\n * rows, never a fabricated count. */\n readonly unreadCount: number;\n readonly markRead: (id: string) => Promise<void>;\n /** The server timestamp this read landed with (`meta.serverTime`) —\n * never a local clock read (hard rule #6). */\n readonly syncedAt: string;\n}\n\nexport type NotificationsResult = NotificationsLoading | NotificationsError | NotificationsReady;\n\nfunction isTombstone(\n item: NotificationListItem,\n): item is Extract<NotificationListItem, { _tombstone: true }> {\n return '_tombstone' in item && item._tombstone === true;\n}\n\nexport function useNotifications(): NotificationsResult {\n const client = useKaafilClient();\n const [result, setResult] = useState<NotificationsResult>({ status: 'loading' });\n\n useEffect(() => {\n let cancelled = false;\n setResult({ status: 'loading' });\n client.notifications\n .list()\n .then((response) => {\n if (cancelled) {\n return;\n }\n const notifications = response.items.filter(\n (item): item is ManagerNotification => !isTombstone(item),\n );\n setResult({\n status: 'ready',\n notifications,\n unreadCount: notifications.filter((n) => n.readAt === null).length,\n markRead: async (id: string) => {\n await client.notifications.markRead({ id });\n },\n syncedAt: response.meta.serverTime,\n });\n })\n .catch(() => {\n if (!cancelled) {\n setResult({ status: 'error' });\n }\n });\n return () => {\n cancelled = true;\n };\n }, [client]);\n\n return result;\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var chunkV45VFRBI_cjs = require('./chunk-V45VFRBI.cjs');
4
- var chunk53ITV6GF_cjs = require('./chunk-53ITV6GF.cjs');
5
- var chunk4QMYUKW4_cjs = require('./chunk-4QMYUKW4.cjs');
3
+ var chunkLBTAK5JA_cjs = require('./chunk-LBTAK5JA.cjs');
4
+ var chunk4R7QBTNL_cjs = require('./chunk-4R7QBTNL.cjs');
5
+ var chunkASFUY3IE_cjs = require('./chunk-ASFUY3IE.cjs');
6
6
  var client = require('kaafil-js/client');
7
7
  var react = require('react');
8
8
 
@@ -40,10 +40,10 @@ function deriveWriteStatus(revoked, saveOp, submitOp, isOnline) {
40
40
  return { status: kind === "submit" ? "submitting" : "saving", op };
41
41
  }
42
42
  function useShareForms(token) {
43
- const client$1 = chunk4QMYUKW4_cjs.useKaafilClient();
44
- const persona = chunk4QMYUKW4_cjs.usePersona();
45
- const engine = chunkV45VFRBI_cjs.useOfflineEngine();
46
- const { now, sinceLastSync } = chunk53ITV6GF_cjs.useServerTime();
43
+ const client$1 = chunkASFUY3IE_cjs.useKaafilClient();
44
+ const persona = chunkASFUY3IE_cjs.usePersona();
45
+ const engine = chunkLBTAK5JA_cjs.useOfflineEngine();
46
+ const { now, sinceLastSync } = chunk4R7QBTNL_cjs.useServerTime();
47
47
  const serverTimeKnown = sinceLastSync !== void 0;
48
48
  const [forms, setForms] = react.useState(void 0);
49
49
  const [serverTime, setServerTime] = react.useState(void 0);
@@ -64,7 +64,7 @@ function useShareForms(token) {
64
64
  }, [client$1, token]);
65
65
  react.useEffect(() => {
66
66
  if (persona !== "share") {
67
- if (chunk4QMYUKW4_cjs.isDevelopment()) {
67
+ if (chunkASFUY3IE_cjs.isDevelopment()) {
68
68
  throw new Error(
69
69
  "useShareForms() was called from a manager/agencyAdmin session \u2014 this hook is `share`-only (families/traveller/02-forms.md, `ShareFormsSection`)."
70
70
  );
@@ -86,7 +86,7 @@ function useShareForms(token) {
86
86
  window.removeEventListener("offline", handleOffline);
87
87
  };
88
88
  }, []);
89
- chunk4QMYUKW4_cjs.useOfflineEvent("share.revoked", () => {
89
+ chunkASFUY3IE_cjs.useOfflineEvent("share.revoked", () => {
90
90
  setRevoked(true);
91
91
  for (const op of engine.outbox.all()) {
92
92
  if (op.tripRef === token && (op.status === "pending" || op.status === "parked")) {
@@ -94,7 +94,7 @@ function useShareForms(token) {
94
94
  }
95
95
  }
96
96
  });
97
- const saveMutation = chunk4QMYUKW4_cjs.useOfflineMutation({
97
+ const saveMutation = chunkASFUY3IE_cjs.useOfflineMutation({
98
98
  tripRef: token,
99
99
  enqueue: (mutationEngine, input) => {
100
100
  const query = input.travellerRef !== void 0 ? `?travellerRef=${encodeURIComponent(input.travellerRef)}` : "";
@@ -129,7 +129,7 @@ function useShareForms(token) {
129
129
  });
130
130
  }
131
131
  });
132
- const submitMutation = chunk4QMYUKW4_cjs.useOfflineMutation({
132
+ const submitMutation = chunkASFUY3IE_cjs.useOfflineMutation({
133
133
  tripRef: token,
134
134
  enqueue: (mutationEngine, input) => {
135
135
  const query = input.travellerRef !== void 0 ? `?travellerRef=${encodeURIComponent(input.travellerRef)}` : "";
@@ -180,9 +180,9 @@ function useShareForms(token) {
180
180
  }
181
181
  var NON_SECTION_KEYS = /* @__PURE__ */ new Set(["trip", "meta"]);
182
182
  function useShareSnapshot(token, options) {
183
- const client = chunk4QMYUKW4_cjs.useKaafilClient();
184
- const persona = chunk4QMYUKW4_cjs.usePersona();
185
- const engine = react.useContext(chunk4QMYUKW4_cjs.OfflineEngineContext);
183
+ const client = chunkASFUY3IE_cjs.useKaafilClient();
184
+ const persona = chunkASFUY3IE_cjs.usePersona();
185
+ const engine = react.useContext(chunkASFUY3IE_cjs.OfflineEngineContext);
186
186
  const [sections, setSections] = react.useState(void 0);
187
187
  const [trip, setTrip] = react.useState(void 0);
188
188
  const [serverTime, setServerTime] = react.useState(void 0);
@@ -191,7 +191,7 @@ function useShareSnapshot(token, options) {
191
191
  );
192
192
  react.useEffect(() => {
193
193
  if (persona !== "share") {
194
- if (chunk4QMYUKW4_cjs.isDevelopment()) {
194
+ if (chunkASFUY3IE_cjs.isDevelopment()) {
195
195
  throw new Error(
196
196
  "useShareSnapshot() was called from a manager/agencyAdmin session \u2014 this hook is `share`-only (08-core-hooks.md \xA73.1)."
197
197
  );
@@ -245,5 +245,5 @@ function useShareSnapshot(token, options) {
245
245
 
246
246
  exports.useShareForms = useShareForms;
247
247
  exports.useShareSnapshot = useShareSnapshot;
248
- //# sourceMappingURL=chunk-OOHU3ECL.cjs.map
249
- //# sourceMappingURL=chunk-OOHU3ECL.cjs.map
248
+ //# sourceMappingURL=chunk-7O3TPYK4.cjs.map
249
+ //# sourceMappingURL=chunk-7O3TPYK4.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/hooks/useShareForms.ts","../src/core/hooks/useShareSnapshot.ts"],"names":["client","useKaafilClient","usePersona","useOfflineEngine","useServerTime","useState","useCallback","useEffect","isDevelopment","useOfflineEvent","useOfflineMutation","SyncOpMethod","useContext","OfflineEngineContext"],"mappings":";;;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AACZ,MAAA,kBAAA,EAAmB;AACnB,MAAA,kBAAA,EAAmB;AAAA,IACrB,CAAA;AAAA,EACF,GAAG,CAAC,MAAA,EAAQ,OAAA,EAAS,KAAA,EAAO,MAAM,CAAC,CAAA;AAEnC,EAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,IAAA,OAAO,EAAE,QAAQ,QAAA,EAAU,QAAA,EAAU,4BAAY,IAAI,GAAA,EAAI,EAAG,IAAA,EAAM,UAAA,EAAW;AAAA,EAC/E;AACA,EAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,IAAA,OAAO,EAAE,MAAA,EAAQ,SAAA,EAAW,QAAA,kBAAU,IAAI,KAAI,EAAG,IAAA,EAAM,MAAA,EAAW,UAAA,EAAY,MAAA,EAAU;AAAA,EAC1F;AACA,EAAA,OAAO,EAAE,MAAA,EAAQ,OAAA,EAAS,QAAA,EAAU,MAAM,UAAA,EAAW;AACvD","file":"chunk-OOHU3ECL.cjs","sourcesContent":["'use client';\n\n// `08-core-hooks.md §3` (new row — `ShareFormsSection`'s `Backed by`,\n// `ui-kit/families/traveller/02-forms.md`, cited): the write-back half of\n// the traveller share surface. `forms` is the ONLY write-back section on\n// the whole share surface; every other section is read-only through\n// `useShareSnapshot()` alone. This hook wraps the four dedicated\n// `shareAuth`-only routes `share.forms.{list,render,save,submit}`\n// (`kaafil-js/src/resources/share.ts`, verified this session).\n//\n// ── WHY THIS HOOK DOES NOT ALSO CALL `useShareSnapshot()` ──────────────────\n//\n// `02-forms.md`'s `Backed by` field says the section's own `/core` hook\n// \"composes both\" — the snapshot (for `forms` section presence) and the\n// dedicated routes (for the actual list/render/save/submit). This file\n// deliberately does NOT reproduce the snapshot fetch: `ShareFormsSection`\n// (future work, not this file) is only ever mounted once its own call to\n// `useShareSnapshot(token)` has already confirmed `sections.has('forms')`\n// (`01-share-sections.md`'s registry-driven mount rule) — duplicating that\n// fetch here would be a second, redundant read of the same snapshot for no\n// new information, and this hook has nothing to add to a presence check it\n// does not own. What this file DOES independently reproduce is\n// `useShareSnapshot()`'s own persona gate and its `share.expired`/\n// `share.revoked` subscriptions (`08-core-hooks.md §0`: \"every domain hook\n// is capability-gated internally\" — the share-surface's equivalent gate is\n// the persona check, applied the same way every other hook in this catalog\n// applies its own).\n//\n// ── SPEC TENSION FLAGGED: \"cache-first\" vs. \"the dedicated routes\" ─────────\n//\n// `02-forms.md`'s `Offline` field says the list \"rides the scoped share\n// snapshot cache-first, same as every other section\", but its own `Backed\n// by` field says in the same breath that \"the actual form list/render/\n// save/submit calls ride the dedicated forms-share routes\" — and\n// `ShareSnapshotResponse`'s per-section shape (verified,\n// `useShareSnapshot.ts`) carries no registered `forms` array with\n// `fillState`/`opensAt`/`closesAt` fields; only `ShareFormsListResponse`\n// (`GET /api/v1/share/{token}/forms`) does. This file follows the more\n// specific, SDK-verified statement — a LIVE `share.forms.list()` call,\n// refreshable on demand — the same \"own live-fetch sub-state, not a\n// `snapshot.updated` subscription\" pattern `useRooming.ts`'s\n// `unassignedPool` already uses for an analogous non-delta read. Flagged\n// for the doc owner to resolve; not silently picked one way with no trace.\n//\n// ── `clientToken` IS NOT A HOOK-MINTED IDEMPOTENCY KEY ──────────────────────\n//\n// `ShareSaveFormRequest`/`ShareSubmitFormRequest` (verified,\n// `kaafil-js/openapi/openapi.json`) require a body-level `clientToken`\n// (16-255 chars) — the SDK's own comment on `share.ts` calls it \"this\n// route's own de-dupe key, distinct from the automatic `Idempotency-Key`\n// header\", and `modules/forms/FRD.md §4.1/§8` calls it \"a fixed\n// `clientToken` generated once at enqueue and reused on every retry\" —\n// i.e. exactly the write-once, replay-unchanged lifecycle hard rule #4\n// reserves for `OfflineEngine.enqueue()`'s own internal idempotency-key\n// minting. This hook does NOT invent a value for it (that would be exactly\n// the \"hook mints its own idempotency key\" anti-pattern hard rule #4\n// forbids, even though `clientToken` is a different field from the\n// transport `Idempotency-Key` header `enqueue()` mints separately and\n// automatically for every op, share writes included). Instead\n// `ShareFormWriteInput.clientToken` is a REQUIRED field the CALLER\n// supplies — a future `ShareFormsSection`/`ShareFormFillScreen` generates\n// one value per form-fill session (e.g. once, the first time a field is\n// touched) and passes the SAME value to every `save()`/`submit()` call for\n// that session, which is what makes retries of the SAME logical write\n// dedupe wire-side. This hook only ever forwards it into the body verbatim.\n//\n// ── REVOCATION DROPS QUEUED WRITES — A REAL SDK GAP, WORKED AROUND HERE ────\n//\n// `02-forms.md`'s `Offline` field: \"Revocation is different and has no\n// grace: a `REVOKED` token drops queued writes unsent and purges the local\n// copy immediately.\" Verified against `kaafil-js/src/offline/share.ts`\n// this session: `ShareGuard.invalidate()` treats `'expired'` and\n// `'revoked'` IDENTICALLY — it purges the read snapshot in both cases and\n// only PRESERVES (never drops) the outbox either way; nothing in\n// `kaafil-js` currently distinguishes \"grace-covered\" from \"unsent, drop\n// it\" at the outbox level. This is a genuine SDK/spec disagreement — see\n// this file's final report note. Rather than leave the spec's hard\n// requirement unmet, this hook enforces it locally on `share.revoked`,\n// riding the outbox's own existing `drop()` primitive (the identical call\n// `useConflicts()`'s `'keep-current'` resolution already makes) — this is\n// composing an existing primitive in reaction to an event, not a second\n// sync engine (hard rule #3): no retry ladder, no cache, no idempotency\n// logic is reimplemented here, only \"remove this op from the outbox\".\n\nimport type { KaafilClient, OutboxOp } from 'kaafil-js/client';\nimport { SyncOpMethod } from 'kaafil-js/client';\nimport { useCallback, useEffect, useState } from 'react';\nimport { isDevelopment } from '../internal/isDevelopment';\nimport { useKaafilClient } from './useKaafilClient';\nimport { useOfflineEngine } from './useOfflineEngine';\nimport { useOfflineEvent } from './useOfflineEvent';\nimport { useOfflineMutation } from './useOfflineMutation';\nimport { usePersona } from './usePersona';\nimport { useServerTime } from './useServerTime';\n\ntype ShareFormsClient = Pick<KaafilClient, 'share'>;\n\n/** One row of `GET /api/v1/share/{token}/forms` — `ShareFormsListResponse`\n * (verified, `kaafil-js/openapi/openapi.json`). Metadata only: no prefill,\n * no field list, no answers (`FRD:traveller-share §4.8`) — that detail\n * arrives only from `renderForm()` below. */\nexport interface ShareFormListItem {\n readonly formId: string;\n readonly key: string;\n readonly title: string;\n readonly phase: string;\n readonly required: boolean;\n readonly fillState: string;\n readonly opensAt: string | null;\n readonly closesAt: string | null;\n readonly responseStatus: string | null;\n readonly submittedAt: string | null;\n}\n\n/** One answer in a `save`/`submit` body — `ShareSaveFormRequest.answers[]`\n * / `ShareSubmitFormRequest.answers[]` (verified). */\nexport interface ShareFormAnswer {\n readonly fieldKey: string;\n readonly value: unknown;\n}\n\nexport interface ShareFormWriteInput {\n readonly formId: string;\n readonly answers: readonly ShareFormAnswer[];\n /** This route's own de-dupe key — REQUIRED by the wire schema. See this\n * file's header (\"`clientToken` IS NOT A HOOK-MINTED IDEMPOTENCY KEY\") —\n * the caller mints this once per form-fill session and reuses it across\n * every save/submit/retry of that session; this hook never generates it. */\n readonly clientToken: string;\n /** Group fill within the same `TripTraveller.partyId` — omit when the\n * token itself already scopes to a single traveller. */\n readonly travellerRef?: string;\n readonly startNew?: boolean;\n readonly isAnonymous?: boolean;\n}\n\nexport type ShareFormsListStatus = 'loading' | 'list-empty' | 'list-populated' | 'not-found';\n\n/**\n * The write-side status a `save()`/`submit()` call's tracked `OutboxOp`\n * resolves to. Deliberately excludes `'filling'` (`02-forms.md`'s own\n * `States` list also names it): `'filling'` is \"the traveller is editing\n * fields, no request in flight yet\" — a pure local UI mode with no\n * server/outbox signal behind it, so it belongs to the composite that owns\n * the form's field state, never to this hook, which only ever reflects\n * something async.\n */\nexport type ShareFormsWriteStatus =\n | 'idle'\n | 'saving'\n | 'submitting'\n | 'submitted'\n | 'conflicted'\n | 'subject-required'\n | 'queued-offline'\n | 'dropped-on-revoke';\n\nexport interface ShareFormsResult {\n readonly status: ShareFormsListStatus;\n /** `[]` in both the `'loading'` and the `'list-empty'` states — a\n * consumer distinguishes them via `status`, never via array emptiness\n * alone (`02-forms.md`'s `Gating`: an empty list is a NORMAL steady\n * state, never an error, never a placeholder). */\n readonly forms: readonly ShareFormListItem[];\n readonly serverTime: string | undefined;\n /** Re-runs `share.forms.list()`. A composite calls this after a\n * `submit()` lands, since submitting can change another form's\n * `fillState` (e.g. an any-phase trigger opening a follow-up form). */\n readonly refresh: () => Promise<void>;\n /** `GET /api/v1/share/{token}/forms/{formId}` — the fully-resolved,\n * ready-to-paint form (definition merged with any in-progress answers).\n * An open shape (`ShareRenderResponse` has no closed schema yet,\n * verified) — a live call, not cached, matching `save`/`submit`'s own\n * un-cached write path. */\n readonly renderForm: (\n formId: string,\n options?: { readonly travellerRef?: string },\n ) => Promise<Record<string, unknown>>;\n /** An in-progress save — no required-field validation server-side. */\n readonly save: (input: ShareFormWriteInput) => Promise<OutboxOp>;\n /** Finalizes the response — full validation, one transaction. */\n readonly submit: (input: ShareFormWriteInput) => Promise<OutboxOp>;\n /** The combined save/submit write status — see `ShareFormsWriteStatus`. */\n readonly writeStatus: ShareFormsWriteStatus;\n /** The most recently tracked save/submit `OutboxOp`, or `undefined`\n * before either has ever been called. */\n readonly writeOp: OutboxOp | undefined;\n}\n\nfunction deriveListStatus(\n forms: readonly ShareFormListItem[] | undefined,\n listFailed: boolean,\n): ShareFormsListStatus {\n if (forms === undefined) {\n return listFailed ? 'not-found' : 'loading';\n }\n return forms.length === 0 ? 'list-empty' : 'list-populated';\n}\n\nfunction deriveWriteStatus(\n revoked: boolean,\n saveOp: OutboxOp | undefined,\n submitOp: OutboxOp | undefined,\n isOnline: boolean,\n): { readonly status: ShareFormsWriteStatus; readonly op: OutboxOp | undefined } {\n if (revoked) {\n return { status: 'dropped-on-revoke', op: submitOp ?? saveOp };\n }\n // `submit` always takes precedence when both are in play — finishing a\n // submission is the more advanced, more important-to-surface state of\n // the two for the same form.\n const active = submitOp !== undefined ? { op: submitOp, kind: 'submit' as const } : undefined;\n const fallback =\n active ?? (saveOp !== undefined ? { op: saveOp, kind: 'save' as const } : undefined);\n if (fallback === undefined) {\n return { status: 'idle', op: undefined };\n }\n const { op, kind } = fallback;\n if (op.status === 'parked') {\n if (op.parkReason?.code === 'CONFLICT_VERSION') {\n return { status: 'conflicted', op };\n }\n if (op.parkReason?.code === 'SUBJECT_REQUIRED') {\n return { status: 'subject-required', op };\n }\n // Any other park reason (e.g. `ShareWriteGraceExpired` —\n // `kaafil-js/src/offline/share.ts`, a grace window that closed before\n // this op ever synced) reports the same as a still-queued offline\n // write: the honest \"still catching up\" framing until it is provably\n // gone (`02-forms.md`'s `Offline` field). A distinct terminal wording\n // for that specific park reason is `ShareFormsSection`'s own\n // presentation concern, not this hook's.\n return { status: 'queued-offline', op };\n }\n if (op.status === 'done') {\n return { status: kind === 'submit' ? 'submitted' : 'idle', op };\n }\n // pending or inflight.\n if (!isOnline) {\n return { status: 'queued-offline', op };\n }\n return { status: kind === 'submit' ? 'submitting' : 'saving', op };\n}\n\nexport function useShareForms(token: string): ShareFormsResult {\n const client = useKaafilClient() as ShareFormsClient;\n const persona = usePersona();\n const engine = useOfflineEngine();\n const { now, sinceLastSync } = useServerTime();\n // `now()` throws before this session's first `snapshot.updated` event —\n // see `useServerTime.ts`'s own \"CALLERS: guard the call site\" note. This\n // hook's writes stay legal without a stamp (see the `enqueuedAt` call\n // sites below), so the guard is \"can I use it\", never \"must I have it\".\n const serverTimeKnown = sinceLastSync !== undefined;\n\n const [forms, setForms] = useState<readonly ShareFormListItem[] | undefined>(undefined);\n const [serverTime, setServerTime] = useState<string | undefined>(undefined);\n const [listFailed, setListFailed] = useState(false);\n const [revoked, setRevoked] = useState(false);\n const [isOnline, setIsOnline] = useState(\n () => typeof navigator === 'undefined' || navigator.onLine,\n );\n\n const fetchList = useCallback(async (): Promise<void> => {\n try {\n const response = await client.share.forms.list({ token });\n setForms(response.items);\n setServerTime(response.meta.serverTime);\n setListFailed(false);\n } catch {\n // `GET .../forms` only ever fails `RESOURCE_NOT_FOUND` (`FRD:\n // traveller-share §4.1`'s route table, verified) — the share 404\n // carve-out means dark/cross-scope/genuinely-gone collapse to one\n // shape, same reasoning `useShareSnapshot()` applies to its own read.\n setListFailed(true);\n }\n }, [client, token]);\n\n useEffect(() => {\n if (persona !== 'share') {\n if (isDevelopment()) {\n throw new Error(\n 'useShareForms() was called from a manager/agencyAdmin session — ' +\n 'this hook is `share`-only (families/traveller/02-forms.md, `ShareFormsSection`).',\n );\n }\n return;\n }\n void fetchList();\n }, [persona, fetchList]);\n\n // A browser-level connectivity signal, same source `useOutboxStatus()`\n // reads (`kaafil-js`'s `OfflineEngine` exposes no queryable connectivity\n // flag of its own — see that hook's own header, verified again here).\n useEffect(() => {\n if (typeof window === 'undefined') {\n return;\n }\n const handleOnline = (): void => setIsOnline(true);\n const handleOffline = (): void => setIsOnline(false);\n window.addEventListener('online', handleOnline);\n window.addEventListener('offline', handleOffline);\n return () => {\n window.removeEventListener('online', handleOnline);\n window.removeEventListener('offline', handleOffline);\n };\n }, []);\n\n useOfflineEvent('share.revoked', () => {\n setRevoked(true);\n // See this file's header (\"REVOCATION DROPS QUEUED WRITES\"). Only this\n // token's own lane, and only ops still in play (a `'done'` op already\n // landed and has nothing left to drop).\n for (const op of engine.outbox.all()) {\n if (op.tripRef === token && (op.status === 'pending' || op.status === 'parked')) {\n void engine.outbox.drop(op.id);\n }\n }\n });\n\n const saveMutation = useOfflineMutation<ShareFormWriteInput>({\n tripRef: token,\n enqueue: (mutationEngine, input) => {\n const query =\n input.travellerRef !== undefined\n ? `?travellerRef=${encodeURIComponent(input.travellerRef)}`\n : '';\n return mutationEngine.enqueue({\n tripRef: token,\n method: SyncOpMethod.Post,\n path: `/api/v1/share/${token}/forms/${input.formId}/save${query}`,\n // Hardcoded literal, not imported: `OperationId` is not exported\n // from `kaafil-js/client`'s public surface (same reasoning\n // `useRooming.ts` documents). Value verified against\n // `kaafil-js/src/generated/security.ts` this session:\n // `OperationId.ShareSaveForm === 'shareSaveForm'`.\n operationId: 'shareSaveForm' as never,\n body: {\n answers: input.answers,\n clientToken: input.clientToken,\n ...(input.startNew !== undefined ? { startNew: input.startNew } : {}),\n ...(input.isAnonymous !== undefined ? { isAnonymous: input.isAnonymous } : {}),\n },\n // The server-anchored \"now\" this write was created at — never\n // `Date.now()`/`new Date()` (hard rule #6) — `EnqueueWriteOptions\n // .enqueuedAt`'s own doc comment: \"client-attested and only ever\n // used by the server to REFUSE\" (the 7-day post-expiry grace\n // check). Optional on the wire, and genuinely omitted here on a\n // cold session: `useServerTime().now()` throws before this\n // session's very first `snapshot.updated` event has landed (its\n // own documented behaviour, guarded at the call site exactly as\n // its header instructs) — a share write attempted in that narrow\n // window still enqueues durably, just without a client-attested\n // stamp for the server's grace check to read.\n ...(serverTimeKnown ? { enqueuedAt: now() } : {}),\n });\n },\n });\n\n const submitMutation = useOfflineMutation<ShareFormWriteInput>({\n tripRef: token,\n enqueue: (mutationEngine, input) => {\n const query =\n input.travellerRef !== undefined\n ? `?travellerRef=${encodeURIComponent(input.travellerRef)}`\n : '';\n return mutationEngine.enqueue({\n tripRef: token,\n method: SyncOpMethod.Post,\n path: `/api/v1/share/${token}/forms/${input.formId}/submit${query}`,\n operationId: 'shareSubmitForm' as never,\n body: {\n answers: input.answers,\n clientToken: input.clientToken,\n ...(input.startNew !== undefined ? { startNew: input.startNew } : {}),\n ...(input.isAnonymous !== undefined ? { isAnonymous: input.isAnonymous } : {}),\n },\n // See the identical `save` enqueue above for why this is guarded.\n ...(serverTimeKnown ? { enqueuedAt: now() } : {}),\n });\n },\n });\n\n const renderForm = useCallback(\n async (\n formId: string,\n options?: { readonly travellerRef?: string },\n ): Promise<Record<string, unknown>> => {\n const response = await client.share.forms.render({\n token,\n formId,\n ...(options?.travellerRef !== undefined ? { travellerRef: options.travellerRef } : {}),\n });\n return response;\n },\n [client, token],\n );\n\n const { status: writeStatus, op: writeOp } = deriveWriteStatus(\n revoked,\n saveMutation.op,\n submitMutation.op,\n isOnline,\n );\n\n return {\n status: deriveListStatus(forms, listFailed),\n forms: forms ?? [],\n serverTime,\n refresh: fetchList,\n renderForm,\n save: saveMutation.mutate,\n submit: submitMutation.mutate,\n writeStatus,\n writeOp,\n };\n}\n","'use client';\n\n// `08-core-hooks.md §3.1`. The single assembled read behind the whole\n// traveller share surface. Wraps `share.snapshot()` (verified `shareAuth`\n// -only in `security.ts` — no `apiKeyAuth` alternative exists for any\n// `share.*` operation), read cache-first from the snapshot once\n// `OfflineEngine`'s `share` option is configured.\n//\n// VERIFIED SHAPE (`openapi/openapi.json`'s `ShareSnapshotResponse`, this\n// session): a flat object with one property PER section key, each present\n// only when the link exposes it and data exists — never `null`, never an\n// empty placeholder — plus a `trip` echo (`name`/`startDate`/`endDate`/\n// `timezone`/`phase`) that is NOT one of the thirteen section flags\n// (`09-registries.md §5`). This hook builds `sections` by taking every own\n// key off the response except `trip` and `meta` — additive-safe against a\n// future 14th section key without needing this file to enumerate all\n// thirteen by name.\n//\n// `trip` and the server clock are surfaced as their OWN top-level fields on\n// `ShareSnapshotResult`, never folded into `sections`: every consumer of\n// `sections` (starting with `KaafilShareView`, which walks the map and\n// renders one composite per key) treats \"is this key present\" as \"should I\n// render a section for it\" — letting `trip`/`meta` leak into that map would\n// make the view try to mount a `<ShareTripSection>`/`<ShareMetaSection>`\n// that has never existed. But every traveller composite still needs BOTH:\n// `trip.timezone` is the one zone `DateDisplay`/`TimeDisplay` may legally\n// anchor to on this surface (never the device zone, never a fabricated\n// `'UTC'`), `trip.phase` lets a composite react to PRE_DEPARTURE/ON_TRIP/\n// POST_TRIP, and `meta.serverTime` is the only trusted \"now\" a share\n// composite may read without going through `useServerTime()` (hard rule\n// #6 — no `Date.now()`/`new Date()` in `src/core`). Hence: two extra return\n// fields, kept structurally apart from the section map they must never\n// pollute.\n\nimport type { KaafilClient } from 'kaafil-js/client';\nimport { useContext, useEffect, useState } from 'react';\nimport { OfflineEngineContext } from '../internal/contexts';\nimport { isDevelopment } from '../internal/isDevelopment';\nimport { useKaafilClient } from './useKaafilClient';\nimport { usePersona } from './usePersona';\n\nexport interface ShareSnapshotOptions {\n readonly travellerRef?: string;\n}\n\n// Derived from the SDK's own return type rather than hand-copied — this\n// stays correct for free if `kaafil-js` grows another `trip` field, instead\n// of silently drifting the way the old `'UTC'` constants did.\ntype ShareSnapshotResponse = Awaited<ReturnType<KaafilClient['share']['snapshot']>>;\n\n/** The trip echo every snapshot response carries — `name`/`startDate`/\n * `endDate` plus the two fields this hook used to throw away:\n * `timezone` (the IANA zone every traveller-facing render must anchor to)\n * and `phase` (server-computed `PRE_DEPARTURE`/`ON_TRIP`/`POST_TRIP`). */\nexport type ShareSnapshotTrip = ShareSnapshotResponse['trip'];\n\nexport interface ShareSnapshotResult {\n readonly status: 'loading' | 'ready' | 'expired' | 'revoked' | 'not-found';\n readonly sections: ReadonlyMap<string, unknown>;\n /** The snapshot's `trip` echo, or `undefined` before any response has\n * landed (mirrors `sections`' own \"empty until ready\" behaviour). NEVER a\n * section key — see this file's header. */\n readonly trip: ShareSnapshotTrip | undefined;\n /** `meta.serverTime` off the most recently landed snapshot response — the\n * only trusted clock a share composite may read (hard rule #6). Kept\n * separate from `useServerTime()`'s own stream (which advances off\n * `OfflineEngine`'s `snapshot.updated` event, not this hook's own fetch)\n * so a composite that only ever calls `useShareSnapshot()` still has a\n * real server stamp to compare against without also wiring the offline\n * engine's event stream. `undefined` before any response has landed. */\n readonly serverTime: string | undefined;\n}\n\nconst NON_SECTION_KEYS = new Set(['trip', 'meta']);\n\nexport function useShareSnapshot(\n token: string,\n options?: ShareSnapshotOptions,\n): ShareSnapshotResult {\n void options; // `travellerRef` narrows which subject-token rows the server\n // itself returns for a `travellerRef`-scoped share link — this hook has no\n // client-side use for it beyond passing the token through; the server does\n // the scoping (`09-registries.md §5`, `families/traveller/01-share-sections.md`, cited).\n\n const client = useKaafilClient();\n const persona = usePersona();\n const engine = useContext(OfflineEngineContext);\n const [sections, setSections] = useState<ReadonlyMap<string, unknown> | undefined>(undefined);\n const [trip, setTrip] = useState<ShareSnapshotTrip | undefined>(undefined);\n const [serverTime, setServerTime] = useState<string | undefined>(undefined);\n const [terminal, setTerminal] = useState<'expired' | 'revoked' | 'not-found' | undefined>(\n undefined,\n );\n\n useEffect(() => {\n if (persona !== 'share') {\n if (isDevelopment()) {\n throw new Error(\n 'useShareSnapshot() was called from a manager/agencyAdmin session — ' +\n 'this hook is `share`-only (08-core-hooks.md §3.1).',\n );\n }\n return;\n }\n\n let cancelled = false;\n async function load(): Promise<void> {\n try {\n const response = await client.share.snapshot({ token });\n if (cancelled) {\n return;\n }\n const map = new Map<string, unknown>();\n for (const [key, value] of Object.entries(response)) {\n if (!NON_SECTION_KEYS.has(key)) {\n map.set(key, value);\n }\n }\n setSections(map);\n setTrip(response.trip);\n setServerTime(response.meta.serverTime);\n } catch {\n // `06-capability-and-personas.md §9`: dark, cross-scope, and\n // genuinely-gone all collapse to the identical shape here — this\n // hook cannot and must not try to distinguish them, so any failure\n // to read the snapshot at all reports the same `'not-found'`.\n if (!cancelled) {\n setTerminal('not-found');\n }\n }\n }\n void load();\n\n if (engine === null) {\n return () => {\n cancelled = true;\n };\n }\n const unsubscribeExpired = engine.events.on('share.expired', () => setTerminal('expired'));\n const unsubscribeRevoked = engine.events.on('share.revoked', () => setTerminal('revoked'));\n return () => {\n cancelled = true;\n unsubscribeExpired();\n unsubscribeRevoked();\n };\n }, [client, persona, token, engine]);\n\n if (terminal !== undefined) {\n return { status: terminal, sections: sections ?? new Map(), trip, serverTime };\n }\n if (sections === undefined) {\n return { status: 'loading', sections: new Map(), trip: undefined, serverTime: undefined };\n }\n return { status: 'ready', sections, trip, serverTime };\n}\n"]}
1
+ {"version":3,"sources":["../src/core/hooks/useShareForms.ts","../src/core/hooks/useShareSnapshot.ts"],"names":["client","useKaafilClient","usePersona","useOfflineEngine","useServerTime","useState","useCallback","useEffect","isDevelopment","useOfflineEvent","useOfflineMutation","SyncOpMethod","useContext","OfflineEngineContext"],"mappings":";;;;;;;;AA6LA,SAAS,gBAAA,CACP,OACA,UAAA,EACsB;AACtB,EAAA,IAAI,UAAU,MAAA,EAAW;AACvB,IAAA,OAAO,aAAa,WAAA,G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AS,KAAA,EAAO,MAAM,CAAC,CAAA;AAEnC,EAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,IAAA,OAAO,EAAE,QAAQ,QAAA,EAAU,QAAA,EAAU,4BAAY,IAAI,GAAA,EAAI,EAAG,IAAA,EAAM,UAAA,EAAW;AAAA,EAC/E;AACA,EAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,IAAA,OAAO,EAAE,MAAA,EAAQ,SAAA,EAAW,QAAA,kBAAU,IAAI,KAAI,EAAG,IAAA,EAAM,MAAA,EAAW,UAAA,EAAY,MAAA,EAAU;AAAA,EAC1F;AACA,EAAA,OAAO,EAAE,MAAA,EAAQ,OAAA,EAAS,QAAA,EAAU,MAAM,UAAA,EAAW;AACvD","file":"chunk-7O3TPYK4.cjs","sourcesContent":["'use client';\n\n// `08-core-hooks.md §3` (new row — `ShareFormsSection`'s `Backed by`,\n// `ui-kit/families/traveller/02-forms.md`, cited): the write-back half of\n// the traveller share surface. `forms` is the ONLY write-back section on\n// the whole share surface; every other section is read-only through\n// `useShareSnapshot()` alone. This hook wraps the four dedicated\n// `shareAuth`-only routes `share.forms.{list,render,save,submit}`\n// (`kaafil-js/src/resources/share.ts`, verified this session).\n//\n// ── WHY THIS HOOK DOES NOT ALSO CALL `useShareSnapshot()` ──────────────────\n//\n// `02-forms.md`'s `Backed by` field says the section's own `/core` hook\n// \"composes both\" — the snapshot (for `forms` section presence) and the\n// dedicated routes (for the actual list/render/save/submit). This file\n// deliberately does NOT reproduce the snapshot fetch: `ShareFormsSection`\n// (future work, not this file) is only ever mounted once its own call to\n// `useShareSnapshot(token)` has already confirmed `sections.has('forms')`\n// (`01-share-sections.md`'s registry-driven mount rule) — duplicating that\n// fetch here would be a second, redundant read of the same snapshot for no\n// new information, and this hook has nothing to add to a presence check it\n// does not own. What this file DOES independently reproduce is\n// `useShareSnapshot()`'s own persona gate and its `share.expired`/\n// `share.revoked` subscriptions (`08-core-hooks.md §0`: \"every domain hook\n// is capability-gated internally\" — the share-surface's equivalent gate is\n// the persona check, applied the same way every other hook in this catalog\n// applies its own).\n//\n// ── SPEC TENSION FLAGGED: \"cache-first\" vs. \"the dedicated routes\" ─────────\n//\n// `02-forms.md`'s `Offline` field says the list \"rides the scoped share\n// snapshot cache-first, same as every other section\", but its own `Backed\n// by` field says in the same breath that \"the actual form list/render/\n// save/submit calls ride the dedicated forms-share routes\" — and\n// `ShareSnapshotResponse`'s per-section shape (verified,\n// `useShareSnapshot.ts`) carries no registered `forms` array with\n// `fillState`/`opensAt`/`closesAt` fields; only `ShareFormsListResponse`\n// (`GET /api/v1/share/{token}/forms`) does. This file follows the more\n// specific, SDK-verified statement — a LIVE `share.forms.list()` call,\n// refreshable on demand — the same \"own live-fetch sub-state, not a\n// `snapshot.updated` subscription\" pattern `useRooming.ts`'s\n// `unassignedPool` already uses for an analogous non-delta read. Flagged\n// for the doc owner to resolve; not silently picked one way with no trace.\n//\n// ── `clientToken` IS NOT A HOOK-MINTED IDEMPOTENCY KEY ──────────────────────\n//\n// `ShareSaveFormRequest`/`ShareSubmitFormRequest` (verified,\n// `kaafil-js/openapi/openapi.json`) require a body-level `clientToken`\n// (16-255 chars) — the SDK's own comment on `share.ts` calls it \"this\n// route's own de-dupe key, distinct from the automatic `Idempotency-Key`\n// header\", and `modules/forms/FRD.md §4.1/§8` calls it \"a fixed\n// `clientToken` generated once at enqueue and reused on every retry\" —\n// i.e. exactly the write-once, replay-unchanged lifecycle hard rule #4\n// reserves for `OfflineEngine.enqueue()`'s own internal idempotency-key\n// minting. This hook does NOT invent a value for it (that would be exactly\n// the \"hook mints its own idempotency key\" anti-pattern hard rule #4\n// forbids, even though `clientToken` is a different field from the\n// transport `Idempotency-Key` header `enqueue()` mints separately and\n// automatically for every op, share writes included). Instead\n// `ShareFormWriteInput.clientToken` is a REQUIRED field the CALLER\n// supplies — a future `ShareFormsSection`/`ShareFormFillScreen` generates\n// one value per form-fill session (e.g. once, the first time a field is\n// touched) and passes the SAME value to every `save()`/`submit()` call for\n// that session, which is what makes retries of the SAME logical write\n// dedupe wire-side. This hook only ever forwards it into the body verbatim.\n//\n// ── REVOCATION DROPS QUEUED WRITES — A REAL SDK GAP, WORKED AROUND HERE ────\n//\n// `02-forms.md`'s `Offline` field: \"Revocation is different and has no\n// grace: a `REVOKED` token drops queued writes unsent and purges the local\n// copy immediately.\" Verified against `kaafil-js/src/offline/share.ts`\n// this session: `ShareGuard.invalidate()` treats `'expired'` and\n// `'revoked'` IDENTICALLY — it purges the read snapshot in both cases and\n// only PRESERVES (never drops) the outbox either way; nothing in\n// `kaafil-js` currently distinguishes \"grace-covered\" from \"unsent, drop\n// it\" at the outbox level. This is a genuine SDK/spec disagreement — see\n// this file's final report note. Rather than leave the spec's hard\n// requirement unmet, this hook enforces it locally on `share.revoked`,\n// riding the outbox's own existing `drop()` primitive (the identical call\n// `useConflicts()`'s `'keep-current'` resolution already makes) — this is\n// composing an existing primitive in reaction to an event, not a second\n// sync engine (hard rule #3): no retry ladder, no cache, no idempotency\n// logic is reimplemented here, only \"remove this op from the outbox\".\n\nimport type { KaafilClient, OutboxOp } from 'kaafil-js/client';\nimport { SyncOpMethod } from 'kaafil-js/client';\nimport { useCallback, useEffect, useState } from 'react';\nimport { isDevelopment } from '../internal/isDevelopment';\nimport { useKaafilClient } from './useKaafilClient';\nimport { useOfflineEngine } from './useOfflineEngine';\nimport { useOfflineEvent } from './useOfflineEvent';\nimport { useOfflineMutation } from './useOfflineMutation';\nimport { usePersona } from './usePersona';\nimport { useServerTime } from './useServerTime';\n\ntype ShareFormsClient = Pick<KaafilClient, 'share'>;\n\n/** One row of `GET /api/v1/share/{token}/forms` — `ShareFormsListResponse`\n * (verified, `kaafil-js/openapi/openapi.json`). Metadata only: no prefill,\n * no field list, no answers (`FRD:traveller-share §4.8`) — that detail\n * arrives only from `renderForm()` below. */\nexport interface ShareFormListItem {\n readonly formId: string;\n readonly key: string;\n readonly title: string;\n readonly phase: string;\n readonly required: boolean;\n readonly fillState: string;\n readonly opensAt: string | null;\n readonly closesAt: string | null;\n readonly responseStatus: string | null;\n readonly submittedAt: string | null;\n}\n\n/** One answer in a `save`/`submit` body — `ShareSaveFormRequest.answers[]`\n * / `ShareSubmitFormRequest.answers[]` (verified). */\nexport interface ShareFormAnswer {\n readonly fieldKey: string;\n readonly value: unknown;\n}\n\nexport interface ShareFormWriteInput {\n readonly formId: string;\n readonly answers: readonly ShareFormAnswer[];\n /** This route's own de-dupe key — REQUIRED by the wire schema. See this\n * file's header (\"`clientToken` IS NOT A HOOK-MINTED IDEMPOTENCY KEY\") —\n * the caller mints this once per form-fill session and reuses it across\n * every save/submit/retry of that session; this hook never generates it. */\n readonly clientToken: string;\n /** Group fill within the same `TripTraveller.partyId` — omit when the\n * token itself already scopes to a single traveller. */\n readonly travellerRef?: string;\n readonly startNew?: boolean;\n readonly isAnonymous?: boolean;\n}\n\nexport type ShareFormsListStatus = 'loading' | 'list-empty' | 'list-populated' | 'not-found';\n\n/**\n * The write-side status a `save()`/`submit()` call's tracked `OutboxOp`\n * resolves to. Deliberately excludes `'filling'` (`02-forms.md`'s own\n * `States` list also names it): `'filling'` is \"the traveller is editing\n * fields, no request in flight yet\" — a pure local UI mode with no\n * server/outbox signal behind it, so it belongs to the composite that owns\n * the form's field state, never to this hook, which only ever reflects\n * something async.\n */\nexport type ShareFormsWriteStatus =\n | 'idle'\n | 'saving'\n | 'submitting'\n | 'submitted'\n | 'conflicted'\n | 'subject-required'\n | 'queued-offline'\n | 'dropped-on-revoke';\n\nexport interface ShareFormsResult {\n readonly status: ShareFormsListStatus;\n /** `[]` in both the `'loading'` and the `'list-empty'` states — a\n * consumer distinguishes them via `status`, never via array emptiness\n * alone (`02-forms.md`'s `Gating`: an empty list is a NORMAL steady\n * state, never an error, never a placeholder). */\n readonly forms: readonly ShareFormListItem[];\n readonly serverTime: string | undefined;\n /** Re-runs `share.forms.list()`. A composite calls this after a\n * `submit()` lands, since submitting can change another form's\n * `fillState` (e.g. an any-phase trigger opening a follow-up form). */\n readonly refresh: () => Promise<void>;\n /** `GET /api/v1/share/{token}/forms/{formId}` — the fully-resolved,\n * ready-to-paint form (definition merged with any in-progress answers).\n * An open shape (`ShareRenderResponse` has no closed schema yet,\n * verified) — a live call, not cached, matching `save`/`submit`'s own\n * un-cached write path. */\n readonly renderForm: (\n formId: string,\n options?: { readonly travellerRef?: string },\n ) => Promise<Record<string, unknown>>;\n /** An in-progress save — no required-field validation server-side. */\n readonly save: (input: ShareFormWriteInput) => Promise<OutboxOp>;\n /** Finalizes the response — full validation, one transaction. */\n readonly submit: (input: ShareFormWriteInput) => Promise<OutboxOp>;\n /** The combined save/submit write status — see `ShareFormsWriteStatus`. */\n readonly writeStatus: ShareFormsWriteStatus;\n /** The most recently tracked save/submit `OutboxOp`, or `undefined`\n * before either has ever been called. */\n readonly writeOp: OutboxOp | undefined;\n}\n\nfunction deriveListStatus(\n forms: readonly ShareFormListItem[] | undefined,\n listFailed: boolean,\n): ShareFormsListStatus {\n if (forms === undefined) {\n return listFailed ? 'not-found' : 'loading';\n }\n return forms.length === 0 ? 'list-empty' : 'list-populated';\n}\n\nfunction deriveWriteStatus(\n revoked: boolean,\n saveOp: OutboxOp | undefined,\n submitOp: OutboxOp | undefined,\n isOnline: boolean,\n): { readonly status: ShareFormsWriteStatus; readonly op: OutboxOp | undefined } {\n if (revoked) {\n return { status: 'dropped-on-revoke', op: submitOp ?? saveOp };\n }\n // `submit` always takes precedence when both are in play — finishing a\n // submission is the more advanced, more important-to-surface state of\n // the two for the same form.\n const active = submitOp !== undefined ? { op: submitOp, kind: 'submit' as const } : undefined;\n const fallback =\n active ?? (saveOp !== undefined ? { op: saveOp, kind: 'save' as const } : undefined);\n if (fallback === undefined) {\n return { status: 'idle', op: undefined };\n }\n const { op, kind } = fallback;\n if (op.status === 'parked') {\n if (op.parkReason?.code === 'CONFLICT_VERSION') {\n return { status: 'conflicted', op };\n }\n if (op.parkReason?.code === 'SUBJECT_REQUIRED') {\n return { status: 'subject-required', op };\n }\n // Any other park reason (e.g. `ShareWriteGraceExpired` —\n // `kaafil-js/src/offline/share.ts`, a grace window that closed before\n // this op ever synced) reports the same as a still-queued offline\n // write: the honest \"still catching up\" framing until it is provably\n // gone (`02-forms.md`'s `Offline` field). A distinct terminal wording\n // for that specific park reason is `ShareFormsSection`'s own\n // presentation concern, not this hook's.\n return { status: 'queued-offline', op };\n }\n if (op.status === 'done') {\n return { status: kind === 'submit' ? 'submitted' : 'idle', op };\n }\n // pending or inflight.\n if (!isOnline) {\n return { status: 'queued-offline', op };\n }\n return { status: kind === 'submit' ? 'submitting' : 'saving', op };\n}\n\nexport function useShareForms(token: string): ShareFormsResult {\n const client = useKaafilClient() as ShareFormsClient;\n const persona = usePersona();\n const engine = useOfflineEngine();\n const { now, sinceLastSync } = useServerTime();\n // `now()` throws before this session's first `snapshot.updated` event —\n // see `useServerTime.ts`'s own \"CALLERS: guard the call site\" note. This\n // hook's writes stay legal without a stamp (see the `enqueuedAt` call\n // sites below), so the guard is \"can I use it\", never \"must I have it\".\n const serverTimeKnown = sinceLastSync !== undefined;\n\n const [forms, setForms] = useState<readonly ShareFormListItem[] | undefined>(undefined);\n const [serverTime, setServerTime] = useState<string | undefined>(undefined);\n const [listFailed, setListFailed] = useState(false);\n const [revoked, setRevoked] = useState(false);\n const [isOnline, setIsOnline] = useState(\n () => typeof navigator === 'undefined' || navigator.onLine,\n );\n\n const fetchList = useCallback(async (): Promise<void> => {\n try {\n const response = await client.share.forms.list({ token });\n setForms(response.items);\n setServerTime(response.meta.serverTime);\n setListFailed(false);\n } catch {\n // `GET .../forms` only ever fails `RESOURCE_NOT_FOUND` (`FRD:\n // traveller-share §4.1`'s route table, verified) — the share 404\n // carve-out means dark/cross-scope/genuinely-gone collapse to one\n // shape, same reasoning `useShareSnapshot()` applies to its own read.\n setListFailed(true);\n }\n }, [client, token]);\n\n useEffect(() => {\n if (persona !== 'share') {\n if (isDevelopment()) {\n throw new Error(\n 'useShareForms() was called from a manager/agencyAdmin session — ' +\n 'this hook is `share`-only (families/traveller/02-forms.md, `ShareFormsSection`).',\n );\n }\n return;\n }\n void fetchList();\n }, [persona, fetchList]);\n\n // A browser-level connectivity signal, same source `useOutboxStatus()`\n // reads (`kaafil-js`'s `OfflineEngine` exposes no queryable connectivity\n // flag of its own — see that hook's own header, verified again here).\n useEffect(() => {\n if (typeof window === 'undefined') {\n return;\n }\n const handleOnline = (): void => setIsOnline(true);\n const handleOffline = (): void => setIsOnline(false);\n window.addEventListener('online', handleOnline);\n window.addEventListener('offline', handleOffline);\n return () => {\n window.removeEventListener('online', handleOnline);\n window.removeEventListener('offline', handleOffline);\n };\n }, []);\n\n useOfflineEvent('share.revoked', () => {\n setRevoked(true);\n // See this file's header (\"REVOCATION DROPS QUEUED WRITES\"). Only this\n // token's own lane, and only ops still in play (a `'done'` op already\n // landed and has nothing left to drop).\n for (const op of engine.outbox.all()) {\n if (op.tripRef === token && (op.status === 'pending' || op.status === 'parked')) {\n void engine.outbox.drop(op.id);\n }\n }\n });\n\n const saveMutation = useOfflineMutation<ShareFormWriteInput>({\n tripRef: token,\n enqueue: (mutationEngine, input) => {\n const query =\n input.travellerRef !== undefined\n ? `?travellerRef=${encodeURIComponent(input.travellerRef)}`\n : '';\n return mutationEngine.enqueue({\n tripRef: token,\n method: SyncOpMethod.Post,\n path: `/api/v1/share/${token}/forms/${input.formId}/save${query}`,\n // Hardcoded literal, not imported: `OperationId` is not exported\n // from `kaafil-js/client`'s public surface (same reasoning\n // `useRooming.ts` documents). Value verified against\n // `kaafil-js/src/generated/security.ts` this session:\n // `OperationId.ShareSaveForm === 'shareSaveForm'`.\n operationId: 'shareSaveForm' as never,\n body: {\n answers: input.answers,\n clientToken: input.clientToken,\n ...(input.startNew !== undefined ? { startNew: input.startNew } : {}),\n ...(input.isAnonymous !== undefined ? { isAnonymous: input.isAnonymous } : {}),\n },\n // The server-anchored \"now\" this write was created at — never\n // `Date.now()`/`new Date()` (hard rule #6) — `EnqueueWriteOptions\n // .enqueuedAt`'s own doc comment: \"client-attested and only ever\n // used by the server to REFUSE\" (the 7-day post-expiry grace\n // check). Optional on the wire, and genuinely omitted here on a\n // cold session: `useServerTime().now()` throws before this\n // session's very first `snapshot.updated` event has landed (its\n // own documented behaviour, guarded at the call site exactly as\n // its header instructs) — a share write attempted in that narrow\n // window still enqueues durably, just without a client-attested\n // stamp for the server's grace check to read.\n ...(serverTimeKnown ? { enqueuedAt: now() } : {}),\n });\n },\n });\n\n const submitMutation = useOfflineMutation<ShareFormWriteInput>({\n tripRef: token,\n enqueue: (mutationEngine, input) => {\n const query =\n input.travellerRef !== undefined\n ? `?travellerRef=${encodeURIComponent(input.travellerRef)}`\n : '';\n return mutationEngine.enqueue({\n tripRef: token,\n method: SyncOpMethod.Post,\n path: `/api/v1/share/${token}/forms/${input.formId}/submit${query}`,\n operationId: 'shareSubmitForm' as never,\n body: {\n answers: input.answers,\n clientToken: input.clientToken,\n ...(input.startNew !== undefined ? { startNew: input.startNew } : {}),\n ...(input.isAnonymous !== undefined ? { isAnonymous: input.isAnonymous } : {}),\n },\n // See the identical `save` enqueue above for why this is guarded.\n ...(serverTimeKnown ? { enqueuedAt: now() } : {}),\n });\n },\n });\n\n const renderForm = useCallback(\n async (\n formId: string,\n options?: { readonly travellerRef?: string },\n ): Promise<Record<string, unknown>> => {\n const response = await client.share.forms.render({\n token,\n formId,\n ...(options?.travellerRef !== undefined ? { travellerRef: options.travellerRef } : {}),\n });\n return response;\n },\n [client, token],\n );\n\n const { status: writeStatus, op: writeOp } = deriveWriteStatus(\n revoked,\n saveMutation.op,\n submitMutation.op,\n isOnline,\n );\n\n return {\n status: deriveListStatus(forms, listFailed),\n forms: forms ?? [],\n serverTime,\n refresh: fetchList,\n renderForm,\n save: saveMutation.mutate,\n submit: submitMutation.mutate,\n writeStatus,\n writeOp,\n };\n}\n","'use client';\n\n// `08-core-hooks.md §3.1`. The single assembled read behind the whole\n// traveller share surface. Wraps `share.snapshot()` (verified `shareAuth`\n// -only in `security.ts` — no `apiKeyAuth` alternative exists for any\n// `share.*` operation), read cache-first from the snapshot once\n// `OfflineEngine`'s `share` option is configured.\n//\n// VERIFIED SHAPE (`openapi/openapi.json`'s `ShareSnapshotResponse`, this\n// session): a flat object with one property PER section key, each present\n// only when the link exposes it and data exists — never `null`, never an\n// empty placeholder — plus a `trip` echo (`name`/`startDate`/`endDate`/\n// `timezone`/`phase`) that is NOT one of the thirteen section flags\n// (`09-registries.md §5`). This hook builds `sections` by taking every own\n// key off the response except `trip` and `meta` — additive-safe against a\n// future 14th section key without needing this file to enumerate all\n// thirteen by name.\n//\n// `trip` and the server clock are surfaced as their OWN top-level fields on\n// `ShareSnapshotResult`, never folded into `sections`: every consumer of\n// `sections` (starting with `KaafilShareView`, which walks the map and\n// renders one composite per key) treats \"is this key present\" as \"should I\n// render a section for it\" — letting `trip`/`meta` leak into that map would\n// make the view try to mount a `<ShareTripSection>`/`<ShareMetaSection>`\n// that has never existed. But every traveller composite still needs BOTH:\n// `trip.timezone` is the one zone `DateDisplay`/`TimeDisplay` may legally\n// anchor to on this surface (never the device zone, never a fabricated\n// `'UTC'`), `trip.phase` lets a composite react to PRE_DEPARTURE/ON_TRIP/\n// POST_TRIP, and `meta.serverTime` is the only trusted \"now\" a share\n// composite may read without going through `useServerTime()` (hard rule\n// #6 — no `Date.now()`/`new Date()` in `src/core`). Hence: two extra return\n// fields, kept structurally apart from the section map they must never\n// pollute.\n\nimport type { KaafilClient } from 'kaafil-js/client';\nimport { useContext, useEffect, useState } from 'react';\nimport { OfflineEngineContext } from '../internal/contexts';\nimport { isDevelopment } from '../internal/isDevelopment';\nimport { useKaafilClient } from './useKaafilClient';\nimport { usePersona } from './usePersona';\n\nexport interface ShareSnapshotOptions {\n readonly travellerRef?: string;\n}\n\n// Derived from the SDK's own return type rather than hand-copied — this\n// stays correct for free if `kaafil-js` grows another `trip` field, instead\n// of silently drifting the way the old `'UTC'` constants did.\ntype ShareSnapshotResponse = Awaited<ReturnType<KaafilClient['share']['snapshot']>>;\n\n/** The trip echo every snapshot response carries — `name`/`startDate`/\n * `endDate` plus the two fields this hook used to throw away:\n * `timezone` (the IANA zone every traveller-facing render must anchor to)\n * and `phase` (server-computed `PRE_DEPARTURE`/`ON_TRIP`/`POST_TRIP`). */\nexport type ShareSnapshotTrip = ShareSnapshotResponse['trip'];\n\nexport interface ShareSnapshotResult {\n readonly status: 'loading' | 'ready' | 'expired' | 'revoked' | 'not-found';\n readonly sections: ReadonlyMap<string, unknown>;\n /** The snapshot's `trip` echo, or `undefined` before any response has\n * landed (mirrors `sections`' own \"empty until ready\" behaviour). NEVER a\n * section key — see this file's header. */\n readonly trip: ShareSnapshotTrip | undefined;\n /** `meta.serverTime` off the most recently landed snapshot response — the\n * only trusted clock a share composite may read (hard rule #6). Kept\n * separate from `useServerTime()`'s own stream (which advances off\n * `OfflineEngine`'s `snapshot.updated` event, not this hook's own fetch)\n * so a composite that only ever calls `useShareSnapshot()` still has a\n * real server stamp to compare against without also wiring the offline\n * engine's event stream. `undefined` before any response has landed. */\n readonly serverTime: string | undefined;\n}\n\nconst NON_SECTION_KEYS = new Set(['trip', 'meta']);\n\nexport function useShareSnapshot(\n token: string,\n options?: ShareSnapshotOptions,\n): ShareSnapshotResult {\n void options; // `travellerRef` narrows which subject-token rows the server\n // itself returns for a `travellerRef`-scoped share link — this hook has no\n // client-side use for it beyond passing the token through; the server does\n // the scoping (`09-registries.md §5`, `families/traveller/01-share-sections.md`, cited).\n\n const client = useKaafilClient();\n const persona = usePersona();\n const engine = useContext(OfflineEngineContext);\n const [sections, setSections] = useState<ReadonlyMap<string, unknown> | undefined>(undefined);\n const [trip, setTrip] = useState<ShareSnapshotTrip | undefined>(undefined);\n const [serverTime, setServerTime] = useState<string | undefined>(undefined);\n const [terminal, setTerminal] = useState<'expired' | 'revoked' | 'not-found' | undefined>(\n undefined,\n );\n\n useEffect(() => {\n if (persona !== 'share') {\n if (isDevelopment()) {\n throw new Error(\n 'useShareSnapshot() was called from a manager/agencyAdmin session — ' +\n 'this hook is `share`-only (08-core-hooks.md §3.1).',\n );\n }\n return;\n }\n\n let cancelled = false;\n async function load(): Promise<void> {\n try {\n const response = await client.share.snapshot({ token });\n if (cancelled) {\n return;\n }\n const map = new Map<string, unknown>();\n for (const [key, value] of Object.entries(response)) {\n if (!NON_SECTION_KEYS.has(key)) {\n map.set(key, value);\n }\n }\n setSections(map);\n setTrip(response.trip);\n setServerTime(response.meta.serverTime);\n } catch {\n // `06-capability-and-personas.md §9`: dark, cross-scope, and\n // genuinely-gone all collapse to the identical shape here — this\n // hook cannot and must not try to distinguish them, so any failure\n // to read the snapshot at all reports the same `'not-found'`.\n if (!cancelled) {\n setTerminal('not-found');\n }\n }\n }\n void load();\n\n if (engine === null) {\n return () => {\n cancelled = true;\n };\n }\n const unsubscribeExpired = engine.events.on('share.expired', () => setTerminal('expired'));\n const unsubscribeRevoked = engine.events.on('share.revoked', () => setTerminal('revoked'));\n return () => {\n cancelled = true;\n unsubscribeExpired();\n unsubscribeRevoked();\n };\n }, [client, persona, token, engine]);\n\n if (terminal !== undefined) {\n return { status: terminal, sections: sections ?? new Map(), trip, serverTime };\n }\n if (sections === undefined) {\n return { status: 'loading', sections: new Map(), trip: undefined, serverTime: undefined };\n }\n return { status: 'ready', sections, trip, serverTime };\n}\n"]}