@burdenoff/microfe-healthybowl 2026.710.19 → 2026.710.21

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 (58) hide show
  1. package/dist/generated/wspace-operations.js +476 -318
  2. package/dist/generated/wspace-operations.js.map +1 -1
  3. package/dist/generated/wspace-types.js.map +1 -1
  4. package/dist/healthybowl/HealthyBowlRoot.js +99 -82
  5. package/dist/healthybowl/HealthyBowlRoot.js.map +1 -1
  6. package/dist/healthybowl/HealthyBowlRoutes.js +103 -79
  7. package/dist/healthybowl/HealthyBowlRoutes.js.map +1 -1
  8. package/dist/healthybowl/hooks/useHealthyBowlData.js +2 -0
  9. package/dist/healthybowl/hooks/useHealthyBowlData.js.map +1 -1
  10. package/dist/healthybowl/hooks/useTracePortal.js +138 -0
  11. package/dist/healthybowl/hooks/useTracePortal.js.map +1 -0
  12. package/dist/healthybowl/index.js +1 -0
  13. package/dist/healthybowl/offline/OfflineStatusPill.js +30 -0
  14. package/dist/healthybowl/offline/OfflineStatusPill.js.map +1 -0
  15. package/dist/healthybowl/offline/OfflineSyncProvider.js +235 -0
  16. package/dist/healthybowl/offline/OfflineSyncProvider.js.map +1 -0
  17. package/dist/healthybowl/offline/geolocation.js +31 -0
  18. package/dist/healthybowl/offline/geolocation.js.map +1 -0
  19. package/dist/healthybowl/offline/graphql.js +89 -0
  20. package/dist/healthybowl/offline/graphql.js.map +1 -0
  21. package/dist/healthybowl/offline/network.js +43 -0
  22. package/dist/healthybowl/offline/network.js.map +1 -0
  23. package/dist/healthybowl/offline/observationMeta.js +107 -0
  24. package/dist/healthybowl/offline/observationMeta.js.map +1 -0
  25. package/dist/healthybowl/offline/store.js +120 -0
  26. package/dist/healthybowl/offline/store.js.map +1 -0
  27. package/dist/healthybowl/offline/syncEngine.js +141 -0
  28. package/dist/healthybowl/offline/syncEngine.js.map +1 -0
  29. package/dist/healthybowl/offline/types.js +15 -0
  30. package/dist/healthybowl/offline/types.js.map +1 -0
  31. package/dist/healthybowl/pages/field-capture/CaptureObservationForm.js +272 -0
  32. package/dist/healthybowl/pages/field-capture/CaptureObservationForm.js.map +1 -0
  33. package/dist/healthybowl/pages/field-capture/ConflictReviewPage.js +200 -0
  34. package/dist/healthybowl/pages/field-capture/ConflictReviewPage.js.map +1 -0
  35. package/dist/healthybowl/pages/field-capture/FieldCapturePage.js +60 -0
  36. package/dist/healthybowl/pages/field-capture/FieldCapturePage.js.map +1 -0
  37. package/dist/healthybowl/pages/field-capture/OfflineSettingsPage.js +217 -0
  38. package/dist/healthybowl/pages/field-capture/OfflineSettingsPage.js.map +1 -0
  39. package/dist/healthybowl/pages/field-capture/PendingSyncPage.js +80 -0
  40. package/dist/healthybowl/pages/field-capture/PendingSyncPage.js.map +1 -0
  41. package/dist/healthybowl/pages/field-capture/SyncHistoryPage.js +130 -0
  42. package/dist/healthybowl/pages/field-capture/SyncHistoryPage.js.map +1 -0
  43. package/dist/healthybowl/pages/field-capture/SyncQueuePanel.js +112 -0
  44. package/dist/healthybowl/pages/field-capture/SyncQueuePanel.js.map +1 -0
  45. package/dist/healthybowl/pages/traceability/PrintLabelDialog.js +296 -0
  46. package/dist/healthybowl/pages/traceability/PrintLabelDialog.js.map +1 -0
  47. package/dist/healthybowl/pages/traceability/QRCodesPage.js +450 -103
  48. package/dist/healthybowl/pages/traceability/QRCodesPage.js.map +1 -1
  49. package/dist/healthybowl/pages/traceability/TracePortalSettingsPage.js +249 -0
  50. package/dist/healthybowl/pages/traceability/TracePortalSettingsPage.js.map +1 -0
  51. package/dist/healthybowl/public/PublicTraceJourney.js +192 -0
  52. package/dist/healthybowl/public/PublicTraceJourney.js.map +1 -0
  53. package/dist/healthybowl/public/PublicTraceNotFound.js +55 -0
  54. package/dist/healthybowl/public/PublicTraceNotFound.js.map +1 -0
  55. package/dist/healthybowl/public/PublicTracePage.js +46 -0
  56. package/dist/healthybowl/public/PublicTracePage.js.map +1 -0
  57. package/dist/index.js +4 -3
  58. package/package.json +1 -1
@@ -0,0 +1,138 @@
1
+ import { useHealthyBowl as e } from "../context/HealthyBowlContext.js";
2
+ import { useGetHealthyBowlTraceBatchLabelPdfLazyQuery as t, useGetHealthyBowlTraceBatchQrPngLazyQuery as n, useGetHealthyBowlTracePortalSettingsQuery as r, usePublishHealthyBowlTraceBatchMutation as i, useSaveHealthyBowlTraceBatchLabelToFilesMutation as a, useUnpublishHealthyBowlTraceBatchMutation as o, useUpdateHealthyBowlTracePortalSettingsMutation as s } from "../../generated/wspace-operations.js";
3
+ import { useCallback as c, useMemo as l, useState as u } from "react";
4
+ //#region src/healthybowl/hooks/useTracePortal.ts
5
+ var d = {
6
+ labelSize: "4x6",
7
+ template: "STANDARD",
8
+ showFarmOrigin: !0,
9
+ showHarvestDate: !0,
10
+ showCertifications: !0,
11
+ showBestBefore: !0,
12
+ qrScale: 3,
13
+ copies: 1
14
+ };
15
+ function f() {
16
+ return typeof window > "u" ? "" : window.location.origin;
17
+ }
18
+ function p(e, t, n) {
19
+ let r = atob(e), i = new Uint8Array(r.length);
20
+ for (let e = 0; e < r.length; e += 1) i[e] = r.charCodeAt(e);
21
+ let a = URL.createObjectURL(new Blob([i], { type: n })), o = document.createElement("a");
22
+ o.href = a, o.download = t, document.body.appendChild(o), o.click(), document.body.removeChild(o), URL.revokeObjectURL(a);
23
+ }
24
+ function m(m) {
25
+ let { workspaceId: h } = e(), g = l(() => ({ workspaceId: h }), [h]), [_, v] = u(null), y = r({
26
+ variables: { context: g },
27
+ skip: !h,
28
+ fetchPolicy: "cache-and-network"
29
+ }), [b] = i(), [x] = o(), [S] = s(), [C] = a(), [w] = n({ fetchPolicy: "no-cache" }), [T] = t({ fetchPolicy: "no-cache" }), E = c(async (e, t) => {
30
+ v(e);
31
+ try {
32
+ let n = await (t ? b : x)({ variables: {
33
+ id: e,
34
+ context: g
35
+ } });
36
+ if (n.error) throw n.error;
37
+ await m?.();
38
+ } finally {
39
+ v(null);
40
+ }
41
+ }, [
42
+ b,
43
+ x,
44
+ g,
45
+ m
46
+ ]), D = c(async (e, t = 512) => {
47
+ let n = (await w({ variables: {
48
+ id: e,
49
+ size: t,
50
+ baseUrl: f(),
51
+ context: g
52
+ } })).data?.getHealthyBowlTraceBatchQrPng;
53
+ return n ? {
54
+ dataUrl: `data:${n.contentType};base64,${n.pngBase64}`,
55
+ publicUrl: n.publicUrl
56
+ } : null;
57
+ }, [w, g]), O = c(async (e, t = 1024) => {
58
+ v(e);
59
+ try {
60
+ let n = await w({ variables: {
61
+ id: e,
62
+ size: t,
63
+ baseUrl: f(),
64
+ context: g
65
+ } });
66
+ if (n.error) throw n.error;
67
+ let r = n.data?.getHealthyBowlTraceBatchQrPng;
68
+ if (!r) throw Error("No QR code was returned for this batch.");
69
+ return p(r.pngBase64, r.fileName, r.contentType), r.publicUrl;
70
+ } finally {
71
+ v(null);
72
+ }
73
+ }, [w, g]), k = c((e, t) => ({
74
+ id: e,
75
+ baseUrl: f(),
76
+ labelSize: t.labelSize,
77
+ template: t.template,
78
+ showFarmOrigin: t.showFarmOrigin,
79
+ showHarvestDate: t.showHarvestDate,
80
+ showCertifications: t.showCertifications,
81
+ showBestBefore: t.showBestBefore,
82
+ qrScale: t.qrScale,
83
+ copies: t.copies,
84
+ context: g
85
+ }), [g]), A = c(async (e, t = d) => {
86
+ v(e);
87
+ try {
88
+ let n = await T({ variables: { input: k(e, t) } });
89
+ if (n.error) throw n.error;
90
+ let r = n.data?.getHealthyBowlTraceBatchLabelPdf;
91
+ if (!r) throw Error("No label was returned for this batch.");
92
+ return p(r.pdfBase64, r.fileName, r.contentType), r.publicUrl;
93
+ } finally {
94
+ v(null);
95
+ }
96
+ }, [T, k]), j = c(async (e, t = d) => {
97
+ v(e);
98
+ try {
99
+ let n = await C({ variables: { input: k(e, t) } });
100
+ if (n.error) throw n.error;
101
+ let r = n.data?.saveHealthyBowlTraceBatchLabelToFiles;
102
+ if (!r) throw Error("The label could not be filed.");
103
+ return r;
104
+ } finally {
105
+ v(null);
106
+ }
107
+ }, [C, k]), M = c(async (e) => {
108
+ let t = await S({ variables: { input: {
109
+ ...e,
110
+ context: g
111
+ } } });
112
+ if (t.error) throw t.error;
113
+ return await y.refetch(), t.data?.updateHealthyBowlTracePortalSettings;
114
+ }, [
115
+ S,
116
+ g,
117
+ y
118
+ ]);
119
+ return {
120
+ settings: y.data?.getHealthyBowlTracePortalSettings ?? null,
121
+ settingsLoading: y.loading,
122
+ settingsError: y.error ?? null,
123
+ busyBatchId: _,
124
+ setPublished: E,
125
+ loadQrDataUrl: D,
126
+ downloadQrPng: O,
127
+ downloadLabelPdf: A,
128
+ saveLabelToFiles: j,
129
+ updateSettings: M
130
+ };
131
+ }
132
+ function h(e) {
133
+ return e ? `${f()}${e}` : null;
134
+ }
135
+ //#endregion
136
+ export { d as DEFAULT_LABEL_OPTIONS, h as publicTraceUrl, m as useTracePortal };
137
+
138
+ //# sourceMappingURL=useTracePortal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useTracePortal.js","names":[],"sources":["../../../src/healthybowl/hooks/useTracePortal.ts"],"sourcesContent":["/**\n * Public farm-to-fork trace portal — owner-side operations (BOFF-2879).\n *\n * Kept out of `useHealthyBowlData` (2.8k lines) because these are on-demand actions rather than\n * page-load reads: a QR PNG and a label PDF are rendered server-side per click, so they must be\n * lazy queries with `no-cache`, not part of the dashboard data bundle.\n *\n * The batch LIST still comes from `useHealthyBowlData().traceBatches`, which now carries the\n * publish fields; the mutations here refetch it so the table reflects a publish immediately.\n */\nimport { useCallback, useMemo, useState } from 'react';\n\nimport {\n useGetHealthyBowlTraceBatchLabelPdfLazyQuery,\n useGetHealthyBowlTraceBatchQrPngLazyQuery,\n useGetHealthyBowlTracePortalSettingsQuery,\n usePublishHealthyBowlTraceBatchMutation,\n useSaveHealthyBowlTraceBatchLabelToFilesMutation,\n useUnpublishHealthyBowlTraceBatchMutation,\n useUpdateHealthyBowlTracePortalSettingsMutation,\n} from '../../generated/wspace-operations';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\nexport type LabelSize = '4x6' | '3x2' | '2x1';\nexport type LabelTemplate = 'STANDARD' | 'COMPACT' | 'RETAIL_SHELF';\n\nexport interface LabelOptions {\n labelSize: LabelSize;\n template: LabelTemplate;\n showFarmOrigin: boolean;\n showHarvestDate: boolean;\n showCertifications: boolean;\n showBestBefore: boolean;\n qrScale: number;\n copies: number;\n}\n\nexport const DEFAULT_LABEL_OPTIONS: LabelOptions = {\n labelSize: '4x6',\n template: 'STANDARD',\n showFarmOrigin: true,\n showHarvestDate: true,\n showCertifications: true,\n showBestBefore: true,\n qrScale: 3,\n copies: 1,\n};\n\nexport interface TracePortalSettingsInput {\n tagline?: string | null;\n showFarmOrigin?: boolean;\n showHarvestDate?: boolean;\n showProcessingDates?: boolean;\n showCertifications?: boolean;\n showSupplyChainSteps?: boolean;\n showBestBeforeDate?: boolean;\n showVerifiedOrganicBanner?: boolean;\n autoPublishOnCreate?: boolean;\n}\n\n/**\n * The origin the QR/label should encode. The service allow-lists this, so a hostile value can\n * only ever degrade to the canonical host — but sending our own origin keeps alpha links on\n * alpha and local links on localhost.\n */\nfunction currentOrigin(): string {\n return typeof window === 'undefined' ? '' : window.location.origin;\n}\n\n/** Trigger a browser download for base64 bytes without ever putting them in the DOM as text. */\nfunction downloadBase64(base64: string, fileName: string, contentType: string): void {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) {\n bytes[i] = binary.charCodeAt(i);\n }\n const url = URL.createObjectURL(new Blob([bytes], { type: contentType }));\n const anchor = document.createElement('a');\n anchor.href = url;\n anchor.download = fileName;\n document.body.appendChild(anchor);\n anchor.click();\n document.body.removeChild(anchor);\n URL.revokeObjectURL(url);\n}\n\nexport function useTracePortal(refetchBatches?: () => Promise<unknown>) {\n const { workspaceId } = useHealthyBowl();\n const context = useMemo(() => ({ workspaceId }), [workspaceId]);\n\n const [busyBatchId, setBusyBatchId] = useState<string | null>(null);\n\n const settingsQuery = useGetHealthyBowlTracePortalSettingsQuery({\n variables: { context },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n });\n\n const [publishMutation] = usePublishHealthyBowlTraceBatchMutation();\n const [unpublishMutation] = useUnpublishHealthyBowlTraceBatchMutation();\n const [updateSettingsMutation] = useUpdateHealthyBowlTracePortalSettingsMutation();\n const [saveLabelMutation] = useSaveHealthyBowlTraceBatchLabelToFilesMutation();\n\n // `no-cache`: the PNG/PDF are large base64 payloads regenerated per click. Caching them would\n // bloat the Apollo store and serve a stale QR after a batch is renamed.\n const [fetchQr] = useGetHealthyBowlTraceBatchQrPngLazyQuery({ fetchPolicy: 'no-cache' });\n const [fetchLabel] = useGetHealthyBowlTraceBatchLabelPdfLazyQuery({ fetchPolicy: 'no-cache' });\n\n const setPublished = useCallback(\n async (batchId: string, published: boolean) => {\n setBusyBatchId(batchId);\n try {\n const mutate = published ? publishMutation : unpublishMutation;\n const res = await mutate({ variables: { id: batchId, context } });\n if (res.error) {\n throw res.error;\n }\n await refetchBatches?.();\n } finally {\n setBusyBatchId(null);\n }\n },\n [publishMutation, unpublishMutation, context, refetchBatches]\n );\n\n /** Fetch the QR as a data URL for on-screen display. Returns null when the batch is a draft. */\n const loadQrDataUrl = useCallback(\n async (batchId: string, size = 512): Promise<{ dataUrl: string; publicUrl: string } | null> => {\n const res = await fetchQr({ variables: { id: batchId, size, baseUrl: currentOrigin(), context } });\n const qr = res.data?.getHealthyBowlTraceBatchQrPng;\n if (!qr) {\n return null;\n }\n return { dataUrl: `data:${qr.contentType};base64,${qr.pngBase64}`, publicUrl: qr.publicUrl };\n },\n [fetchQr, context]\n );\n\n const downloadQrPng = useCallback(\n async (batchId: string, size = 1024) => {\n setBusyBatchId(batchId);\n try {\n const res = await fetchQr({ variables: { id: batchId, size, baseUrl: currentOrigin(), context } });\n if (res.error) {\n throw res.error;\n }\n const qr = res.data?.getHealthyBowlTraceBatchQrPng;\n if (!qr) {\n throw new Error('No QR code was returned for this batch.');\n }\n downloadBase64(qr.pngBase64, qr.fileName, qr.contentType);\n return qr.publicUrl;\n } finally {\n setBusyBatchId(null);\n }\n },\n [fetchQr, context]\n );\n\n const buildLabelInput = useCallback(\n (batchId: string, options: LabelOptions) => ({\n id: batchId,\n baseUrl: currentOrigin(),\n labelSize: options.labelSize,\n template: options.template,\n showFarmOrigin: options.showFarmOrigin,\n showHarvestDate: options.showHarvestDate,\n showCertifications: options.showCertifications,\n showBestBefore: options.showBestBefore,\n qrScale: options.qrScale,\n copies: options.copies,\n context,\n }),\n [context]\n );\n\n const downloadLabelPdf = useCallback(\n async (batchId: string, options: LabelOptions = DEFAULT_LABEL_OPTIONS) => {\n setBusyBatchId(batchId);\n try {\n const res = await fetchLabel({ variables: { input: buildLabelInput(batchId, options) } });\n if (res.error) {\n throw res.error;\n }\n const label = res.data?.getHealthyBowlTraceBatchLabelPdf;\n if (!label) {\n throw new Error('No label was returned for this batch.');\n }\n downloadBase64(label.pdfBase64, label.fileName, label.contentType);\n return label.publicUrl;\n } finally {\n setBusyBatchId(null);\n }\n },\n [fetchLabel, buildLabelInput]\n );\n\n /** Archive the label in the workspace file library (wspace-files-svc owns the blob). */\n const saveLabelToFiles = useCallback(\n async (batchId: string, options: LabelOptions = DEFAULT_LABEL_OPTIONS) => {\n setBusyBatchId(batchId);\n try {\n const res = await saveLabelMutation({ variables: { input: buildLabelInput(batchId, options) } });\n if (res.error) {\n throw res.error;\n }\n const saved = res.data?.saveHealthyBowlTraceBatchLabelToFiles;\n if (!saved) {\n throw new Error('The label could not be filed.');\n }\n return saved;\n } finally {\n setBusyBatchId(null);\n }\n },\n [saveLabelMutation, buildLabelInput]\n );\n\n const updateSettings = useCallback(\n async (input: TracePortalSettingsInput) => {\n const res = await updateSettingsMutation({ variables: { input: { ...input, context } } });\n if (res.error) {\n throw res.error;\n }\n await settingsQuery.refetch();\n return res.data?.updateHealthyBowlTracePortalSettings;\n },\n [updateSettingsMutation, context, settingsQuery]\n );\n\n return {\n settings: settingsQuery.data?.getHealthyBowlTracePortalSettings ?? null,\n settingsLoading: settingsQuery.loading,\n settingsError: settingsQuery.error ?? null,\n busyBatchId,\n setPublished,\n loadQrDataUrl,\n downloadQrPng,\n downloadLabelPdf,\n saveLabelToFiles,\n updateSettings,\n };\n}\n\n/** Absolute public URL for a published batch, built from the shell's own origin. */\nexport function publicTraceUrl(publicPath: string | null | undefined): string | null {\n if (!publicPath) {\n return null;\n }\n return `${currentOrigin()}${publicPath}`;\n}\n"],"mappings":";;;;AAqCA,IAAa,IAAsC;CACjD,WAAW;CACX,UAAU;CACV,gBAAgB;CAChB,iBAAiB;CACjB,oBAAoB;CACpB,gBAAgB;CAChB,SAAS;CACT,QAAQ;CACT;AAmBD,SAAS,IAAwB;AAC/B,QAAO,OAAO,SAAW,MAAc,KAAK,OAAO,SAAS;;AAI9D,SAAS,EAAe,GAAgB,GAAkB,GAA2B;CACnF,IAAM,IAAS,KAAK,EAAO,EACrB,IAAQ,IAAI,WAAW,EAAO,OAAO;AAC3C,MAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KAAK,EACtC,GAAM,KAAK,EAAO,WAAW,EAAE;CAEjC,IAAM,IAAM,IAAI,gBAAgB,IAAI,KAAK,CAAC,EAAM,EAAE,EAAE,MAAM,GAAa,CAAC,CAAC,EACnE,IAAS,SAAS,cAAc,IAAI;AAM1C,CALA,EAAO,OAAO,GACd,EAAO,WAAW,GAClB,SAAS,KAAK,YAAY,EAAO,EACjC,EAAO,OAAO,EACd,SAAS,KAAK,YAAY,EAAO,EACjC,IAAI,gBAAgB,EAAI;;AAG1B,SAAgB,EAAe,GAAyC;CACtE,IAAM,EAAE,mBAAgB,GAAgB,EAClC,IAAU,SAAe,EAAE,gBAAa,GAAG,CAAC,EAAY,CAAC,EAEzD,CAAC,GAAa,KAAkB,EAAwB,KAAK,EAE7D,IAAgB,EAA0C;EAC9D,WAAW,EAAE,YAAS;EACtB,MAAM,CAAC;EACP,aAAa;EACd,CAAC,EAEI,CAAC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L,UAAU,EAAc,MAAM,qCAAqC;EACnE,iBAAiB,EAAc;EAC/B,eAAe,EAAc,SAAS;EACtC;EACA;EACA;EACA;EACA;EACA;EACA;EACD;;AAIH,SAAgB,EAAe,GAAsD;AAInF,QAHK,IAGE,GAAG,GAAe,GAAG,MAFnB"}
@@ -1,5 +1,6 @@
1
1
  import "./context/HealthyBowlContext.js";
2
2
  import "./components/assistant/index.js";
3
3
  import "./HealthyBowlRoot.js";
4
+ import "./public/PublicTracePage.js";
4
5
  import "./store/healthybowlStore.js";
5
6
  import "./hooks/useOpenAssistantHelp.js";
@@ -0,0 +1,30 @@
1
+ import { useOfflineSync as e } from "./OfflineSyncProvider.js";
2
+ import { relativeTime as t } from "./observationMeta.js";
3
+ import { AlertTriangle as n, CheckCircle2 as r, RefreshCw as i, Wifi as a, WifiOff as o } from "lucide-react";
4
+ import { jsx as s, jsxs as c } from "react/jsx-runtime";
5
+ //#region src/healthybowl/offline/OfflineStatusPill.tsx
6
+ var l = ({ inline: l, className: u }) => {
7
+ let { online: d, syncing: f, queuedCount: p, conflictCount: m, lastSyncedAt: h, syncNow: g } = e(), _ = !d, v = p > 0, y = "ok";
8
+ _ ? y = "offline" : (v || m > 0) && (y = "warning");
9
+ let b = y === "offline" || y === "warning" ? "bg-status-warning-bgSubtle text-status-warning-text border-status-warning-border" : "bg-status-success-bgSubtle text-status-success-text border-status-success-border", x = _ ? o : m > 0 ? n : v ? a : r, S;
10
+ return S = _ ? v ? `Offline — ${p} record${p > 1 ? "s" : ""} queued` : "Offline — working locally" : f ? "Online — syncing…" : m > 0 ? `Online — ${m} conflict${m > 1 ? "s" : ""} to review` : v ? `Online — ${p} record${p > 1 ? "s" : ""} queued` : h ? `Online — all synced · last synced ${t(h)}` : "Online — all synced", /* @__PURE__ */ c("div", {
11
+ className: `flex items-center justify-between gap-3 rounded-xl border px-3.5 py-2 ${b} ${l ? "" : "shadow-sm"} ${u ?? ""}`,
12
+ role: "status",
13
+ "aria-live": "polite",
14
+ children: [/* @__PURE__ */ c("span", {
15
+ className: "flex items-center gap-2 text-sm font-medium",
16
+ children: [/* @__PURE__ */ s(x, { className: "h-4 w-4 shrink-0" }), S]
17
+ }), /* @__PURE__ */ c("button", {
18
+ type: "button",
19
+ onClick: () => void g({ manual: !0 }),
20
+ disabled: f || !d && !0,
21
+ title: d ? "Sync now" : "Reconnect to sync",
22
+ className: "inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-bg-surface px-2.5 py-1 text-xs font-semibold text-text-primary shadow-sm ring-1 ring-border-subtle transition hover:bg-bg-sunken disabled:cursor-not-allowed disabled:opacity-50",
23
+ children: [/* @__PURE__ */ s(i, { className: `h-3.5 w-3.5 ${f ? "animate-spin" : ""}` }), "Sync Now"]
24
+ })]
25
+ });
26
+ };
27
+ //#endregion
28
+ export { l as OfflineStatusPill };
29
+
30
+ //# sourceMappingURL=OfflineStatusPill.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OfflineStatusPill.js","names":[],"sources":["../../../src/healthybowl/offline/OfflineStatusPill.tsx"],"sourcesContent":["/**\n * Offline status pill (BOFF-2883).\n *\n * A persistent, honest connectivity indicator: reflects the REAL network state\n * and the REAL queue depth. Shown as a sticky banner at the top of the Field\n * Capture screens (and reusable inline). Includes a manual \"Sync Now\".\n */\nimport type { FC } from 'react';\nimport { Wifi, WifiOff, RefreshCw, CheckCircle2, AlertTriangle } from 'lucide-react';\nimport { useOfflineSync } from './OfflineSyncProvider';\nimport { relativeTime } from './observationMeta';\n\ninterface Props {\n /** Compact inline pill (no full-width banner chrome). */\n inline?: boolean;\n className?: string;\n}\n\nexport const OfflineStatusPill: FC<Props> = ({ inline, className }) => {\n const { online, syncing, queuedCount, conflictCount, lastSyncedAt, syncNow } = useOfflineSync();\n\n const offline = !online;\n const hasQueue = queuedCount > 0;\n\n let tone: 'offline' | 'warning' | 'ok' = 'ok';\n if (offline) tone = 'offline';\n else if (hasQueue || conflictCount > 0) tone = 'warning';\n\n const toneClasses =\n tone === 'offline'\n ? 'bg-status-warning-bgSubtle text-status-warning-text border-status-warning-border'\n : tone === 'warning'\n ? 'bg-status-warning-bgSubtle text-status-warning-text border-status-warning-border'\n : 'bg-status-success-bgSubtle text-status-success-text border-status-success-border';\n\n const Icon = offline ? WifiOff : conflictCount > 0 ? AlertTriangle : hasQueue ? Wifi : CheckCircle2;\n\n let label: string;\n if (offline) {\n label = hasQueue\n ? `Offline — ${queuedCount} record${queuedCount > 1 ? 's' : ''} queued`\n : 'Offline — working locally';\n } else if (syncing) {\n label = 'Online — syncing…';\n } else if (conflictCount > 0) {\n label = `Online — ${conflictCount} conflict${conflictCount > 1 ? 's' : ''} to review`;\n } else if (hasQueue) {\n label = `Online — ${queuedCount} record${queuedCount > 1 ? 's' : ''} queued`;\n } else {\n label = lastSyncedAt ? `Online — all synced · last synced ${relativeTime(lastSyncedAt)}` : 'Online — all synced';\n }\n\n return (\n <div\n className={`flex items-center justify-between gap-3 rounded-xl border px-3.5 py-2 ${toneClasses} ${\n inline ? '' : 'shadow-sm'\n } ${className ?? ''}`}\n role=\"status\"\n aria-live=\"polite\"\n >\n <span className=\"flex items-center gap-2 text-sm font-medium\">\n <Icon className=\"h-4 w-4 shrink-0\" />\n {label}\n </span>\n <button\n type=\"button\"\n onClick={() => void syncNow({ manual: true })}\n disabled={syncing || (!online && true)}\n title={online ? 'Sync now' : 'Reconnect to sync'}\n className=\"inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-bg-surface px-2.5 py-1 text-xs font-semibold text-text-primary shadow-sm ring-1 ring-border-subtle transition hover:bg-bg-sunken disabled:cursor-not-allowed disabled:opacity-50\"\n >\n <RefreshCw className={`h-3.5 w-3.5 ${syncing ? 'animate-spin' : ''}`} />\n Sync Now\n </button>\n </div>\n );\n};\n"],"mappings":";;;;;AAkBA,IAAa,KAAgC,EAAE,WAAQ,mBAAgB;CACrE,IAAM,EAAE,WAAQ,YAAS,gBAAa,kBAAe,iBAAc,eAAY,GAAgB,EAEzF,IAAU,CAAC,GACX,IAAW,IAAc,GAE3B,IAAqC;AACzC,CAAI,IAAS,IAAO,aACX,KAAY,IAAgB,OAAG,IAAO;CAE/C,IAAM,IACJ,MAAS,aAEL,MAAS,YADT,qFAGE,oFAEF,IAAO,IAAU,IAAU,IAAgB,IAAI,IAAgB,IAAW,IAAO,GAEnF;AAeJ,QAdA,AAWE,IAXE,IACM,IACJ,aAAa,EAAY,SAAS,IAAc,IAAI,MAAM,GAAG,WAC7D,8BACK,IACD,sBACC,IAAgB,IACjB,YAAY,EAAc,WAAW,IAAgB,IAAI,MAAM,GAAG,cACjE,IACD,YAAY,EAAY,SAAS,IAAc,IAAI,MAAM,GAAG,WAE5D,IAAe,qCAAqC,EAAa,EAAa,KAAK,uBAI3F,kBAAC,OAAD;EACE,WAAW,yEAAyE,EAAY,GAC9F,IAAS,KAAK,YACf,GAAG,KAAa;EACjB,MAAK;EACL,aAAU;YALZ,CAOE,kBAAC,QAAD;GAAM,WAAU;aAAhB,CACE,kBAAC,GAAD,EAAM,WAAU,oBAAqB,CAAA,EACpC,EACI;MACP,kBAAC,UAAD;GACE,MAAK;GACL,eAAe,KAAK,EAAQ,EAAE,QAAQ,IAAM,CAAC;GAC7C,UAAU,KAAY,CAAC,KAAU;GACjC,OAAO,IAAS,aAAa;GAC7B,WAAU;aALZ,CAOE,kBAAC,GAAD,EAAW,WAAW,eAAe,IAAU,iBAAiB,MAAQ,CAAA,EAAA,WAEjE;KACL"}
@@ -0,0 +1,235 @@
1
+ import { useHealthyBowl as e } from "../context/HealthyBowlContext.js";
2
+ import { useToast as t } from "../hooks/useToast.js";
3
+ import { DEFAULT_SETTINGS as n } from "./types.js";
4
+ import { deleteObservation as r, getAllObservations as i, getHistory as a, getMeta as ee, getPhotosFor as o, loadSettings as te, saveObservation as s, savePhoto as ne, saveSettings as c, setMeta as l } from "./store.js";
5
+ import { getNetworkState as u, isCellular as re, subscribeNetwork as ie } from "./network.js";
6
+ import { fetchFieldCaptureData as d, resolveConflict as f } from "./graphql.js";
7
+ import { drainQueue as p } from "./syncEngine.js";
8
+ import { createContext as m, useCallback as h, useContext as g, useEffect as _, useMemo as v, useRef as y, useState as b } from "react";
9
+ import { jsx as x } from "react/jsx-runtime";
10
+ import { useSaveToFiles as S } from "@burdenoff/fe-libs/storage";
11
+ //#region src/healthybowl/offline/OfflineSyncProvider.tsx
12
+ var C = m(null);
13
+ function w() {
14
+ let e = g(C);
15
+ if (!e) throw Error("useOfflineSync must be used within an OfflineSyncProvider");
16
+ return e;
17
+ }
18
+ var T = "lastSyncedAt";
19
+ function E() {
20
+ return (/* @__PURE__ */ new Date()).toISOString();
21
+ }
22
+ function D(e) {
23
+ return `${e}-${typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.round(Math.random() * 1e9)}`}`;
24
+ }
25
+ var O = ({ children: m }) => {
26
+ let { workspaceId: g } = e(), { save: w } = S(), { toast: O } = t(), [k, A] = b(!1), [j, ae] = b(() => u()), [oe, M] = b(!1), [N, P] = b([]), [F, I] = b([]), [L, R] = b(n), [z, B] = b(null), [V, H] = b(null), [U, W] = b(!1), G = y(L), K = y(j), q = y(!1), J = y(w), Y = y(g);
27
+ G.current = L, K.current = j, J.current = w, Y.current = g;
28
+ let X = h(async () => {
29
+ let [e, t] = await Promise.all([i(), a()]);
30
+ P(e), I(t);
31
+ }, []), Z = h(async () => {
32
+ if (!(!Y.current || !K.current.online)) {
33
+ W(!0);
34
+ try {
35
+ let e = await d({ workspaceId: Y.current });
36
+ e && H(e);
37
+ } finally {
38
+ W(!1);
39
+ }
40
+ }
41
+ }, []);
42
+ _(() => {
43
+ let e = !1;
44
+ return (async () => {
45
+ let [t, n, r, o] = await Promise.all([
46
+ i(),
47
+ a(),
48
+ te(),
49
+ ee(T)
50
+ ]);
51
+ e || (P(t), I(n), R(r), B(o ?? null), A(!0));
52
+ })(), () => {
53
+ e = !0;
54
+ };
55
+ }, []), _(() => {
56
+ Z();
57
+ }, [Z, g]);
58
+ let Q = h(async (e) => {
59
+ if (q.current) return;
60
+ let t = Y.current, n = K.current;
61
+ if (!(!t || !n.online) && !(!e?.manual && !G.current.syncOverMobileData && re(n))) {
62
+ q.current = !0, M(!0);
63
+ try {
64
+ let r = await p({
65
+ workspaceId: t,
66
+ saveToFiles: J.current,
67
+ settings: G.current,
68
+ network: n
69
+ }), i = Date.now();
70
+ B(i), await l(T, i), await X(), Z(), r.attempted > 0 || r.synced > 0 ? r.conflict > 0 ? O({
71
+ title: `${r.conflict} record${r.conflict > 1 ? "s" : ""} need review`,
72
+ description: "A record changed on the server since you captured it.",
73
+ variant: "warning"
74
+ }) : r.synced > 0 || r.duplicate > 0 ? O({
75
+ title: "Synced",
76
+ description: `${r.synced + r.duplicate} record${r.synced + r.duplicate > 1 ? "s" : ""} uploaded${r.photosUploaded ? `, ${r.photosUploaded} photo(s)` : ""}.`,
77
+ variant: "success"
78
+ }) : r.failed > 0 && O({
79
+ title: "Sync incomplete",
80
+ description: "Some records are still queued and will retry automatically.",
81
+ variant: "error"
82
+ }) : e?.manual && O({
83
+ title: "All synced",
84
+ description: "Nothing is waiting to sync.",
85
+ variant: "info"
86
+ });
87
+ } catch {
88
+ e?.manual && O({
89
+ title: "Sync failed",
90
+ description: "Please try again.",
91
+ variant: "error"
92
+ });
93
+ } finally {
94
+ q.current = !1, M(!1);
95
+ }
96
+ }
97
+ }, [
98
+ X,
99
+ Z,
100
+ O
101
+ ]);
102
+ _(() => {
103
+ let e = K.current.online;
104
+ return ie((t) => {
105
+ ae(t);
106
+ let n = !e && t.online;
107
+ e = t.online, n && G.current.autoSyncOnReconnect && Q();
108
+ });
109
+ }, [Q]), _(() => {
110
+ if (!L.autoSyncOnReconnect || L.syncFrequencyMs <= 0) return;
111
+ let e = window.setInterval(() => {
112
+ K.current.online && Q();
113
+ }, L.syncFrequencyMs);
114
+ return () => window.clearInterval(e);
115
+ }, [
116
+ L.autoSyncOnReconnect,
117
+ L.syncFrequencyMs,
118
+ Q
119
+ ]);
120
+ let $ = h(async (e) => {
121
+ let t = D("obs"), n = [];
122
+ for (let r of e.photos ?? []) {
123
+ let e = D("photo");
124
+ await ne({
125
+ id: e,
126
+ clientId: t,
127
+ blob: r,
128
+ filename: r.name || `photo-${e}.jpg`,
129
+ mimeType: r.type || "image/jpeg",
130
+ createdAt: Date.now()
131
+ }), n.push(e);
132
+ }
133
+ let r = {
134
+ clientId: t,
135
+ observationType: e.observationType,
136
+ fieldId: e.fieldId ?? null,
137
+ fieldName: e.fieldName ?? null,
138
+ note: e.note ?? null,
139
+ severity: e.severity ?? null,
140
+ quantity: e.quantity ?? null,
141
+ unit: e.unit ?? null,
142
+ cropName: e.cropName ?? null,
143
+ animalTag: e.animalTag ?? null,
144
+ latitude: e.latitude ?? null,
145
+ longitude: e.longitude ?? null,
146
+ gpsAccuracy: e.gpsAccuracy ?? null,
147
+ photoLocalIds: n,
148
+ photoFileIds: [],
149
+ capturedAt: E(),
150
+ capturedOffline: !K.current.online,
151
+ status: "QUEUED",
152
+ baseVersion: null,
153
+ attempts: 0,
154
+ createdAt: Date.now(),
155
+ updatedAt: Date.now(),
156
+ workspaceId: Y.current
157
+ };
158
+ return await s(r), await X(), K.current.online && G.current.autoSyncOnReconnect && Q(), r;
159
+ }, [X, Q]), se = h(async (e, t, n) => {
160
+ let r = N.find((t) => t.clientId === e), i = r?.serverVersion?.version ?? r?.baseVersion ?? 0;
161
+ try {
162
+ let a = await f({ workspaceId: Y.current }, {
163
+ clientId: e,
164
+ resolution: t,
165
+ baseVersion: i,
166
+ fieldId: n?.fieldId,
167
+ note: n?.note,
168
+ severity: n?.severity,
169
+ quantity: n?.quantity,
170
+ unit: n?.unit,
171
+ cropName: n?.cropName,
172
+ animalTag: n?.animalTag,
173
+ latitude: n?.latitude,
174
+ longitude: n?.longitude,
175
+ photoFileIds: n?.photoFileIds
176
+ });
177
+ r && (r.status = "SYNCED", r.serverVersion = null, r.baseVersion = a.version, r.serverId = a.id, r.syncedAt = E(), r.message = null, r.note = a.note ?? r.note, r.severity = a.severity ?? r.severity, r.updatedAt = Date.now(), await s(r)), await X(), O({
178
+ title: "Conflict resolved",
179
+ variant: "success"
180
+ });
181
+ } catch (e) {
182
+ throw O({
183
+ title: "Resolve failed",
184
+ description: e instanceof Error ? e.message : "Could not resolve the conflict",
185
+ variant: "error"
186
+ }), e;
187
+ }
188
+ }, [
189
+ N,
190
+ X,
191
+ O
192
+ ]), ce = h(async (e) => {
193
+ await r(e), await X();
194
+ }, [X]), le = h(async (e) => {
195
+ R((t) => {
196
+ let n = {
197
+ ...t,
198
+ ...e
199
+ };
200
+ return c(n), n;
201
+ });
202
+ }, []), ue = h((e) => o(e), []), de = v(() => N.filter((e) => e.status === "QUEUED" || e.status === "UPLOADING" || e.status === "FAILED").length, [N]), fe = v(() => N.filter((e) => e.status === "CONFLICT").length, [N]), pe = {
203
+ ready: k,
204
+ online: j.online,
205
+ connectionType: j.connectionType,
206
+ syncing: oe,
207
+ lastSyncedAt: z,
208
+ observations: N,
209
+ queuedCount: de,
210
+ conflictCount: fe,
211
+ history: F,
212
+ settings: L,
213
+ fields: V?.fields ?? [],
214
+ serverRecent: V?.recentObservations ?? [],
215
+ stats: V?.stats ?? null,
216
+ loadingCaptureData: U,
217
+ capture: $,
218
+ syncNow: Q,
219
+ resolve: se,
220
+ remove: ce,
221
+ updateSettings: le,
222
+ refresh: async () => {
223
+ await X(), await Z();
224
+ },
225
+ loadLocalPhotos: ue
226
+ };
227
+ return /* @__PURE__ */ x(C.Provider, {
228
+ value: pe,
229
+ children: m
230
+ });
231
+ };
232
+ //#endregion
233
+ export { O as OfflineSyncProvider, w as useOfflineSync };
234
+
235
+ //# sourceMappingURL=OfflineSyncProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OfflineSyncProvider.js","names":[],"sources":["../../../src/healthybowl/offline/OfflineSyncProvider.tsx"],"sourcesContent":["/**\n * OfflineSyncProvider (BOFF-2883).\n *\n * The single owner of the offline capture + sync lifecycle for the HealthyBowl\n * MFE. Holds the outbox + history + settings, watches connectivity, auto-drains\n * the queue on reconnect (and on an interval), and exposes capture / sync /\n * resolve / delete actions to the Field Capture screens.\n */\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type FC,\n type PropsWithChildren,\n} from 'react';\nimport { useSaveToFiles } from '@burdenoff/fe-libs/storage';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\nimport { useToast } from '../hooks/useToast';\nimport type {\n LocalObservation,\n LocalPhoto,\n ObservationType,\n OfflineSettings,\n SyncHistoryEntry,\n ServerObservation,\n} from './types';\nimport { DEFAULT_SETTINGS } from './types';\nimport {\n getAllObservations,\n saveObservation,\n deleteObservation as storeDeleteObservation,\n savePhoto,\n getPhotosFor,\n getHistory,\n loadSettings,\n saveSettings,\n getMeta,\n setMeta,\n} from './store';\nimport { subscribeNetwork, getNetworkState, isCellular } from './network';\nimport { drainQueue, type SaveToFiles } from './syncEngine';\nimport { resolveConflict as resolveConflictGql, fetchFieldCaptureData, type FieldCaptureData } from './graphql';\nimport type { NetworkState } from './types';\n\nexport interface CaptureInput {\n observationType: ObservationType;\n fieldId?: string | null;\n fieldName?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n gpsAccuracy?: number | null;\n /** Freshly-captured photo files (blobs stored locally, uploaded on sync). */\n photos?: File[];\n}\n\nexport interface ResolveValues {\n fieldId?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n photoFileIds?: string[];\n}\n\ninterface OfflineSyncContextValue {\n ready: boolean;\n online: boolean;\n connectionType: string;\n syncing: boolean;\n lastSyncedAt: number | null;\n observations: LocalObservation[];\n queuedCount: number;\n conflictCount: number;\n history: SyncHistoryEntry[];\n settings: OfflineSettings;\n fields: Array<{ id: string; name: string; cropNames: string[] }>;\n serverRecent: ServerObservation[];\n stats: FieldCaptureData['stats'] | null;\n loadingCaptureData: boolean;\n capture: (input: CaptureInput) => Promise<LocalObservation>;\n syncNow: (opts?: { manual?: boolean }) => Promise<void>;\n resolve: (\n clientId: string,\n resolution: 'KEEP_MINE' | 'KEEP_SERVER' | 'MERGE',\n values?: ResolveValues\n ) => Promise<void>;\n remove: (clientId: string) => Promise<void>;\n updateSettings: (patch: Partial<OfflineSettings>) => Promise<void>;\n refresh: () => Promise<void>;\n loadLocalPhotos: (clientId: string) => Promise<LocalPhoto[]>;\n}\n\nconst OfflineSyncContext = createContext<OfflineSyncContextValue | null>(null);\n\nexport function useOfflineSync(): OfflineSyncContextValue {\n const ctx = useContext(OfflineSyncContext);\n if (!ctx) throw new Error('useOfflineSync must be used within an OfflineSyncProvider');\n return ctx;\n}\n\nconst LAST_SYNCED_META = 'lastSyncedAt';\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\nfunction uid(prefix: string): string {\n const rand =\n typeof crypto !== 'undefined' && crypto.randomUUID\n ? crypto.randomUUID()\n : `${Date.now()}-${Math.round(Math.random() * 1e9)}`;\n return `${prefix}-${rand}`;\n}\n\nexport const OfflineSyncProvider: FC<PropsWithChildren> = ({ children }) => {\n const { workspaceId } = useHealthyBowl();\n const { save: saveToFiles } = useSaveToFiles();\n const { toast } = useToast();\n\n const [ready, setReady] = useState(false);\n const [network, setNetwork] = useState<NetworkState>(() => getNetworkState());\n const [syncing, setSyncing] = useState(false);\n const [observations, setObservations] = useState<LocalObservation[]>([]);\n const [history, setHistory] = useState<SyncHistoryEntry[]>([]);\n const [settings, setSettings] = useState<OfflineSettings>(DEFAULT_SETTINGS);\n const [lastSyncedAt, setLastSyncedAt] = useState<number | null>(null);\n const [captureData, setCaptureData] = useState<FieldCaptureData | null>(null);\n const [loadingCaptureData, setLoadingCaptureData] = useState(false);\n\n // Refs mirror the latest values for use inside listeners / intervals (avoids stale closures).\n const settingsRef = useRef(settings);\n const networkRef = useRef(network);\n const syncingRef = useRef(false);\n const saveToFilesRef = useRef<SaveToFiles>(saveToFiles as unknown as SaveToFiles);\n const workspaceRef = useRef(workspaceId);\n settingsRef.current = settings;\n networkRef.current = network;\n saveToFilesRef.current = saveToFiles as unknown as SaveToFiles;\n workspaceRef.current = workspaceId;\n\n const reload = useCallback(async () => {\n const [obs, hist] = await Promise.all([getAllObservations(), getHistory()]);\n setObservations(obs);\n setHistory(hist);\n }, []);\n\n const refreshCaptureData = useCallback(async () => {\n if (!workspaceRef.current || !networkRef.current.online) return;\n setLoadingCaptureData(true);\n try {\n const data = await fetchFieldCaptureData({ workspaceId: workspaceRef.current });\n if (data) setCaptureData(data);\n } finally {\n setLoadingCaptureData(false);\n }\n }, []);\n\n // Initial load.\n useEffect(() => {\n let cancelled = false;\n void (async () => {\n const [obs, hist, s, last] = await Promise.all([\n getAllObservations(),\n getHistory(),\n loadSettings(),\n getMeta<number>(LAST_SYNCED_META),\n ]);\n if (cancelled) return;\n setObservations(obs);\n setHistory(hist);\n setSettings(s);\n setLastSyncedAt(last ?? null);\n setReady(true);\n })();\n return () => {\n cancelled = true;\n };\n }, []);\n\n useEffect(() => {\n void refreshCaptureData();\n }, [refreshCaptureData, workspaceId]);\n\n const syncNow = useCallback(\n async (opts?: { manual?: boolean }) => {\n if (syncingRef.current) return;\n const ws = workspaceRef.current;\n const net = networkRef.current;\n if (!ws || !net.online) return;\n // Respect \"sync over mobile data\" — a manual tap always syncs.\n if (!opts?.manual && !settingsRef.current.syncOverMobileData && isCellular(net)) return;\n\n syncingRef.current = true;\n setSyncing(true);\n try {\n const summary = await drainQueue({\n workspaceId: ws,\n saveToFiles: saveToFilesRef.current,\n settings: settingsRef.current,\n network: net,\n });\n const ts = Date.now();\n setLastSyncedAt(ts);\n await setMeta(LAST_SYNCED_META, ts);\n await reload();\n void refreshCaptureData();\n if (summary.attempted > 0 || summary.synced > 0) {\n if (summary.conflict > 0) {\n toast({\n title: `${summary.conflict} record${summary.conflict > 1 ? 's' : ''} need review`,\n description: 'A record changed on the server since you captured it.',\n variant: 'warning',\n });\n } else if (summary.synced > 0 || summary.duplicate > 0) {\n toast({\n title: 'Synced',\n description: `${summary.synced + summary.duplicate} record${\n summary.synced + summary.duplicate > 1 ? 's' : ''\n } uploaded${summary.photosUploaded ? `, ${summary.photosUploaded} photo(s)` : ''}.`,\n variant: 'success',\n });\n } else if (summary.failed > 0) {\n toast({\n title: 'Sync incomplete',\n description: 'Some records are still queued and will retry automatically.',\n variant: 'error',\n });\n }\n } else if (opts?.manual) {\n toast({ title: 'All synced', description: 'Nothing is waiting to sync.', variant: 'info' });\n }\n } catch {\n if (opts?.manual) toast({ title: 'Sync failed', description: 'Please try again.', variant: 'error' });\n } finally {\n syncingRef.current = false;\n setSyncing(false);\n }\n },\n [reload, refreshCaptureData, toast]\n );\n\n // Connectivity: subscribe and auto-sync on the offline→online transition.\n useEffect(() => {\n let prevOnline = networkRef.current.online;\n const unsub = subscribeNetwork((state) => {\n setNetwork(state);\n const cameOnline = !prevOnline && state.online;\n prevOnline = state.online;\n if (cameOnline && settingsRef.current.autoSyncOnReconnect) {\n void syncNow();\n }\n });\n return unsub;\n }, [syncNow]);\n\n // Periodic auto-sync while online (configurable frequency; 0 disables).\n useEffect(() => {\n if (!settings.autoSyncOnReconnect || settings.syncFrequencyMs <= 0) return;\n const id = window.setInterval(() => {\n if (networkRef.current.online) void syncNow();\n }, settings.syncFrequencyMs);\n return () => window.clearInterval(id);\n }, [settings.autoSyncOnReconnect, settings.syncFrequencyMs, syncNow]);\n\n const capture = useCallback(\n async (input: CaptureInput): Promise<LocalObservation> => {\n const clientId = uid('obs');\n const photoLocalIds: string[] = [];\n for (const file of input.photos ?? []) {\n const pid = uid('photo');\n await savePhoto({\n id: pid,\n clientId,\n blob: file,\n filename: file.name || `photo-${pid}.jpg`,\n mimeType: file.type || 'image/jpeg',\n createdAt: Date.now(),\n });\n photoLocalIds.push(pid);\n }\n const obs: LocalObservation = {\n clientId,\n observationType: input.observationType,\n fieldId: input.fieldId ?? null,\n fieldName: input.fieldName ?? null,\n note: input.note ?? null,\n severity: input.severity ?? null,\n quantity: input.quantity ?? null,\n unit: input.unit ?? null,\n cropName: input.cropName ?? null,\n animalTag: input.animalTag ?? null,\n latitude: input.latitude ?? null,\n longitude: input.longitude ?? null,\n gpsAccuracy: input.gpsAccuracy ?? null,\n photoLocalIds,\n photoFileIds: [],\n capturedAt: nowIso(),\n capturedOffline: !networkRef.current.online,\n status: 'QUEUED',\n baseVersion: null,\n attempts: 0,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n workspaceId: workspaceRef.current,\n };\n await saveObservation(obs);\n await reload();\n // Kick a sync immediately if we're online and auto-sync is on.\n if (networkRef.current.online && settingsRef.current.autoSyncOnReconnect) void syncNow();\n return obs;\n },\n [reload, syncNow]\n );\n\n const resolve = useCallback(\n async (clientId: string, resolution: 'KEEP_MINE' | 'KEEP_SERVER' | 'MERGE', values?: ResolveValues) => {\n const obs = observations.find((o) => o.clientId === clientId);\n const baseVersion = obs?.serverVersion?.version ?? obs?.baseVersion ?? 0;\n try {\n const server = await resolveConflictGql(\n { workspaceId: workspaceRef.current },\n {\n clientId,\n resolution,\n baseVersion,\n fieldId: values?.fieldId,\n note: values?.note,\n severity: values?.severity,\n quantity: values?.quantity,\n unit: values?.unit,\n cropName: values?.cropName,\n animalTag: values?.animalTag,\n latitude: values?.latitude,\n longitude: values?.longitude,\n photoFileIds: values?.photoFileIds,\n }\n );\n if (obs) {\n obs.status = 'SYNCED';\n obs.serverVersion = null;\n obs.baseVersion = server.version;\n obs.serverId = server.id;\n obs.syncedAt = nowIso();\n obs.message = null;\n // Reflect the resolved values locally so the queue shows the merged truth.\n if (resolution !== 'KEEP_SERVER') {\n obs.note = server.note ?? obs.note;\n obs.severity = server.severity ?? obs.severity;\n } else {\n obs.note = server.note ?? obs.note;\n obs.severity = server.severity ?? obs.severity;\n }\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n }\n await reload();\n toast({ title: 'Conflict resolved', variant: 'success' });\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Could not resolve the conflict';\n toast({ title: 'Resolve failed', description: message, variant: 'error' });\n throw err;\n }\n },\n [observations, reload, toast]\n );\n\n const remove = useCallback(\n async (clientId: string) => {\n await storeDeleteObservation(clientId);\n await reload();\n },\n [reload]\n );\n\n const updateSettings = useCallback(async (patch: Partial<OfflineSettings>) => {\n setSettings((prev) => {\n const next = { ...prev, ...patch };\n void saveSettings(next);\n return next;\n });\n }, []);\n\n const loadLocalPhotos = useCallback((clientId: string) => getPhotosFor(clientId), []);\n\n const queuedCount = useMemo(\n () => observations.filter((o) => o.status === 'QUEUED' || o.status === 'UPLOADING' || o.status === 'FAILED').length,\n [observations]\n );\n const conflictCount = useMemo(() => observations.filter((o) => o.status === 'CONFLICT').length, [observations]);\n\n const value: OfflineSyncContextValue = {\n ready,\n online: network.online,\n connectionType: network.connectionType,\n syncing,\n lastSyncedAt,\n observations,\n queuedCount,\n conflictCount,\n history,\n settings,\n fields: captureData?.fields ?? [],\n serverRecent: captureData?.recentObservations ?? [],\n stats: captureData?.stats ?? null,\n loadingCaptureData,\n capture,\n syncNow,\n resolve,\n remove,\n updateSettings,\n refresh: async () => {\n await reload();\n await refreshCaptureData();\n },\n loadLocalPhotos,\n };\n\n return <OfflineSyncContext.Provider value={value}>{children}</OfflineSyncContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;AA0GA,IAAM,IAAqB,EAA8C,KAAK;AAE9E,SAAgB,IAA0C;CACxD,IAAM,IAAM,EAAW,EAAmB;AAC1C,KAAI,CAAC,EAAK,OAAU,MAAM,4DAA4D;AACtF,QAAO;;AAGT,IAAM,IAAmB;AAEzB,SAAS,IAAiB;AACxB,yBAAO,IAAI,MAAM,EAAC,aAAa;;AAEjC,SAAS,EAAI,GAAwB;AAKnC,QAAO,GAAG,EAAO,GAHf,OAAO,SAAW,OAAe,OAAO,aACpC,OAAO,YAAY,GACn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M,GAAQ,EACd,EAAM;IAAE,OAAO;IAAqB,SAAS;IAAW,CAAC;WAClD,GAAK;AAGZ,SADA,EAAM;IAAE,OAAO;IAAkB,aADjB,aAAe,QAAQ,EAAI,UAAU;IACE,SAAS;IAAS,CAAC,EACpE;;IAGV;EAAC;EAAc;EAAQ;EAAM,CAC9B,EAEK,KAAS,EACb,OAAO,MAAqB;AAE1B,EADA,MAAM,EAAuB,EAAS,EACtC,MAAM,GAAQ;IAEhB,CAAC,EAAO,CACT,EAEK,KAAiB,EAAY,OAAO,MAAoC;AAC5E,KAAa,MAAS;GACpB,IAAM,IAAO;IAAE,GAAG;IAAM,GAAG;IAAO;AAElC,UADK,EAAa,EAAK,EAChB;IACP;IACD,EAAE,CAAC,EAEA,KAAkB,GAAa,MAAqB,EAAa,EAAS,EAAE,EAAE,CAAC,EAE/E,KAAc,QACZ,EAAa,QAAQ,MAAM,EAAE,WAAW,YAAY,EAAE,WAAW,eAAe,EAAE,WAAW,SAAS,CAAC,QAC7G,CAAC,EAAa,CACf,EACK,KAAgB,QAAc,EAAa,QAAQ,MAAM,EAAE,WAAW,WAAW,CAAC,QAAQ,CAAC,EAAa,CAAC,EAEzG,KAAiC;EACrC;EACA,QAAQ,EAAQ;EAChB,gBAAgB,EAAQ;EACxB;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ,GAAa,UAAU,EAAE;EACjC,cAAc,GAAa,sBAAsB,EAAE;EACnD,OAAO,GAAa,SAAS;EAC7B;EACA;EACA;EACA;EACA;EACA;EACA,SAAS,YAAY;AAEnB,GADA,MAAM,GAAQ,EACd,MAAM,GAAoB;;EAE5B;EACD;AAED,QAAO,kBAAC,EAAmB,UAApB;EAAoC;EAAQ;EAAuC,CAAA"}
@@ -0,0 +1,31 @@
1
+ //#region src/healthybowl/offline/geolocation.ts
2
+ function e(e) {
3
+ let t = e?.highAccuracy ?? !1, n = e?.timeoutMs ?? 1e4;
4
+ return new Promise((e) => {
5
+ try {
6
+ if (typeof navigator > "u" || !navigator.geolocation) {
7
+ e(null);
8
+ return;
9
+ }
10
+ navigator.geolocation.getCurrentPosition((t) => e({
11
+ latitude: t.coords.latitude,
12
+ longitude: t.coords.longitude,
13
+ accuracy: t.coords.accuracy
14
+ }), () => e(null), {
15
+ enableHighAccuracy: t,
16
+ timeout: n,
17
+ maximumAge: 6e4
18
+ });
19
+ } catch {
20
+ e(null);
21
+ }
22
+ });
23
+ }
24
+ function t(e, t) {
25
+ let n = e >= 0 ? "N" : "S", r = t >= 0 ? "E" : "W";
26
+ return `${Math.abs(e).toFixed(4)}° ${n}, ${Math.abs(t).toFixed(4)}° ${r}`;
27
+ }
28
+ //#endregion
29
+ export { e as captureGps, t as formatGps };
30
+
31
+ //# sourceMappingURL=geolocation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geolocation.js","names":[],"sources":["../../../src/healthybowl/offline/geolocation.ts"],"sourcesContent":["/**\n * GPS capture (BOFF-2883).\n *\n * Auto-stamps a captured observation with the device's coordinates — works fully\n * offline (the GNSS fix does not need connectivity). Uses the standard\n * `navigator.geolocation` API, which is available both in the browser and inside\n * the Capacitor WebView (with the OS location permission granted).\n */\n\nexport interface GpsFix {\n latitude: number;\n longitude: number;\n accuracy: number;\n}\n\n/**\n * Get the current position. Resolves null (never throws) on denial / timeout /\n * unsupported so capture always proceeds — GPS is a best-effort stamp, not a gate.\n */\nexport function captureGps(options?: { highAccuracy?: boolean; timeoutMs?: number }): Promise<GpsFix | null> {\n const highAccuracy = options?.highAccuracy ?? false;\n const timeout = options?.timeoutMs ?? 10000;\n return new Promise((resolve) => {\n try {\n if (typeof navigator === 'undefined' || !navigator.geolocation) {\n resolve(null);\n return;\n }\n navigator.geolocation.getCurrentPosition(\n (pos) =>\n resolve({\n latitude: pos.coords.latitude,\n longitude: pos.coords.longitude,\n accuracy: pos.coords.accuracy,\n }),\n () => resolve(null),\n { enableHighAccuracy: highAccuracy, timeout, maximumAge: 60000 }\n );\n } catch {\n resolve(null);\n }\n });\n}\n\n/** Format a fix for display, e.g. \"11.0168° N, 76.9558° E\". */\nexport function formatGps(lat: number, lng: number): string {\n const ns = lat >= 0 ? 'N' : 'S';\n const ew = lng >= 0 ? 'E' : 'W';\n return `${Math.abs(lat).toFixed(4)}° ${ns}, ${Math.abs(lng).toFixed(4)}° ${ew}`;\n}\n"],"mappings":";AAmBA,SAAgB,EAAW,GAAkF;CAC3G,IAAM,IAAe,GAAS,gBAAgB,IACxC,IAAU,GAAS,aAAa;AACtC,QAAO,IAAI,SAAS,MAAY;AAC9B,MAAI;AACF,OAAI,OAAO,YAAc,OAAe,CAAC,UAAU,aAAa;AAC9D,MAAQ,KAAK;AACb;;AAEF,aAAU,YAAY,oBACnB,MACC,EAAQ;IACN,UAAU,EAAI,OAAO;IACrB,WAAW,EAAI,OAAO;IACtB,UAAU,EAAI,OAAO;IACtB,CAAC,QACE,EAAQ,KAAK,EACnB;IAAE,oBAAoB;IAAc;IAAS,YAAY;IAAO,CACjE;UACK;AACN,KAAQ,KAAK;;GAEf;;AAIJ,SAAgB,EAAU,GAAa,GAAqB;CAC1D,IAAM,IAAK,KAAO,IAAI,MAAM,KACtB,IAAK,KAAO,IAAI,MAAM;AAC5B,QAAO,GAAG,KAAK,IAAI,EAAI,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAG,IAAI,KAAK,IAAI,EAAI,CAAC,QAAQ,EAAE,CAAC,IAAI"}
@@ -0,0 +1,89 @@
1
+ import { graphqlFetch as e } from "@burdenoff/fe-libs/shared/graphql";
2
+ //#region src/healthybowl/offline/graphql.ts
3
+ var t = class extends Error {
4
+ code;
5
+ constructor(e, t) {
6
+ super(e), this.name = "SyncGraphQLError", this.code = t;
7
+ }
8
+ };
9
+ function n(e) {
10
+ if (!e || e.length === 0) return null;
11
+ let n = e[0];
12
+ return new t(n.extensions?.userMessage ?? n.message, n.extensions?.code ?? "INTERNAL_SERVER_ERROR");
13
+ }
14
+ var r = "\n id clientId fieldId fieldName observationType title note severity quantity unit\n cropName animalTag latitude longitude gpsAccuracy photoFileIds capturedAt\n capturedOffline syncedAt version createdBy createdAt updatedAt\n", i = `
15
+ mutation SyncFieldObservations($input: SyncFieldObservationsInput!) {
16
+ syncHealthyBowlFieldObservations(input: $input) {
17
+ syncedCount duplicateCount conflictCount failedCount
18
+ items {
19
+ clientId outcome message
20
+ observation { ${r} }
21
+ serverVersion { ${r} }
22
+ }
23
+ }
24
+ }
25
+ `;
26
+ async function a(r, a) {
27
+ let o = await e({
28
+ gateway: "workspace",
29
+ query: i,
30
+ variables: { input: {
31
+ context: r,
32
+ observations: a
33
+ } },
34
+ workspaceToken: !0,
35
+ workspaceId: r.workspaceId,
36
+ suppressGlobalErrorEvent: !0
37
+ }), s = n(o.errors);
38
+ if (s) throw s;
39
+ let c = o.data?.syncHealthyBowlFieldObservations;
40
+ if (!c) throw new t("Empty sync response", "INTERNAL_SERVER_ERROR");
41
+ return c;
42
+ }
43
+ var o = `
44
+ mutation ResolveFieldObservationConflict($input: ResolveFieldObservationConflictInput!) {
45
+ resolveHealthyBowlFieldObservationConflict(input: $input) { ${r} }
46
+ }
47
+ `;
48
+ async function s(r, i) {
49
+ let a = await e({
50
+ gateway: "workspace",
51
+ query: o,
52
+ variables: { input: {
53
+ ...i,
54
+ context: r
55
+ } },
56
+ workspaceToken: !0,
57
+ workspaceId: r.workspaceId,
58
+ suppressGlobalErrorEvent: !0
59
+ }), s = n(a.errors);
60
+ if (s) throw s;
61
+ let c = a.data?.resolveHealthyBowlFieldObservationConflict;
62
+ if (!c) throw new t("Empty resolve response", "INTERNAL_SERVER_ERROR");
63
+ return c;
64
+ }
65
+ var c = `
66
+ query FieldCaptureData($context: ContextInput!) {
67
+ getHealthyBowlFieldCaptureData(context: $context) {
68
+ fields { id name cropNames }
69
+ recentObservations { ${r} }
70
+ stats { totalObservations observationsToday byType { observationType count } }
71
+ updatedAt
72
+ }
73
+ }
74
+ `;
75
+ async function l(t) {
76
+ let n = await e({
77
+ gateway: "workspace",
78
+ query: c,
79
+ variables: { context: t },
80
+ workspaceToken: !0,
81
+ workspaceId: t.workspaceId,
82
+ suppressGlobalErrorEvent: !0
83
+ });
84
+ return n.errors && n.errors.length ? null : n.data?.getHealthyBowlFieldCaptureData ?? null;
85
+ }
86
+ //#endregion
87
+ export { l as fetchFieldCaptureData, s as resolveConflict, a as syncObservations };
88
+
89
+ //# sourceMappingURL=graphql.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graphql.js","names":[],"sources":["../../../src/healthybowl/offline/graphql.ts"],"sourcesContent":["/**\n * GraphQL operations for the offline sync engine (BOFF-2883).\n *\n * These replay through fe-libs `graphqlFetch` (gateway: 'workspace'), which\n * re-derives auth (bearer + workspace dual-token + context headers) from\n * profile storage on every call — so the outbox never freezes a rotating token.\n * The workspaces public gateway enforces the `@rbac` directives.\n */\nimport { graphqlFetch } from '@burdenoff/fe-libs/shared/graphql';\nimport type { ServerObservation } from './types';\n\ninterface GqlError {\n message: string;\n extensions?: { code?: string; userMessage?: string };\n}\n\n/** Thrown when the gateway returns GraphQL errors (vs a transport failure). */\nexport class SyncGraphQLError extends Error {\n code: string;\n constructor(message: string, code: string) {\n super(message);\n this.name = 'SyncGraphQLError';\n this.code = code;\n }\n}\n\nfunction firstError(errors: GqlError[] | undefined): SyncGraphQLError | null {\n if (!errors || errors.length === 0) return null;\n const e = errors[0];\n return new SyncGraphQLError(e.extensions?.userMessage ?? e.message, e.extensions?.code ?? 'INTERNAL_SERVER_ERROR');\n}\n\ntype Ctx = { workspaceId: string };\n\nconst OBSERVATION_FIELDS = `\n id clientId fieldId fieldName observationType title note severity quantity unit\n cropName animalTag latitude longitude gpsAccuracy photoFileIds capturedAt\n capturedOffline syncedAt version createdBy createdAt updatedAt\n`;\n\nexport interface SyncInputItem {\n clientId: string;\n observationType: string;\n fieldId?: string | null;\n fieldName?: string | null;\n title?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n gpsAccuracy?: number | null;\n photoFileIds?: string[];\n capturedAt: string;\n capturedOffline?: boolean;\n baseVersion?: number | null;\n}\n\nexport interface SyncResultItem {\n clientId: string;\n outcome: 'SYNCED' | 'DUPLICATE' | 'CONFLICT' | 'FAILED';\n observation: ServerObservation | null;\n serverVersion: ServerObservation | null;\n message: string | null;\n}\n\nexport interface SyncResult {\n items: SyncResultItem[];\n syncedCount: number;\n duplicateCount: number;\n conflictCount: number;\n failedCount: number;\n}\n\nconst SYNC_MUTATION = `\n mutation SyncFieldObservations($input: SyncFieldObservationsInput!) {\n syncHealthyBowlFieldObservations(input: $input) {\n syncedCount duplicateCount conflictCount failedCount\n items {\n clientId outcome message\n observation { ${OBSERVATION_FIELDS} }\n serverVersion { ${OBSERVATION_FIELDS} }\n }\n }\n }\n`;\n\nexport async function syncObservations(ctx: Ctx, observations: SyncInputItem[]): Promise<SyncResult> {\n const res = await graphqlFetch<{ syncHealthyBowlFieldObservations: SyncResult }>({\n gateway: 'workspace',\n query: SYNC_MUTATION,\n variables: { input: { context: ctx, observations } },\n // The workspaces gateway enforces @rbac(scopeType:\"wspace\"); attach the workspace\n // dual-token + x-workspace-id so the call is authorized for this workspace.\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n const err = firstError(res.errors as GqlError[] | undefined);\n if (err) throw err;\n const data = res.data?.syncHealthyBowlFieldObservations;\n if (!data) throw new SyncGraphQLError('Empty sync response', 'INTERNAL_SERVER_ERROR');\n return data;\n}\n\nexport interface ResolveInput {\n clientId: string;\n resolution: 'KEEP_MINE' | 'KEEP_SERVER' | 'MERGE';\n baseVersion: number;\n fieldId?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n photoFileIds?: string[];\n}\n\nconst RESOLVE_MUTATION = `\n mutation ResolveFieldObservationConflict($input: ResolveFieldObservationConflictInput!) {\n resolveHealthyBowlFieldObservationConflict(input: $input) { ${OBSERVATION_FIELDS} }\n }\n`;\n\nexport async function resolveConflict(ctx: Ctx, input: ResolveInput): Promise<ServerObservation> {\n const res = await graphqlFetch<{ resolveHealthyBowlFieldObservationConflict: ServerObservation }>({\n gateway: 'workspace',\n query: RESOLVE_MUTATION,\n variables: { input: { ...input, context: ctx } },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n const err = firstError(res.errors as GqlError[] | undefined);\n if (err) throw err;\n const data = res.data?.resolveHealthyBowlFieldObservationConflict;\n if (!data) throw new SyncGraphQLError('Empty resolve response', 'INTERNAL_SERVER_ERROR');\n return data;\n}\n\nexport interface FieldCaptureData {\n fields: Array<{ id: string; name: string; cropNames: string[] }>;\n recentObservations: ServerObservation[];\n stats: {\n totalObservations: number;\n observationsToday: number;\n byType: Array<{ observationType: string; count: number }>;\n };\n updatedAt: string;\n}\n\nconst CAPTURE_DATA_QUERY = `\n query FieldCaptureData($context: ContextInput!) {\n getHealthyBowlFieldCaptureData(context: $context) {\n fields { id name cropNames }\n recentObservations { ${OBSERVATION_FIELDS} }\n stats { totalObservations observationsToday byType { observationType count } }\n updatedAt\n }\n }\n`;\n\nexport async function fetchFieldCaptureData(ctx: Ctx): Promise<FieldCaptureData | null> {\n const res = await graphqlFetch<{ getHealthyBowlFieldCaptureData: FieldCaptureData }>({\n gateway: 'workspace',\n query: CAPTURE_DATA_QUERY,\n variables: { context: ctx },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors && res.errors.length) return null;\n return res.data?.getHealthyBowlFieldCaptureData ?? null;\n}\n\nconst DOWNLOAD_URL_QUERY = `\n query HealthyBowlObservationPhotoUrl($id: ID!) {\n getFileDownloadUrl(id: $id, expiresIn: 21600)\n }\n`;\n\n/** Presigned URL for a synced photo (6h TTL, well under the S3 7-day cap). */\nexport async function fetchPhotoUrl(id: string): Promise<string | null> {\n try {\n const res = await graphqlFetch<{ getFileDownloadUrl: string | null }>({\n gateway: 'workspace',\n query: DOWNLOAD_URL_QUERY,\n variables: { id },\n workspaceToken: true,\n workspaceId: true,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors && res.errors.length) return null;\n return res.data?.getFileDownloadUrl ?? null;\n } catch {\n return null;\n }\n}\n"],"mappings":";;AAiBA,IAAa,IAAb,cAAsC,MAAM;CAC1C;CACA,YAAY,GAAiB,GAAc;AAGzC,EAFA,MAAM,EAAQ,EACd,KAAK,OAAO,oBACZ,KAAK,OAAO;;;AAIhB,SAAS,EAAW,GAAyD;AAC3E,KAAI,CAAC,KAAU,EAAO,WAAW,EAAG,QAAO;CAC3C,IAAM,IAAI,EAAO;AACjB,QAAO,IAAI,EAAiB,EAAE,YAAY,eAAe,EAAE,SAAS,EAAE,YAAY,QAAQ,wBAAwB;;AAKpH,IAAM,IAAqB,wOA2CrB,IAAgB;;;;;;wBAME,EAAmB;0BACjB,EAAmB;;;;;AAM7C,eAAsB,EAAiB,GAAU,GAAoD;CACnG,IAAM,IAAM,MAAM,EAA+D;EAC/E,SAAS;EACT,OAAO;EACP,WAAW,EAAE,OAAO;GAAE,SAAS;GAAK;GAAc,EAAE;EAGpD,gBAAgB;EAChB,aAAa,EAAI;EACjB,0BAA0B;EAC3B,CAAC,EACI,IAAM,EAAW,EAAI,OAAiC;AAC5D,KAAI,EAAK,OAAM;CACf,IAAM,IAAO,EAAI,MAAM;AACvB,KAAI,CAAC,EAAM,OAAM,IAAI,EAAiB,uBAAuB,wBAAwB;AACrF,QAAO;;AAmBT,IAAM,IAAmB;;kEAEyC,EAAmB;;;AAIrF,eAAsB,EAAgB,GAAU,GAAiD;CAC/F,IAAM,IAAM,MAAM,EAAgF;EAChG,SAAS;EACT,OAAO;EACP,WAAW,EAAE,OAAO;GAAE,GAAG;GAAO,SAAS;GAAK,EAAE;EAChD,gBAAgB;EAChB,aAAa,EAAI;EACj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