tempest-react-sdk 0.24.0 → 0.25.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 (106) hide show
  1. package/README.md +11 -3
  2. package/dist/charts/AreaChart.cjs +1 -1
  3. package/dist/charts/AreaChart.cjs.map +1 -1
  4. package/dist/charts/AreaChart.js +7 -7
  5. package/dist/charts/AreaChart.js.map +1 -1
  6. package/dist/charts/BarChart.cjs +1 -1
  7. package/dist/charts/BarChart.cjs.map +1 -1
  8. package/dist/charts/BarChart.js +7 -7
  9. package/dist/charts/BarChart.js.map +1 -1
  10. package/dist/charts/LineChart.cjs +1 -1
  11. package/dist/charts/LineChart.cjs.map +1 -1
  12. package/dist/charts/LineChart.js +6 -6
  13. package/dist/charts/LineChart.js.map +1 -1
  14. package/dist/charts/PieChart.cjs +1 -1
  15. package/dist/charts/PieChart.cjs.map +1 -1
  16. package/dist/charts/PieChart.js +6 -6
  17. package/dist/charts/PieChart.js.map +1 -1
  18. package/dist/charts/RadarChart.cjs +1 -1
  19. package/dist/charts/RadarChart.cjs.map +1 -1
  20. package/dist/charts/RadarChart.js +6 -6
  21. package/dist/charts/RadarChart.js.map +1 -1
  22. package/dist/charts/palette.cjs +1 -1
  23. package/dist/charts/palette.cjs.map +1 -1
  24. package/dist/charts/palette.js +19 -2
  25. package/dist/charts/palette.js.map +1 -1
  26. package/dist/charts/use-chart-colors.cjs +2 -0
  27. package/dist/charts/use-chart-colors.cjs.map +1 -0
  28. package/dist/charts/use-chart-colors.js +29 -0
  29. package/dist/charts/use-chart-colors.js.map +1 -0
  30. package/dist/charts.cjs +1 -1
  31. package/dist/charts.d.ts +59 -10
  32. package/dist/charts.js +8 -7
  33. package/dist/components/AvatarGroup/AvatarGroup.cjs +2 -0
  34. package/dist/components/AvatarGroup/AvatarGroup.cjs.map +1 -0
  35. package/dist/components/AvatarGroup/AvatarGroup.js +39 -0
  36. package/dist/components/AvatarGroup/AvatarGroup.js.map +1 -0
  37. package/dist/components/AvatarGroup/AvatarGroup.module.cjs +2 -0
  38. package/dist/components/AvatarGroup/AvatarGroup.module.cjs.map +1 -0
  39. package/dist/components/AvatarGroup/AvatarGroup.module.js +16 -0
  40. package/dist/components/AvatarGroup/AvatarGroup.module.js.map +1 -0
  41. package/dist/components/Lightbox/Lightbox.cjs +2 -0
  42. package/dist/components/Lightbox/Lightbox.cjs.map +1 -0
  43. package/dist/components/Lightbox/Lightbox.js +148 -0
  44. package/dist/components/Lightbox/Lightbox.js.map +1 -0
  45. package/dist/components/Lightbox/Lightbox.module.cjs +2 -0
  46. package/dist/components/Lightbox/Lightbox.module.cjs.map +1 -0
  47. package/dist/components/Lightbox/Lightbox.module.js +21 -0
  48. package/dist/components/Lightbox/Lightbox.module.js.map +1 -0
  49. package/dist/components/SignaturePad/SignaturePad.cjs +2 -0
  50. package/dist/components/SignaturePad/SignaturePad.cjs.map +1 -0
  51. package/dist/components/SignaturePad/SignaturePad.js +115 -0
  52. package/dist/components/SignaturePad/SignaturePad.js.map +1 -0
  53. package/dist/components/SignaturePad/SignaturePad.module.cjs +2 -0
  54. package/dist/components/SignaturePad/SignaturePad.module.cjs.map +1 -0
  55. package/dist/components/SignaturePad/SignaturePad.module.js +11 -0
  56. package/dist/components/SignaturePad/SignaturePad.module.js.map +1 -0
  57. package/dist/components/Stepper/Stepper.cjs +1 -1
  58. package/dist/components/Stepper/Stepper.cjs.map +1 -1
  59. package/dist/components/Stepper/Stepper.js +43 -19
  60. package/dist/components/Stepper/Stepper.js.map +1 -1
  61. package/dist/components/Stepper/Stepper.module.cjs +1 -1
  62. package/dist/components/Stepper/Stepper.module.cjs.map +1 -1
  63. package/dist/components/Stepper/Stepper.module.js +6 -3
  64. package/dist/components/Stepper/Stepper.module.js.map +1 -1
  65. package/dist/components/TreeView/TreeView.cjs +2 -0
  66. package/dist/components/TreeView/TreeView.cjs.map +1 -0
  67. package/dist/components/TreeView/TreeView.js +124 -0
  68. package/dist/components/TreeView/TreeView.js.map +1 -0
  69. package/dist/components/TreeView/TreeView.module.cjs +2 -0
  70. package/dist/components/TreeView/TreeView.module.cjs.map +1 -0
  71. package/dist/components/TreeView/TreeView.module.js +17 -0
  72. package/dist/components/TreeView/TreeView.module.js.map +1 -0
  73. package/dist/components/Wizard/Wizard.cjs +2 -0
  74. package/dist/components/Wizard/Wizard.cjs.map +1 -0
  75. package/dist/components/Wizard/Wizard.js +111 -0
  76. package/dist/components/Wizard/Wizard.js.map +1 -0
  77. package/dist/components/Wizard/Wizard.module.cjs +2 -0
  78. package/dist/components/Wizard/Wizard.module.cjs.map +1 -0
  79. package/dist/components/Wizard/Wizard.module.js +10 -0
  80. package/dist/components/Wizard/Wizard.module.js.map +1 -0
  81. package/dist/offline/create-offline-sync.cjs +1 -1
  82. package/dist/offline/create-offline-sync.cjs.map +1 -1
  83. package/dist/offline/create-offline-sync.js +8 -2
  84. package/dist/offline/create-offline-sync.js.map +1 -1
  85. package/dist/styles.css +1 -1
  86. package/dist/tempest-react-sdk.cjs +1 -1
  87. package/dist/tempest-react-sdk.d.ts +605 -2
  88. package/dist/tempest-react-sdk.js +255 -246
  89. package/dist/theme/apply-theme.cjs +2 -0
  90. package/dist/theme/apply-theme.cjs.map +1 -0
  91. package/dist/theme/apply-theme.js +24 -0
  92. package/dist/theme/apply-theme.js.map +1 -0
  93. package/dist/theme/color.cjs +2 -0
  94. package/dist/theme/color.cjs.map +1 -0
  95. package/dist/theme/color.js +130 -0
  96. package/dist/theme/color.js.map +1 -0
  97. package/dist/theme/create-theme.cjs +5 -0
  98. package/dist/theme/create-theme.cjs.map +1 -0
  99. package/dist/theme/create-theme.js +135 -0
  100. package/dist/theme/create-theme.js.map +1 -0
  101. package/dist/theme/theme-presets.cjs +2 -0
  102. package/dist/theme/theme-presets.cjs.map +1 -0
  103. package/dist/theme/theme-presets.js +82 -0
  104. package/dist/theme/theme-presets.js.map +1 -0
  105. package/dist/utilities.css +432 -0
  106. package/package.json +4 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TreeView.module.js","names":[],"sources":["../../../src/components/TreeView/TreeView.module.css"],"sourcesContent":[".tree {\n display: flex;\n flex-direction: column;\n margin: 0;\n padding: 0;\n list-style: none;\n color: var(--tempest-text);\n font-size: var(--tempest-text-sm);\n}\n\n.item {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n\n.row {\n display: flex;\n align-items: center;\n gap: var(--tempest-space-2);\n width: 100%;\n padding-block: var(--tempest-space-2);\n padding-inline-end: var(--tempest-space-3);\n border-radius: var(--tempest-radius-sm);\n cursor: pointer;\n user-select: none;\n transition:\n background-color var(--tempest-duration-fast) var(--tempest-ease-out),\n color var(--tempest-duration-fast) var(--tempest-ease-out);\n}\n\n.row:hover {\n background-color: var(--tempest-surface-2);\n}\n\n.row:focus-visible {\n outline: var(--tempest-focus-ring-width) solid var(--tempest-focus-ring-color);\n outline-offset: calc(var(--tempest-focus-ring-offset) * -1);\n}\n\n.selected {\n background-color: var(--tempest-primary-soft);\n color: var(--tempest-primary-on-soft);\n font-weight: var(--tempest-weight-medium);\n}\n\n.selected:hover {\n background-color: var(--tempest-primary-soft-hover);\n}\n\n.disabled {\n color: var(--tempest-text-subtle);\n cursor: not-allowed;\n}\n\n.disabled:hover {\n background-color: transparent;\n}\n\n.chevron {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex: 0 0 auto;\n width: 18px;\n height: 18px;\n border-radius: var(--tempest-radius-xs);\n color: var(--tempest-text-muted);\n transition: transform var(--tempest-duration-fast) var(--tempest-ease-out);\n}\n\n.chevron:hover {\n background-color: var(--tempest-surface-3);\n}\n\n.chevronOpen {\n transform: rotate(90deg);\n}\n\n.chevronPlaceholder {\n display: inline-block;\n flex: 0 0 auto;\n width: 18px;\n height: 18px;\n}\n\n.icon {\n display: inline-flex;\n align-items: center;\n flex: 0 0 auto;\n color: var(--tempest-text-muted);\n}\n\n.label {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n@media (prefers-reduced-motion: reduce) {\n .row,\n .chevron {\n transition: none;\n }\n}\n"],"mappings":""}
@@ -0,0 +1,2 @@
1
+ const e=require("../../utils/cn.cjs"),t=require("../Button/Button.cjs"),n=require("../Stepper/Stepper.cjs"),r=require("./Wizard.module.cjs");let i=require("react"),a=require("react/jsx-runtime");function o({steps:o,activeIndex:s,defaultActiveIndex:c=0,onStepChange:l,onComplete:u,nextLabel:d=`Next`,backLabel:f=`Back`,finishLabel:p=`Finish`,clickableSteps:m=!1,renderActions:h,className:g}){let _=s!==void 0,[v,y]=(0,i.useState)(c),[b,x]=(0,i.useState)(!1),S=Math.min(_?s:v,o.length-1),C=o[S],w=(0,i.useCallback)(e=>{_||y(e),l?.(e,o[e])},[_,l,o]),T=(0,i.useCallback)(async e=>{if(!e.validate)return!0;x(!0);try{return await e.validate()}catch{return!1}finally{x(!1)}},[]),E=(0,i.useCallback)(async()=>{if(await T(C)){if(S===o.length-1){await u?.();return}w(S+1)}},[S,w,u,T,C,o.length]),D=(0,i.useCallback)(()=>{S>0&&w(S-1)},[S,w]),O=(0,i.useCallback)(async e=>{let t=Math.max(0,Math.min(e,o.length-1));if(t!==S){if(t<S){w(t);return}for(let e=S;e<t;e+=1)if(!await T(o[e]))return;w(t)}},[S,w,T,o]),k=(0,i.useMemo)(()=>({activeIndex:S,step:C,validating:b,isFirst:S===0,isLast:S===o.length-1,next:E,back:D,goTo:O}),[D,S,O,E,C,o.length,b]),A=(0,i.useMemo)(()=>o.map(e=>({label:e.label,description:e.optional?`${e.description??``} (optional)`.trim():e.description})),[o]);return(0,a.jsxs)(`div`,{className:e.cn(r.default.wizard,g),children:[(0,a.jsx)(n.Stepper,{steps:A,current:S,onStepClick:m?e=>void O(e):void 0}),(0,a.jsx)(`div`,{className:r.default.body,role:`group`,"aria-label":C.label,children:typeof C.content==`function`?C.content(k):C.content}),h?h(k):(0,a.jsxs)(`div`,{className:r.default.actions,children:[(0,a.jsx)(t.Button,{variant:`secondary`,onClick:D,disabled:k.isFirst||b,children:f}),(0,a.jsx)(t.Button,{onClick:()=>void E(),loading:b,children:k.isLast?p:d})]})]})}exports.Wizard=o;
2
+ //# sourceMappingURL=Wizard.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Wizard.cjs","names":[],"sources":["../../../src/components/Wizard/Wizard.tsx"],"sourcesContent":["import { useCallback, useMemo, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { cn } from \"@/utils/cn\";\nimport { Button } from \"../Button\";\nimport { Stepper } from \"../Stepper\";\nimport styles from \"./Wizard.module.css\";\n\n/** One step of the flow. */\nexport interface WizardStep {\n /** Stable identifier. */\n id: string;\n /** Step label shown in the indicator. */\n label: string;\n /** Optional description under the label. */\n description?: string;\n /** Step body. A function receives the flow controls, for a \"skip\" link inside the form. */\n content: ReactNode | ((controls: WizardControls) => ReactNode);\n /**\n * Gate for leaving this step forward. Return `false` (or a rejected/`false`\n * promise) to keep the user here — typically `() => form.trigger()`.\n * Async is supported: the Next button shows a pending state while it runs.\n */\n validate?: () => boolean | Promise<boolean>;\n /** Marks the step as optional, so `onComplete` can ignore it. */\n optional?: boolean;\n}\n\n/** Flow controls handed to a step body and to `renderActions`. */\nexport interface WizardControls {\n /** Zero-based index of the current step. */\n activeIndex: number;\n /** The current step. */\n step: WizardStep;\n /** `true` while a `validate` promise is pending. */\n validating: boolean;\n isFirst: boolean;\n isLast: boolean;\n /** Run the current step's `validate` and advance when it passes. */\n next: () => Promise<void>;\n /** Go back one step. No validation — going back never blocks. */\n back: () => void;\n /** Jump to an index. Forward jumps validate every step in between. */\n goTo: (index: number) => Promise<void>;\n}\n\nexport interface WizardProps {\n steps: WizardStep[];\n /** Controlled active index. */\n activeIndex?: number;\n /** Uncontrolled initial index. Default `0`. */\n defaultActiveIndex?: number;\n onStepChange?: (index: number, step: WizardStep) => void;\n /** Called when the last step passes validation. */\n onComplete?: () => void | Promise<void>;\n /** Label of the advance button. Default `\"Next\"`. */\n nextLabel?: string;\n /** Label of the back button. Default `\"Back\"`. */\n backLabel?: string;\n /** Label of the button on the last step. Default `\"Finish\"`. */\n finishLabel?: string;\n /**\n * Allow clicking the indicator to jump. Default `false` — a wizard exists\n * because order matters, and a free jump skips the gates.\n */\n clickableSteps?: boolean;\n /** Replace the default button row. */\n renderActions?: (controls: WizardControls) => ReactNode;\n className?: string;\n}\n\n/**\n * Multi-step flow: step indicator, one body at a time, and navigation that\n * respects per-step validation.\n *\n * `Stepper` draws the indicator; this owns the part every app was rewriting — the\n * active index, the async gate before advancing, the disabled/pending buttons and\n * the completion call.\n *\n * Only the active step's body is mounted. Uncommitted input in a step you leave is\n * therefore lost unless the state lives outside (react-hook-form's `FormProvider`,\n * a store, a parent `useState`) — which is the right place for it anyway, since\n * the last step usually needs to submit everything at once.\n *\n * @example\n * ```tsx\n * const form = useZodForm(schema);\n *\n * <FormProvider {...form}>\n * <Wizard\n * steps={[\n * {\n * id: \"dados\",\n * label: \"Dados\",\n * validate: () => form.trigger([\"nome\", \"email\"]),\n * content: (\n * <>\n * <FormField name=\"nome\" label=\"Nome\"><Input /></FormField>\n * <FormField name=\"email\" label=\"E-mail\"><Input type=\"email\" /></FormField>\n * </>\n * ),\n * },\n * { id: \"revisao\", label: \"Revisão\", content: <Review /> },\n * ]}\n * onComplete={form.handleSubmit(onSubmit)}\n * />\n * </FormProvider>\n * ```\n */\nexport function Wizard({\n steps,\n activeIndex,\n defaultActiveIndex = 0,\n onStepChange,\n onComplete,\n nextLabel = \"Next\",\n backLabel = \"Back\",\n finishLabel = \"Finish\",\n clickableSteps = false,\n renderActions,\n className,\n}: WizardProps) {\n const isControlled = activeIndex !== undefined;\n const [internalIndex, setInternalIndex] = useState(defaultActiveIndex);\n const [validating, setValidating] = useState(false);\n\n const current = Math.min(isControlled ? activeIndex : internalIndex, steps.length - 1);\n const step = steps[current];\n\n const moveTo = useCallback(\n (index: number): void => {\n if (!isControlled) setInternalIndex(index);\n onStepChange?.(index, steps[index]);\n },\n [isControlled, onStepChange, steps],\n );\n\n /**\n * Run a step's gate. A gate that throws counts as \"not allowed\": a `validate`\n * wired to a network check should not strand the user on a half-advanced flow\n * when the request fails.\n */\n const runValidate = useCallback(async (candidate: WizardStep): Promise<boolean> => {\n if (!candidate.validate) return true;\n setValidating(true);\n try {\n return await candidate.validate();\n } catch {\n return false;\n } finally {\n setValidating(false);\n }\n }, []);\n\n const next = useCallback(async (): Promise<void> => {\n if (!(await runValidate(step))) return;\n if (current === steps.length - 1) {\n await onComplete?.();\n return;\n }\n moveTo(current + 1);\n }, [current, moveTo, onComplete, runValidate, step, steps.length]);\n\n const back = useCallback((): void => {\n if (current > 0) moveTo(current - 1);\n }, [current, moveTo]);\n\n const goTo = useCallback(\n async (index: number): Promise<void> => {\n const target = Math.max(0, Math.min(index, steps.length - 1));\n if (target === current) return;\n if (target < current) {\n moveTo(target);\n return;\n }\n for (let i = current; i < target; i += 1) {\n if (!(await runValidate(steps[i]))) return;\n }\n moveTo(target);\n },\n [current, moveTo, runValidate, steps],\n );\n\n const controls = useMemo<WizardControls>(\n () => ({\n activeIndex: current,\n step,\n validating,\n isFirst: current === 0,\n isLast: current === steps.length - 1,\n next,\n back,\n goTo,\n }),\n [back, current, goTo, next, step, steps.length, validating],\n );\n\n const indicatorSteps = useMemo(\n () =>\n steps.map((item) => ({\n label: item.label,\n description: item.optional\n ? `${item.description ?? \"\"} (optional)`.trim()\n : item.description,\n })),\n [steps],\n );\n\n return (\n <div className={cn(styles.wizard, className)}>\n <Stepper\n steps={indicatorSteps}\n current={current}\n onStepClick={clickableSteps ? (index) => void goTo(index) : undefined}\n />\n\n <div className={styles.body} role=\"group\" aria-label={step.label}>\n {typeof step.content === \"function\" ? step.content(controls) : step.content}\n </div>\n\n {renderActions ? (\n renderActions(controls)\n ) : (\n <div className={styles.actions}>\n <Button\n variant=\"secondary\"\n onClick={back}\n disabled={controls.isFirst || validating}\n >\n {backLabel}\n </Button>\n <Button onClick={() => void next()} loading={validating}>\n {controls.isLast ? finishLabel : nextLabel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,CAAQ,YAAe,KAAK,EAAK,EAAG,QAAS,WACxC,EAAS,OAAS,EAAc,CAC7B,CAAA,CACP,GAER,GAEb"}
@@ -0,0 +1,111 @@
1
+ import { cn as e } from "../../utils/cn.js";
2
+ import { Button as t } from "../Button/Button.js";
3
+ import { Stepper as n } from "../Stepper/Stepper.js";
4
+ import r from "./Wizard.module.js";
5
+ import { useCallback as i, useMemo as a, useState as o } from "react";
6
+ import { jsx as s, jsxs as c } from "react/jsx-runtime";
7
+ //#region src/components/Wizard/Wizard.tsx
8
+ function l({ steps: l, activeIndex: u, defaultActiveIndex: d = 0, onStepChange: f, onComplete: p, nextLabel: m = "Next", backLabel: h = "Back", finishLabel: g = "Finish", clickableSteps: _ = !1, renderActions: v, className: y }) {
9
+ let b = u !== void 0, [x, S] = o(d), [C, w] = o(!1), T = Math.min(b ? u : x, l.length - 1), E = l[T], D = i((e) => {
10
+ b || S(e), f?.(e, l[e]);
11
+ }, [
12
+ b,
13
+ f,
14
+ l
15
+ ]), O = i(async (e) => {
16
+ if (!e.validate) return !0;
17
+ w(!0);
18
+ try {
19
+ return await e.validate();
20
+ } catch {
21
+ return !1;
22
+ } finally {
23
+ w(!1);
24
+ }
25
+ }, []), k = i(async () => {
26
+ if (await O(E)) {
27
+ if (T === l.length - 1) {
28
+ await p?.();
29
+ return;
30
+ }
31
+ D(T + 1);
32
+ }
33
+ }, [
34
+ T,
35
+ D,
36
+ p,
37
+ O,
38
+ E,
39
+ l.length
40
+ ]), A = i(() => {
41
+ T > 0 && D(T - 1);
42
+ }, [T, D]), j = i(async (e) => {
43
+ let t = Math.max(0, Math.min(e, l.length - 1));
44
+ if (t !== T) {
45
+ if (t < T) {
46
+ D(t);
47
+ return;
48
+ }
49
+ for (let e = T; e < t; e += 1) if (!await O(l[e])) return;
50
+ D(t);
51
+ }
52
+ }, [
53
+ T,
54
+ D,
55
+ O,
56
+ l
57
+ ]), M = a(() => ({
58
+ activeIndex: T,
59
+ step: E,
60
+ validating: C,
61
+ isFirst: T === 0,
62
+ isLast: T === l.length - 1,
63
+ next: k,
64
+ back: A,
65
+ goTo: j
66
+ }), [
67
+ A,
68
+ T,
69
+ j,
70
+ k,
71
+ E,
72
+ l.length,
73
+ C
74
+ ]), N = a(() => l.map((e) => ({
75
+ label: e.label,
76
+ description: e.optional ? `${e.description ?? ""} (optional)`.trim() : e.description
77
+ })), [l]);
78
+ return /* @__PURE__ */ c("div", {
79
+ className: e(r.wizard, y),
80
+ children: [
81
+ /* @__PURE__ */ s(n, {
82
+ steps: N,
83
+ current: T,
84
+ onStepClick: _ ? (e) => void j(e) : void 0
85
+ }),
86
+ /* @__PURE__ */ s("div", {
87
+ className: r.body,
88
+ role: "group",
89
+ "aria-label": E.label,
90
+ children: typeof E.content == "function" ? E.content(M) : E.content
91
+ }),
92
+ v ? v(M) : /* @__PURE__ */ c("div", {
93
+ className: r.actions,
94
+ children: [/* @__PURE__ */ s(t, {
95
+ variant: "secondary",
96
+ onClick: A,
97
+ disabled: M.isFirst || C,
98
+ children: h
99
+ }), /* @__PURE__ */ s(t, {
100
+ onClick: () => void k(),
101
+ loading: C,
102
+ children: M.isLast ? g : m
103
+ })]
104
+ })
105
+ ]
106
+ });
107
+ }
108
+ //#endregion
109
+ export { l as Wizard };
110
+
111
+ //# sourceMappingURL=Wizard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Wizard.js","names":[],"sources":["../../../src/components/Wizard/Wizard.tsx"],"sourcesContent":["import { useCallback, useMemo, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { cn } from \"@/utils/cn\";\nimport { Button } from \"../Button\";\nimport { Stepper } from \"../Stepper\";\nimport styles from \"./Wizard.module.css\";\n\n/** One step of the flow. */\nexport interface WizardStep {\n /** Stable identifier. */\n id: string;\n /** Step label shown in the indicator. */\n label: string;\n /** Optional description under the label. */\n description?: string;\n /** Step body. A function receives the flow controls, for a \"skip\" link inside the form. */\n content: ReactNode | ((controls: WizardControls) => ReactNode);\n /**\n * Gate for leaving this step forward. Return `false` (or a rejected/`false`\n * promise) to keep the user here — typically `() => form.trigger()`.\n * Async is supported: the Next button shows a pending state while it runs.\n */\n validate?: () => boolean | Promise<boolean>;\n /** Marks the step as optional, so `onComplete` can ignore it. */\n optional?: boolean;\n}\n\n/** Flow controls handed to a step body and to `renderActions`. */\nexport interface WizardControls {\n /** Zero-based index of the current step. */\n activeIndex: number;\n /** The current step. */\n step: WizardStep;\n /** `true` while a `validate` promise is pending. */\n validating: boolean;\n isFirst: boolean;\n isLast: boolean;\n /** Run the current step's `validate` and advance when it passes. */\n next: () => Promise<void>;\n /** Go back one step. No validation — going back never blocks. */\n back: () => void;\n /** Jump to an index. Forward jumps validate every step in between. */\n goTo: (index: number) => Promise<void>;\n}\n\nexport interface WizardProps {\n steps: WizardStep[];\n /** Controlled active index. */\n activeIndex?: number;\n /** Uncontrolled initial index. Default `0`. */\n defaultActiveIndex?: number;\n onStepChange?: (index: number, step: WizardStep) => void;\n /** Called when the last step passes validation. */\n onComplete?: () => void | Promise<void>;\n /** Label of the advance button. Default `\"Next\"`. */\n nextLabel?: string;\n /** Label of the back button. Default `\"Back\"`. */\n backLabel?: string;\n /** Label of the button on the last step. Default `\"Finish\"`. */\n finishLabel?: string;\n /**\n * Allow clicking the indicator to jump. Default `false` — a wizard exists\n * because order matters, and a free jump skips the gates.\n */\n clickableSteps?: boolean;\n /** Replace the default button row. */\n renderActions?: (controls: WizardControls) => ReactNode;\n className?: string;\n}\n\n/**\n * Multi-step flow: step indicator, one body at a time, and navigation that\n * respects per-step validation.\n *\n * `Stepper` draws the indicator; this owns the part every app was rewriting — the\n * active index, the async gate before advancing, the disabled/pending buttons and\n * the completion call.\n *\n * Only the active step's body is mounted. Uncommitted input in a step you leave is\n * therefore lost unless the state lives outside (react-hook-form's `FormProvider`,\n * a store, a parent `useState`) — which is the right place for it anyway, since\n * the last step usually needs to submit everything at once.\n *\n * @example\n * ```tsx\n * const form = useZodForm(schema);\n *\n * <FormProvider {...form}>\n * <Wizard\n * steps={[\n * {\n * id: \"dados\",\n * label: \"Dados\",\n * validate: () => form.trigger([\"nome\", \"email\"]),\n * content: (\n * <>\n * <FormField name=\"nome\" label=\"Nome\"><Input /></FormField>\n * <FormField name=\"email\" label=\"E-mail\"><Input type=\"email\" /></FormField>\n * </>\n * ),\n * },\n * { id: \"revisao\", label: \"Revisão\", content: <Review /> },\n * ]}\n * onComplete={form.handleSubmit(onSubmit)}\n * />\n * </FormProvider>\n * ```\n */\nexport function Wizard({\n steps,\n activeIndex,\n defaultActiveIndex = 0,\n onStepChange,\n onComplete,\n nextLabel = \"Next\",\n backLabel = \"Back\",\n finishLabel = \"Finish\",\n clickableSteps = false,\n renderActions,\n className,\n}: WizardProps) {\n const isControlled = activeIndex !== undefined;\n const [internalIndex, setInternalIndex] = useState(defaultActiveIndex);\n const [validating, setValidating] = useState(false);\n\n const current = Math.min(isControlled ? activeIndex : internalIndex, steps.length - 1);\n const step = steps[current];\n\n const moveTo = useCallback(\n (index: number): void => {\n if (!isControlled) setInternalIndex(index);\n onStepChange?.(index, steps[index]);\n },\n [isControlled, onStepChange, steps],\n );\n\n /**\n * Run a step's gate. A gate that throws counts as \"not allowed\": a `validate`\n * wired to a network check should not strand the user on a half-advanced flow\n * when the request fails.\n */\n const runValidate = useCallback(async (candidate: WizardStep): Promise<boolean> => {\n if (!candidate.validate) return true;\n setValidating(true);\n try {\n return await candidate.validate();\n } catch {\n return false;\n } finally {\n setValidating(false);\n }\n }, []);\n\n const next = useCallback(async (): Promise<void> => {\n if (!(await runValidate(step))) return;\n if (current === steps.length - 1) {\n await onComplete?.();\n return;\n }\n moveTo(current + 1);\n }, [current, moveTo, onComplete, runValidate, step, steps.length]);\n\n const back = useCallback((): void => {\n if (current > 0) moveTo(current - 1);\n }, [current, moveTo]);\n\n const goTo = useCallback(\n async (index: number): Promise<void> => {\n const target = Math.max(0, Math.min(index, steps.length - 1));\n if (target === current) return;\n if (target < current) {\n moveTo(target);\n return;\n }\n for (let i = current; i < target; i += 1) {\n if (!(await runValidate(steps[i]))) return;\n }\n moveTo(target);\n },\n [current, moveTo, runValidate, steps],\n );\n\n const controls = useMemo<WizardControls>(\n () => ({\n activeIndex: current,\n step,\n validating,\n isFirst: current === 0,\n isLast: current === steps.length - 1,\n next,\n back,\n goTo,\n }),\n [back, current, goTo, next, step, steps.length, validating],\n );\n\n const indicatorSteps = useMemo(\n () =>\n steps.map((item) => ({\n label: item.label,\n description: item.optional\n ? `${item.description ?? \"\"} (optional)`.trim()\n : item.description,\n })),\n [steps],\n );\n\n return (\n <div className={cn(styles.wizard, className)}>\n <Stepper\n steps={indicatorSteps}\n current={current}\n onStepClick={clickableSteps ? (index) => void goTo(index) : undefined}\n />\n\n <div className={styles.body} role=\"group\" aria-label={step.label}>\n {typeof step.content === \"function\" ? step.content(controls) : step.content}\n </div>\n\n {renderActions ? (\n renderActions(controls)\n ) : (\n <div className={styles.actions}>\n <Button\n variant=\"secondary\"\n onClick={back}\n disabled={controls.isFirst || validating}\n >\n {backLabel}\n </Button>\n <Button onClick={() => void next()} loading={validating}>\n {controls.isLast ? finishLabel : nextLabel}\n </Button>\n </div>\n )}\n </div>\n );\n}\n"],"mappings":";;;;;;;AA4GA,SAAgB,EAAO,EACnB,UACA,gBACA,wBAAqB,GACrB,iBACA,eACA,eAAY,QACZ,eAAY,QACZ,iBAAc,UACd,oBAAiB,IACjB,kBACA,gBACY;CACZ,IAAM,IAAe,MAAgB,KAAA,GAC/B,CAAC,GAAe,KAAoB,EAAS,CAAkB,GAC/D,CAAC,GAAY,KAAiB,EAAS,EAAK,GAE5C,IAAU,KAAK,IAAI,IAAe,IAAc,GAAe,EAAM,SAAS,CAAC,GAC/E,IAAO,EAAM,IAEb,IAAS,GACV,MAAwB;EAErB,AADK,KAAc,EAAiB,CAAK,GACzC,IAAe,GAAO,EAAM,EAAM;CACtC,GACA;EAAC;EAAc;EAAc;CAAK,CACtC,GAOM,IAAc,EAAY,OAAO,MAA4C;EAC/E,IAAI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,kBAAC,GAAD;IACI,OAAO;IACE;IACT,aAAa,KAAkB,MAAU,KAAK,EAAK,CAAK,IAAI,KAAA;GAC/D,CAAA;GAED,kBAAC,OAAD;IAAK,WAAW,EAAO;IAAM,MAAK;IAAQ,cAAY,EAAK;cACtD,OAAO,EAAK,WAAY,aAAa,EAAK,QAAQ,CAAQ,IAAI,EAAK;GACnE,CAAA;GAEJ,IACG,EAAc,CAAQ,IAEtB,kBAAC,OAAD;IAAK,WAAW,EAAO;cAAvB,CACI,kBAAC,GAAD;KACI,SAAQ;KACR,SAAS;KACT,UAAU,EAAS,WAAW;eAE7B;IACG,CAAA,GACR,kBAAC,GAAD;KAAQ,eAAe,KAAK,EAAK;KAAG,SAAS;eACxC,EAAS,SAAS,IAAc;IAC7B,CAAA,CACP;;EAER;;AAEb"}
@@ -0,0 +1,2 @@
1
+ var e=`tempest_wizard_2BkgZ`,t=`tempest_body_ZDhtj`,n=`tempest_actions_-VsgT`,r={wizard:e,body:t,actions:n};exports.actions=n,exports.body=t,exports.default=r,exports.wizard=e;
2
+ //# sourceMappingURL=Wizard.module.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Wizard.module.cjs","names":[],"sources":["../../../src/components/Wizard/Wizard.module.css"],"sourcesContent":[".wizard {\n display: flex;\n flex-direction: column;\n gap: var(--tempest-space-6);\n width: 100%;\n}\n\n.body {\n display: flex;\n flex-direction: column;\n gap: var(--tempest-space-4);\n min-height: var(--tempest-wizard-body-min-height, 0);\n}\n\n.actions {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: var(--tempest-space-3);\n padding-top: var(--tempest-space-4);\n border-top: 1px solid var(--tempest-border);\n}\n"],"mappings":""}
@@ -0,0 +1,10 @@
1
+ //#region src/components/Wizard/Wizard.module.css
2
+ var e = "tempest_wizard_2BkgZ", t = "tempest_body_ZDhtj", n = "tempest_actions_-VsgT", r = {
3
+ wizard: e,
4
+ body: t,
5
+ actions: n
6
+ };
7
+ //#endregion
8
+ export { n as actions, t as body, r as default, e as wizard };
9
+
10
+ //# sourceMappingURL=Wizard.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Wizard.module.js","names":[],"sources":["../../../src/components/Wizard/Wizard.module.css"],"sourcesContent":[".wizard {\n display: flex;\n flex-direction: column;\n gap: var(--tempest-space-6);\n width: 100%;\n}\n\n.body {\n display: flex;\n flex-direction: column;\n gap: var(--tempest-space-4);\n min-height: var(--tempest-wizard-body-min-height, 0);\n}\n\n.actions {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: var(--tempest-space-3);\n padding-top: var(--tempest-space-4);\n border-top: 1px solid var(--tempest-border);\n}\n"],"mappings":""}
@@ -1,2 +1,2 @@
1
- const e=require("../utils/ids.cjs"),t=require("./create-offline-store.cjs");function n(e){let t=typeof localStorage<`u`;return{get:()=>t?localStorage.getItem(e):null,set:n=>{t&&localStorage.setItem(e,n)},clear:()=>{t&&localStorage.removeItem(e)}}}function r(r){let i=t.createOfflineStore({databaseName:r.databaseName,version:r.version??1,tableName:r.tableName??`outbox`,indexes:`&id, recordId, enqueuedAt`,keyPath:`id`}),a=`get`in r.watermark?r.watermark:n(r.watermark.storageKey),o=r.idPrefix??`outbox`,s=r.isOnline??(()=>typeof navigator<`u`?navigator.onLine:!0),c=null,l=new Set,u={phase:`idle`,pending:0,lastSummary:null,lastError:null,lastSyncedAt:null},d=r.crossTab===!0,f=r.broadcastChannelName??`tempest-sync:${r.databaseName}`,p=d&&typeof BroadcastChannel<`u`?new BroadcastChannel(f):null,m=!1;function h(){for(let e of l)e(u)}function g(e){u={...u,...e},h(),p&&!m&&p.postMessage(u)}p&&(p.onmessage=e=>{m||(u=e.data,h())});async function _(){g({pending:await i.count()})}async function v(e){let t=await i.list(void 0,{orderBy:`enqueuedAt`});for(let n of t)try{await r.deliver(n),await i.delete(n.id),await r.onEntryDelivered?.(n),e.succeeded+=1}catch(t){let a=t instanceof Error?t.message:`delivery failed`;await i.update(n.id,{attempts:n.attempts+1,lastError:a}),await r.onEntryFailed?.(n,t),e.failed+=1,e.lastError=a}}async function y(){let e=a.get(),t=null,n;do{let i=await r.pullPage(e,t);for(let e of i.items)await r.applyRemote(e);t=i.nextCursor,n=i.serverTime}while(t);n&&a.set(n)}async function b(e){let t=Date.now(),n={trigger:e,succeeded:0,failed:0,durationMs:0,skipped:!1,lastError:null};return s()?(await v(n),await y(),n.durationMs=Date.now()-t,n):(n.skipped=!0,n.durationMs=Date.now()-t,n)}async function x(e){let t=typeof navigator<`u`?navigator.locks:void 0;return!d||!t?b(e):await t.request(`${f}:flush`,{ifAvailable:!0},async t=>t?b(e):null)??{trigger:e,succeeded:0,failed:0,durationMs:0,skipped:!1,lastError:null}}return _(),{async enqueue(t,n,r){let a={id:e.randomId(o),op:t,recordId:n,enqueuedAt:Date.now(),attempts:0,payload:r};return await i.put(a),await _(),a.id},flush(e=`manual`){return c||=(g({phase:`syncing`}),x(e).then(async e=>(await _(),g({phase:e.skipped?`offline`:e.failed>0?`error`:`idle`,lastSummary:e,lastError:e.lastError,lastSyncedAt:e.skipped?u.lastSyncedAt:Date.now()}),e)).finally(()=>{c=null})),c},pendingCount(){return i.count()},listPending(){return i.list(void 0,{orderBy:`enqueuedAt`})},async clearOutbox(){await i.clear(),await _()},resetWatermark(){a.clear()},getState(){return u},subscribe(e){return l.add(e),()=>{l.delete(e)}},dispose(){m=!0,p?.close()}}}exports.createOfflineSync=r;
1
+ const e=require("../utils/ids.cjs"),t=require("./create-offline-store.cjs");function n(e){let t=typeof localStorage<`u`;return{get:()=>t?localStorage.getItem(e):null,set:n=>{t&&localStorage.setItem(e,n)},clear:()=>{t&&localStorage.removeItem(e)}}}function r(r){let i=t.createOfflineStore({databaseName:r.databaseName,version:r.version??1,tableName:r.tableName??`outbox`,indexes:`&id, recordId, enqueuedAt`,keyPath:`id`}),a=`get`in r.watermark?r.watermark:n(r.watermark.storageKey),o=r.idPrefix??`outbox`,s=r.isOnline??(()=>typeof navigator<`u`?navigator.onLine:!0),c=null,l=new Set,u={phase:`idle`,pending:0,lastSummary:null,lastError:null,lastSyncedAt:null},d=r.crossTab===!0,f=r.broadcastChannelName??`tempest-sync:${r.databaseName}`,p=d&&typeof BroadcastChannel<`u`?new BroadcastChannel(f):null,m=!1;function h(){for(let e of l)e(u)}function g(e){u={...u,...e},h(),p&&!m&&p.postMessage(u)}p&&(p.onmessage=e=>{m||(u=e.data,h())});async function _(){g({pending:await i.count()})}async function v(e){let t=await i.list(void 0,{orderBy:`enqueuedAt`});for(let n of t)try{await r.deliver(n),await i.delete(n.id),await r.onEntryDelivered?.(n),e.succeeded+=1}catch(t){let a=t instanceof Error?t.message:`delivery failed`;await i.update(n.id,{attempts:n.attempts+1,lastError:a}),await r.onEntryFailed?.(n,t),e.failed+=1,e.lastError=a}}async function y(){let e=a.get(),t=null,n;do{let i=await r.pullPage(e,t);for(let e of i.items)await r.applyRemote(e);t=i.nextCursor,n=i.serverTime}while(t);n&&a.set(n)}async function b(e){let t=Date.now(),n={trigger:e,succeeded:0,failed:0,durationMs:0,skipped:!1,lastError:null};return s()?(await v(n),await y(),n.durationMs=Date.now()-t,n):(n.skipped=!0,n.durationMs=Date.now()-t,n)}async function x(e){let t=typeof navigator<`u`?navigator.locks:void 0;return!d||!t?b(e):await t.request(`${f}:flush`,{ifAvailable:!0},async t=>t?b(e):null)??{trigger:e,succeeded:0,failed:0,durationMs:0,skipped:!1,lastError:null}}_();let S=0;function C(){let e=Date.now();return S=e>S?e:S+1,S}return{async enqueue(t,n,r){let a={id:e.randomId(o),op:t,recordId:n,enqueuedAt:C(),attempts:0,payload:r};return await i.put(a),await _(),a.id},flush(e=`manual`){return c||=(g({phase:`syncing`}),x(e).then(async e=>(await _(),g({phase:e.skipped?`offline`:e.failed>0?`error`:`idle`,lastSummary:e,lastError:e.lastError,lastSyncedAt:e.skipped?u.lastSyncedAt:Date.now()}),e)).finally(()=>{c=null})),c},pendingCount(){return i.count()},listPending(){return i.list(void 0,{orderBy:`enqueuedAt`})},async clearOutbox(){await i.clear(),await _()},resetWatermark(){a.clear()},getState(){return u},subscribe(e){return l.add(e),()=>{l.delete(e)}},dispose(){m=!0,p?.close()}}}exports.createOfflineSync=r;
2
2
  //# sourceMappingURL=create-offline-sync.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-offline-sync.cjs","names":[],"sources":["../../src/offline/create-offline-sync.ts"],"sourcesContent":["import { randomId } from \"../utils/ids\";\nimport { createOfflineStore } from \"./create-offline-store\";\n\n/**\n * Mutation kinds queued in the outbox.\n *\n * `create`/`update` carry a snapshot of the record; `delete` needs only the\n * record id. The distinction between `create` and `update` is advisory — the\n * engine treats both as \"deliver this record\" and leaves the create-vs-update\n * decision to the app's `deliver` callback (a `PUT` upsert usually ignores it).\n */\nexport type OutboxOp = \"create\" | \"update\" | \"delete\";\n\n/**\n * A single queued mutation.\n *\n * @typeParam TPayload - The record snapshot shape carried by\n * `create`/`update` entries (omitted for `delete`).\n */\nexport interface OutboxEntry<TPayload = unknown> {\n /** Stable per-entry id (generated with {@link randomId}). */\n id: string;\n /** The mutation kind. */\n op: OutboxOp;\n /** Primary key of the record the mutation targets. */\n recordId: string;\n /** Epoch milliseconds when the mutation was queued. */\n enqueuedAt: number;\n /** How many delivery attempts have been made so far. */\n attempts: number;\n /** Last delivery error message, kept for UI/debug. */\n lastError?: string;\n /** Record snapshot for `create`/`update`. Omitted for `delete`. */\n payload?: TPayload;\n}\n\n/**\n * Why a sync run was triggered. The listed values are the common ones; any\n * string is accepted so apps can add their own telemetry labels.\n */\nexport type SyncTrigger =\n \"boot\" | \"online-event\" | \"after-mutation\" | \"manual\" | \"interval\" | (string & {});\n\n/**\n * One page of the server delta pull.\n *\n * @typeParam TRemote - The server-side item shape.\n */\nexport interface PullPage<TRemote> {\n /** Items changed since the watermark, in this page. */\n items: TRemote[];\n /** Cursor for the next page, or `null` when this is the last page. */\n nextCursor: string | null;\n /**\n * Server clock to persist as the next watermark once the whole delta is\n * applied. `null` leaves the watermark unchanged.\n */\n serverTime: string | null;\n}\n\n/** Outcome of a single {@link OfflineSync.flush} run. */\nexport interface SyncRunSummary {\n /** The trigger passed to `flush`. */\n trigger: SyncTrigger;\n /** Entries delivered to the server this run. */\n succeeded: number;\n /** Entries that failed and stay queued for the next run. */\n failed: number;\n /** Total wall-clock milliseconds the run took. */\n durationMs: number;\n /** `true` when the run was skipped because the device was offline. */\n skipped: boolean;\n /** Last delivery error message seen this run, or `null` when none failed. */\n lastError: string | null;\n}\n\n/**\n * Coarse lifecycle phase of the sync engine, surfaced through\n * {@link OfflineSync.getState} / {@link OfflineSync.subscribe} for reactive UI.\n *\n * - `\"idle\"` — nothing in flight and the last run (if any) fully succeeded.\n * - `\"syncing\"` — a `flush` run is currently in progress.\n * - `\"offline\"` — the last run was skipped because the device was offline.\n * - `\"error\"` — the last run left at least one entry queued after a failure.\n */\nexport type SyncPhase = \"idle\" | \"syncing\" | \"offline\" | \"error\";\n\n/**\n * Immutable snapshot of the engine's reactive state. A fresh object is emitted\n * to subscribers on every change, so it is safe to use as a\n * `useSyncExternalStore` snapshot (reference equality signals \"no change\").\n */\nexport interface SyncState {\n /** Current lifecycle phase. */\n phase: SyncPhase;\n /** Number of mutations still queued in the outbox. */\n pending: number;\n /** Summary of the most recent `flush` run, or `null` before the first. */\n lastSummary: SyncRunSummary | null;\n /** Message of the most recent delivery failure, or `null`. */\n lastError: string | null;\n /** Epoch ms of the last non-skipped run, or `null` before the first. */\n lastSyncedAt: number | null;\n}\n\n/**\n * Pluggable persistence for the pull watermark (the \"changed since\" cursor).\n * Pass an object with a `storageKey` to use a `localStorage`-backed default.\n */\nexport interface WatermarkStore {\n /** Read the current watermark, or `null` when none is stored. */\n get: () => string | null;\n /** Persist a new watermark. */\n set: (value: string) => void;\n /** Drop the watermark (e.g. on logout / account switch). */\n clear: () => void;\n}\n\n/**\n * Configuration for {@link createOfflineSync}.\n *\n * The engine owns the outbox, the single-flight flush, the offline guard, the\n * paginated pull loop and the watermark; the three transport callbacks\n * (`deliver`, `pullPage`, `applyRemote`) are where the app plugs in its own\n * endpoints, record shape and conflict resolution.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n * @typeParam TRemote - Server item shape returned by `pullPage`.\n */\nexport interface OfflineSyncConfig<TPayload, TRemote> {\n /** IndexedDB database name for the outbox (kept separate per queue). */\n databaseName: string;\n /** Outbox object-store name. Default `\"outbox\"`. */\n tableName?: string;\n /** Outbox schema version. Default `1`. */\n version?: number;\n /** Prefix for generated entry ids. Default `\"outbox\"`. */\n idPrefix?: string;\n /**\n * Deliver one queued mutation to the server. Throwing keeps the entry\n * queued (its `attempts`/`lastError` are bumped) for the next run.\n */\n deliver: (entry: OutboxEntry<TPayload>) => Promise<void>;\n /** Fetch one page of the server delta since `since`, from `cursor`. */\n pullPage: (since: string | null, cursor: string | null) => Promise<PullPage<TRemote>>;\n /**\n * Merge one pulled item into the local store. The app owns conflict\n * resolution here (e.g. last-write-wins, keeping newer local pending\n * edits, resolving tombstones and downloading blobs).\n */\n applyRemote: (item: TRemote) => Promise<void>;\n /** Watermark persistence, or `{ storageKey }` for a `localStorage` default. */\n watermark: WatermarkStore | { storageKey: string };\n /** Called after an entry is delivered and acked. */\n onEntryDelivered?: (entry: OutboxEntry<TPayload>) => void | Promise<void>;\n /** Called after an entry fails delivery (it stays queued). */\n onEntryFailed?: (entry: OutboxEntry<TPayload>, error: unknown) => void | Promise<void>;\n /**\n * Connectivity check. Default reads `navigator.onLine` (always online in\n * non-browser environments). When it returns `false`, `flush` is skipped.\n */\n isOnline?: () => boolean;\n /**\n * Broadcast {@link SyncState} across browser tabs of the same origin via a\n * `BroadcastChannel`, so every tab shows a coherent pending count / phase\n * (e.g. one tab flushing drops the badge to zero everywhere). The outbox is\n * already a shared IndexedDB; this only shares the in-memory state. Silently\n * ignored where `BroadcastChannel` is unavailable. Default `false`.\n *\n * When the Web Locks API is available, `flush` is additionally coordinated\n * *across* tabs: only one tab runs at a time and others skip while the lock\n * is held (they pick up the result via the broadcast). Delivery should still\n * be idempotent (upsert by client id). Without Web Locks, `flush` falls back\n * to per-tab single-flight.\n */\n crossTab?: boolean;\n /** Channel name when `crossTab` is on. Default `tempest-sync:${databaseName}`. */\n broadcastChannelName?: string;\n}\n\n/**\n * Offline-first sync engine: a durable outbox plus a paginated delta pull.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n */\nexport interface OfflineSync<TPayload> {\n /**\n * Queue a mutation. Returns the generated entry id.\n *\n * @param op - The mutation kind.\n * @param recordId - Primary key of the affected record.\n * @param payload - Record snapshot (for `create`/`update`).\n */\n enqueue: (op: OutboxOp, recordId: string, payload?: TPayload) => Promise<string>;\n /**\n * Run a full sync (drain the outbox, then pull the delta). Concurrent\n * calls share one in-flight promise, so triggers never overlap.\n *\n * @param trigger - Label for why the run happened. Default `\"manual\"`.\n */\n flush: (trigger?: SyncTrigger) => Promise<SyncRunSummary>;\n /** Number of mutations still queued. */\n pendingCount: () => Promise<number>;\n /** The queued mutations in FIFO order. */\n listPending: () => Promise<OutboxEntry<TPayload>[]>;\n /** Drop every queued mutation (e.g. on logout). */\n clearOutbox: () => Promise<void>;\n /** Reset the pull watermark (e.g. on logout / account switch). */\n resetWatermark: () => void;\n /** Read the current reactive {@link SyncState} snapshot synchronously. */\n getState: () => SyncState;\n /**\n * Subscribe to {@link SyncState} changes. The listener fires on every\n * enqueue, flush transition and outbox clear.\n *\n * @param listener - Called with the new snapshot on each change.\n * @returns An unsubscribe function.\n */\n subscribe: (listener: (state: SyncState) => void) => () => void;\n /**\n * Release resources held by the engine — currently the cross-tab\n * `BroadcastChannel` when `crossTab` is enabled. Safe to call when none was\n * opened. Optional in long-lived apps (the channel is reclaimed on tab\n * close); call it in tests and on teardown.\n */\n dispose: () => void;\n}\n\n/**\n * Build a `localStorage`-backed {@link WatermarkStore}. Reads/writes are no-ops\n * when `localStorage` is unavailable (SSR / non-browser).\n *\n * @param key - The `localStorage` key.\n * @returns A watermark store persisting to `localStorage`.\n */\nfunction localStorageWatermark(key: string): WatermarkStore {\n const available = typeof localStorage !== \"undefined\";\n return {\n get: () => (available ? localStorage.getItem(key) : null),\n set: (value: string) => {\n if (available) localStorage.setItem(key, value);\n },\n clear: () => {\n if (available) localStorage.removeItem(key);\n },\n };\n}\n\n/**\n * Create an offline-first sync engine over an IndexedDB outbox.\n *\n * The engine drains queued mutations to the server (`deliver`) and pulls the\n * server delta back (`pullPage` + `applyRemote`), advancing a watermark so each\n * run only fetches what changed. `flush` is single-flight and skips cleanly\n * while offline; failed deliveries stay queued with their attempt count bumped.\n *\n * Dexie is an **optional peer dependency** (via {@link createOfflineStore}) —\n * install it (`npm i dexie`) when you use this engine.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n * @typeParam TRemote - Server item shape returned by `pullPage`.\n * @param config - Transport callbacks + outbox/watermark configuration.\n * @returns The sync handle (`enqueue`, `flush`, `pendingCount`, …).\n *\n * @example\n * const sync = createOfflineSync<Note, NoteDto>({\n * databaseName: \"NotesOutbox\",\n * watermark: { storageKey: \"notes.watermark\" },\n * deliver: async (entry) => {\n * if (entry.op === \"delete\") return api.remove(entry.recordId);\n * await api.upsert(entry.recordId, entry.payload!);\n * },\n * pullPage: async (since, cursor) => {\n * const page = await api.changes(since, cursor);\n * return { items: page.items, nextCursor: page.next, serverTime: page.now };\n * },\n * applyRemote: async (dto) => {\n * if (dto.deleted) return localStore.remove(dto.id);\n * await localStore.save(fromDto(dto));\n * },\n * });\n * await sync.enqueue(\"create\", note.id, note);\n * await sync.flush(\"after-mutation\");\n */\nexport function createOfflineSync<TPayload = unknown, TRemote = unknown>(\n config: OfflineSyncConfig<TPayload, TRemote>,\n): OfflineSync<TPayload> {\n const outbox = createOfflineStore<OutboxEntry<TPayload>, string>({\n databaseName: config.databaseName,\n version: config.version ?? 1,\n tableName: config.tableName ?? \"outbox\",\n indexes: \"&id, recordId, enqueuedAt\",\n keyPath: \"id\",\n });\n\n const watermark: WatermarkStore =\n \"get\" in config.watermark\n ? config.watermark\n : localStorageWatermark(config.watermark.storageKey);\n\n const idPrefix = config.idPrefix ?? \"outbox\";\n const isOnline =\n config.isOnline ?? (() => (typeof navigator !== \"undefined\" ? navigator.onLine : true));\n\n let inflight: Promise<SyncRunSummary> | null = null;\n\n const listeners = new Set<(state: SyncState) => void>();\n let state: SyncState = {\n phase: \"idle\",\n pending: 0,\n lastSummary: null,\n lastError: null,\n lastSyncedAt: null,\n };\n\n const crossTab = config.crossTab === true;\n const channelName = config.broadcastChannelName ?? `tempest-sync:${config.databaseName}`;\n const channel: BroadcastChannel | null =\n crossTab && typeof BroadcastChannel !== \"undefined\"\n ? new BroadcastChannel(channelName)\n : null;\n let closed = false;\n\n function notify(): void {\n for (const listener of listeners) listener(state);\n }\n\n function setState(patch: Partial<SyncState>): void {\n state = { ...state, ...patch };\n notify();\n if (channel && !closed) channel.postMessage(state);\n }\n\n if (channel) {\n channel.onmessage = (event: MessageEvent<SyncState>) => {\n if (closed) return;\n state = event.data;\n notify();\n };\n }\n\n async function refreshPending(): Promise<void> {\n setState({ pending: await outbox.count() });\n }\n\n async function push(summary: SyncRunSummary): Promise<void> {\n const entries = await outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n for (const entry of entries) {\n try {\n await config.deliver(entry);\n await outbox.delete(entry.id);\n await config.onEntryDelivered?.(entry);\n summary.succeeded += 1;\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : \"delivery failed\";\n await outbox.update(entry.id, {\n attempts: entry.attempts + 1,\n lastError: message,\n } as Partial<OutboxEntry<TPayload>>);\n await config.onEntryFailed?.(entry, cause);\n summary.failed += 1;\n summary.lastError = message;\n }\n }\n }\n\n async function pull(): Promise<void> {\n const since = watermark.get();\n let cursor: string | null = null;\n let serverTime: string | null;\n do {\n const page = await config.pullPage(since, cursor);\n for (const item of page.items) {\n await config.applyRemote(item);\n }\n cursor = page.nextCursor;\n serverTime = page.serverTime;\n } while (cursor);\n if (serverTime) watermark.set(serverTime);\n }\n\n async function runOnce(trigger: SyncTrigger): Promise<SyncRunSummary> {\n const startedAt = Date.now();\n const summary: SyncRunSummary = {\n trigger,\n succeeded: 0,\n failed: 0,\n durationMs: 0,\n skipped: false,\n lastError: null,\n };\n if (!isOnline()) {\n summary.skipped = true;\n summary.durationMs = Date.now() - startedAt;\n return summary;\n }\n await push(summary);\n await pull();\n summary.durationMs = Date.now() - startedAt;\n return summary;\n }\n\n /**\n * Run one sync pass, serialized across tabs when possible.\n *\n * With `crossTab` on and the Web Locks API available, the pass is wrapped in\n * an `ifAvailable` lock request: whichever tab holds the lock runs, and the\n * others get `null` back instead of duplicating the work — their `SyncState`\n * catches up through the `BroadcastChannel`. The no-op summary keeps\n * `skipped: false` on purpose: `skipped` means \"device offline\" (it maps to\n * `phase: \"offline\"`), which is not what happened here. Falls back to a plain\n * per-tab run when `crossTab` is off or Web Locks is missing.\n *\n * @param trigger - What asked for this run, carried into the summary.\n * @returns The run summary, or an empty summary when another tab held the lock.\n */\n async function runGuarded(trigger: SyncTrigger): Promise<SyncRunSummary> {\n const locks = typeof navigator !== \"undefined\" ? navigator.locks : undefined;\n if (!crossTab || !locks) return runOnce(trigger);\n const result = await locks.request(\n `${channelName}:flush`,\n { ifAvailable: true },\n async (lock) => (lock ? runOnce(trigger) : null),\n );\n return (\n result ?? {\n trigger,\n succeeded: 0,\n failed: 0,\n durationMs: 0,\n skipped: false,\n lastError: null,\n }\n );\n }\n\n void refreshPending();\n\n return {\n async enqueue(op, recordId, payload) {\n const entry: OutboxEntry<TPayload> = {\n id: randomId(idPrefix),\n op,\n recordId,\n enqueuedAt: Date.now(),\n attempts: 0,\n payload,\n };\n await outbox.put(entry);\n await refreshPending();\n return entry.id;\n },\n flush(trigger: SyncTrigger = \"manual\") {\n if (!inflight) {\n setState({ phase: \"syncing\" });\n inflight = runGuarded(trigger)\n .then(async (summary) => {\n await refreshPending();\n setState({\n phase: summary.skipped\n ? \"offline\"\n : summary.failed > 0\n ? \"error\"\n : \"idle\",\n lastSummary: summary,\n lastError: summary.lastError,\n lastSyncedAt: summary.skipped ? state.lastSyncedAt : Date.now(),\n });\n return summary;\n })\n .finally(() => {\n inflight = null;\n });\n }\n return inflight;\n },\n pendingCount() {\n return outbox.count();\n },\n listPending() {\n return outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n },\n async clearOutbox() {\n await outbox.clear();\n await refreshPending();\n },\n resetWatermark() {\n watermark.clear();\n },\n getState() {\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n closed = true;\n channel?.close();\n },\n };\n}\n"],"mappings":"4EA2OA,SAAS,EAAsB,EAA6B,CACxD,IAAM,EAAY,OAAO,aAAiB,IAC1C,MAAO,CACH,QAAY,EAAY,aAAa,QAAQ,CAAG,EAAI,KACpD,IAAM,GAAkB,CAChB,GAAW,aAAa,QAAQ,EAAK,CAAK,CAClD,EACA,UAAa,CACL,GAAW,aAAa,WAAW,CAAG,CAC9C,CACJ,CACJ,CAsCA,SAAgB,EACZ,EACqB,CACrB,IAAM,EAAS,EAAA,mBAAkD,CAC7D,aAAc,EAAO,aACrB,QAAS,EAAO,SAAW,EAC3B,UAAW,EAAO,WAAa,SAC/B,QAAS,4BACT,QAAS,IACb,CAAC,EAEK,EACF,QAAS,EAAO,UACV,EAAO,UACP,EAAsB,EAAO,UAAU,UAAU,EAErD,EAAW,EAAO,UAAY,SAC9B,EACF,EAAO,eAAoB,OAAO,UAAc,IAAc,UAAU,OAAS,IAEjF,EAA2C,KAEzC,EAAY,IAAI,IAClB,EAAmB,CACnB,MAAO,OACP,QAAS,EACT,YAAa,KACb,UAAW,KACX,aAAc,IAClB,EAEM,EAAW,EAAO,WAAa,GAC/B,EAAc,EAAO,sBAAwB,gBAAgB,EAAO,eACpE,EACF,GAAY,OAAO,iBAAqB,IAClC,IAAI,iBAAiB,CAAW,EAChC,KACN,EAAS,GAEb,SAAS,GAAe,CACpB,IAAK,IAAM,KAAY,EAAW,EAAS,CAAK,CACpD,CAEA,SAAS,EA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MAAM,CACpB,EACA,UAAW,CACP,OAAO,CACX,EACA,UAAU,EAAU,CAEhB,OADA,EAAU,IAAI,CAAQ,MACT,CACT,EAAU,OAAO,CAAQ,CAC7B,CACJ,EACA,SAAU,CACN,EAAS,GACT,GAAS,MAAM,CACnB,CACJ,CACJ"}
1
+ {"version":3,"file":"create-offline-sync.cjs","names":[],"sources":["../../src/offline/create-offline-sync.ts"],"sourcesContent":["import { randomId } from \"../utils/ids\";\nimport { createOfflineStore } from \"./create-offline-store\";\n\n/**\n * Mutation kinds queued in the outbox.\n *\n * `create`/`update` carry a snapshot of the record; `delete` needs only the\n * record id. The distinction between `create` and `update` is advisory — the\n * engine treats both as \"deliver this record\" and leaves the create-vs-update\n * decision to the app's `deliver` callback (a `PUT` upsert usually ignores it).\n */\nexport type OutboxOp = \"create\" | \"update\" | \"delete\";\n\n/**\n * A single queued mutation.\n *\n * @typeParam TPayload - The record snapshot shape carried by\n * `create`/`update` entries (omitted for `delete`).\n */\nexport interface OutboxEntry<TPayload = unknown> {\n /** Stable per-entry id (generated with {@link randomId}). */\n id: string;\n /** The mutation kind. */\n op: OutboxOp;\n /** Primary key of the record the mutation targets. */\n recordId: string;\n /**\n * Epoch milliseconds when the mutation was queued, and the FIFO sort key for\n * `listPending()` and the delivery loop. Strictly increasing per engine\n * instance: entries queued inside the same millisecond are spaced by 1ms so\n * the order never depends on how the index breaks a tie.\n */\n enqueuedAt: number;\n /** How many delivery attempts have been made so far. */\n attempts: number;\n /** Last delivery error message, kept for UI/debug. */\n lastError?: string;\n /** Record snapshot for `create`/`update`. Omitted for `delete`. */\n payload?: TPayload;\n}\n\n/**\n * Why a sync run was triggered. The listed values are the common ones; any\n * string is accepted so apps can add their own telemetry labels.\n */\nexport type SyncTrigger =\n \"boot\" | \"online-event\" | \"after-mutation\" | \"manual\" | \"interval\" | (string & {});\n\n/**\n * One page of the server delta pull.\n *\n * @typeParam TRemote - The server-side item shape.\n */\nexport interface PullPage<TRemote> {\n /** Items changed since the watermark, in this page. */\n items: TRemote[];\n /** Cursor for the next page, or `null` when this is the last page. */\n nextCursor: string | null;\n /**\n * Server clock to persist as the next watermark once the whole delta is\n * applied. `null` leaves the watermark unchanged.\n */\n serverTime: string | null;\n}\n\n/** Outcome of a single {@link OfflineSync.flush} run. */\nexport interface SyncRunSummary {\n /** The trigger passed to `flush`. */\n trigger: SyncTrigger;\n /** Entries delivered to the server this run. */\n succeeded: number;\n /** Entries that failed and stay queued for the next run. */\n failed: number;\n /** Total wall-clock milliseconds the run took. */\n durationMs: number;\n /** `true` when the run was skipped because the device was offline. */\n skipped: boolean;\n /** Last delivery error message seen this run, or `null` when none failed. */\n lastError: string | null;\n}\n\n/**\n * Coarse lifecycle phase of the sync engine, surfaced through\n * {@link OfflineSync.getState} / {@link OfflineSync.subscribe} for reactive UI.\n *\n * - `\"idle\"` — nothing in flight and the last run (if any) fully succeeded.\n * - `\"syncing\"` — a `flush` run is currently in progress.\n * - `\"offline\"` — the last run was skipped because the device was offline.\n * - `\"error\"` — the last run left at least one entry queued after a failure.\n */\nexport type SyncPhase = \"idle\" | \"syncing\" | \"offline\" | \"error\";\n\n/**\n * Immutable snapshot of the engine's reactive state. A fresh object is emitted\n * to subscribers on every change, so it is safe to use as a\n * `useSyncExternalStore` snapshot (reference equality signals \"no change\").\n */\nexport interface SyncState {\n /** Current lifecycle phase. */\n phase: SyncPhase;\n /** Number of mutations still queued in the outbox. */\n pending: number;\n /** Summary of the most recent `flush` run, or `null` before the first. */\n lastSummary: SyncRunSummary | null;\n /** Message of the most recent delivery failure, or `null`. */\n lastError: string | null;\n /** Epoch ms of the last non-skipped run, or `null` before the first. */\n lastSyncedAt: number | null;\n}\n\n/**\n * Pluggable persistence for the pull watermark (the \"changed since\" cursor).\n * Pass an object with a `storageKey` to use a `localStorage`-backed default.\n */\nexport interface WatermarkStore {\n /** Read the current watermark, or `null` when none is stored. */\n get: () => string | null;\n /** Persist a new watermark. */\n set: (value: string) => void;\n /** Drop the watermark (e.g. on logout / account switch). */\n clear: () => void;\n}\n\n/**\n * Configuration for {@link createOfflineSync}.\n *\n * The engine owns the outbox, the single-flight flush, the offline guard, the\n * paginated pull loop and the watermark; the three transport callbacks\n * (`deliver`, `pullPage`, `applyRemote`) are where the app plugs in its own\n * endpoints, record shape and conflict resolution.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n * @typeParam TRemote - Server item shape returned by `pullPage`.\n */\nexport interface OfflineSyncConfig<TPayload, TRemote> {\n /** IndexedDB database name for the outbox (kept separate per queue). */\n databaseName: string;\n /** Outbox object-store name. Default `\"outbox\"`. */\n tableName?: string;\n /** Outbox schema version. Default `1`. */\n version?: number;\n /** Prefix for generated entry ids. Default `\"outbox\"`. */\n idPrefix?: string;\n /**\n * Deliver one queued mutation to the server. Throwing keeps the entry\n * queued (its `attempts`/`lastError` are bumped) for the next run.\n */\n deliver: (entry: OutboxEntry<TPayload>) => Promise<void>;\n /** Fetch one page of the server delta since `since`, from `cursor`. */\n pullPage: (since: string | null, cursor: string | null) => Promise<PullPage<TRemote>>;\n /**\n * Merge one pulled item into the local store. The app owns conflict\n * resolution here (e.g. last-write-wins, keeping newer local pending\n * edits, resolving tombstones and downloading blobs).\n */\n applyRemote: (item: TRemote) => Promise<void>;\n /** Watermark persistence, or `{ storageKey }` for a `localStorage` default. */\n watermark: WatermarkStore | { storageKey: string };\n /** Called after an entry is delivered and acked. */\n onEntryDelivered?: (entry: OutboxEntry<TPayload>) => void | Promise<void>;\n /** Called after an entry fails delivery (it stays queued). */\n onEntryFailed?: (entry: OutboxEntry<TPayload>, error: unknown) => void | Promise<void>;\n /**\n * Connectivity check. Default reads `navigator.onLine` (always online in\n * non-browser environments). When it returns `false`, `flush` is skipped.\n */\n isOnline?: () => boolean;\n /**\n * Broadcast {@link SyncState} across browser tabs of the same origin via a\n * `BroadcastChannel`, so every tab shows a coherent pending count / phase\n * (e.g. one tab flushing drops the badge to zero everywhere). The outbox is\n * already a shared IndexedDB; this only shares the in-memory state. Silently\n * ignored where `BroadcastChannel` is unavailable. Default `false`.\n *\n * When the Web Locks API is available, `flush` is additionally coordinated\n * *across* tabs: only one tab runs at a time and others skip while the lock\n * is held (they pick up the result via the broadcast). Delivery should still\n * be idempotent (upsert by client id). Without Web Locks, `flush` falls back\n * to per-tab single-flight.\n */\n crossTab?: boolean;\n /** Channel name when `crossTab` is on. Default `tempest-sync:${databaseName}`. */\n broadcastChannelName?: string;\n}\n\n/**\n * Offline-first sync engine: a durable outbox plus a paginated delta pull.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n */\nexport interface OfflineSync<TPayload> {\n /**\n * Queue a mutation. Returns the generated entry id.\n *\n * @param op - The mutation kind.\n * @param recordId - Primary key of the affected record.\n * @param payload - Record snapshot (for `create`/`update`).\n */\n enqueue: (op: OutboxOp, recordId: string, payload?: TPayload) => Promise<string>;\n /**\n * Run a full sync (drain the outbox, then pull the delta). Concurrent\n * calls share one in-flight promise, so triggers never overlap.\n *\n * @param trigger - Label for why the run happened. Default `\"manual\"`.\n */\n flush: (trigger?: SyncTrigger) => Promise<SyncRunSummary>;\n /** Number of mutations still queued. */\n pendingCount: () => Promise<number>;\n /** The queued mutations in FIFO order. */\n listPending: () => Promise<OutboxEntry<TPayload>[]>;\n /** Drop every queued mutation (e.g. on logout). */\n clearOutbox: () => Promise<void>;\n /** Reset the pull watermark (e.g. on logout / account switch). */\n resetWatermark: () => void;\n /** Read the current reactive {@link SyncState} snapshot synchronously. */\n getState: () => SyncState;\n /**\n * Subscribe to {@link SyncState} changes. The listener fires on every\n * enqueue, flush transition and outbox clear.\n *\n * @param listener - Called with the new snapshot on each change.\n * @returns An unsubscribe function.\n */\n subscribe: (listener: (state: SyncState) => void) => () => void;\n /**\n * Release resources held by the engine — currently the cross-tab\n * `BroadcastChannel` when `crossTab` is enabled. Safe to call when none was\n * opened. Optional in long-lived apps (the channel is reclaimed on tab\n * close); call it in tests and on teardown.\n */\n dispose: () => void;\n}\n\n/**\n * Build a `localStorage`-backed {@link WatermarkStore}. Reads/writes are no-ops\n * when `localStorage` is unavailable (SSR / non-browser).\n *\n * @param key - The `localStorage` key.\n * @returns A watermark store persisting to `localStorage`.\n */\nfunction localStorageWatermark(key: string): WatermarkStore {\n const available = typeof localStorage !== \"undefined\";\n return {\n get: () => (available ? localStorage.getItem(key) : null),\n set: (value: string) => {\n if (available) localStorage.setItem(key, value);\n },\n clear: () => {\n if (available) localStorage.removeItem(key);\n },\n };\n}\n\n/**\n * Create an offline-first sync engine over an IndexedDB outbox.\n *\n * The engine drains queued mutations to the server (`deliver`) and pulls the\n * server delta back (`pullPage` + `applyRemote`), advancing a watermark so each\n * run only fetches what changed. `flush` is single-flight and skips cleanly\n * while offline; failed deliveries stay queued with their attempt count bumped.\n *\n * Dexie is an **optional peer dependency** (via {@link createOfflineStore}) —\n * install it (`npm i dexie`) when you use this engine.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n * @typeParam TRemote - Server item shape returned by `pullPage`.\n * @param config - Transport callbacks + outbox/watermark configuration.\n * @returns The sync handle (`enqueue`, `flush`, `pendingCount`, …).\n *\n * @example\n * const sync = createOfflineSync<Note, NoteDto>({\n * databaseName: \"NotesOutbox\",\n * watermark: { storageKey: \"notes.watermark\" },\n * deliver: async (entry) => {\n * if (entry.op === \"delete\") return api.remove(entry.recordId);\n * await api.upsert(entry.recordId, entry.payload!);\n * },\n * pullPage: async (since, cursor) => {\n * const page = await api.changes(since, cursor);\n * return { items: page.items, nextCursor: page.next, serverTime: page.now };\n * },\n * applyRemote: async (dto) => {\n * if (dto.deleted) return localStore.remove(dto.id);\n * await localStore.save(fromDto(dto));\n * },\n * });\n * await sync.enqueue(\"create\", note.id, note);\n * await sync.flush(\"after-mutation\");\n */\nexport function createOfflineSync<TPayload = unknown, TRemote = unknown>(\n config: OfflineSyncConfig<TPayload, TRemote>,\n): OfflineSync<TPayload> {\n const outbox = createOfflineStore<OutboxEntry<TPayload>, string>({\n databaseName: config.databaseName,\n version: config.version ?? 1,\n tableName: config.tableName ?? \"outbox\",\n indexes: \"&id, recordId, enqueuedAt\",\n keyPath: \"id\",\n });\n\n const watermark: WatermarkStore =\n \"get\" in config.watermark\n ? config.watermark\n : localStorageWatermark(config.watermark.storageKey);\n\n const idPrefix = config.idPrefix ?? \"outbox\";\n const isOnline =\n config.isOnline ?? (() => (typeof navigator !== \"undefined\" ? navigator.onLine : true));\n\n let inflight: Promise<SyncRunSummary> | null = null;\n\n const listeners = new Set<(state: SyncState) => void>();\n let state: SyncState = {\n phase: \"idle\",\n pending: 0,\n lastSummary: null,\n lastError: null,\n lastSyncedAt: null,\n };\n\n const crossTab = config.crossTab === true;\n const channelName = config.broadcastChannelName ?? `tempest-sync:${config.databaseName}`;\n const channel: BroadcastChannel | null =\n crossTab && typeof BroadcastChannel !== \"undefined\"\n ? new BroadcastChannel(channelName)\n : null;\n let closed = false;\n\n function notify(): void {\n for (const listener of listeners) listener(state);\n }\n\n function setState(patch: Partial<SyncState>): void {\n state = { ...state, ...patch };\n notify();\n if (channel && !closed) channel.postMessage(state);\n }\n\n if (channel) {\n channel.onmessage = (event: MessageEvent<SyncState>) => {\n if (closed) return;\n state = event.data;\n notify();\n };\n }\n\n async function refreshPending(): Promise<void> {\n setState({ pending: await outbox.count() });\n }\n\n async function push(summary: SyncRunSummary): Promise<void> {\n const entries = await outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n for (const entry of entries) {\n try {\n await config.deliver(entry);\n await outbox.delete(entry.id);\n await config.onEntryDelivered?.(entry);\n summary.succeeded += 1;\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : \"delivery failed\";\n await outbox.update(entry.id, {\n attempts: entry.attempts + 1,\n lastError: message,\n } as Partial<OutboxEntry<TPayload>>);\n await config.onEntryFailed?.(entry, cause);\n summary.failed += 1;\n summary.lastError = message;\n }\n }\n }\n\n async function pull(): Promise<void> {\n const since = watermark.get();\n let cursor: string | null = null;\n let serverTime: string | null;\n do {\n const page = await config.pullPage(since, cursor);\n for (const item of page.items) {\n await config.applyRemote(item);\n }\n cursor = page.nextCursor;\n serverTime = page.serverTime;\n } while (cursor);\n if (serverTime) watermark.set(serverTime);\n }\n\n async function runOnce(trigger: SyncTrigger): Promise<SyncRunSummary> {\n const startedAt = Date.now();\n const summary: SyncRunSummary = {\n trigger,\n succeeded: 0,\n failed: 0,\n durationMs: 0,\n skipped: false,\n lastError: null,\n };\n if (!isOnline()) {\n summary.skipped = true;\n summary.durationMs = Date.now() - startedAt;\n return summary;\n }\n await push(summary);\n await pull();\n summary.durationMs = Date.now() - startedAt;\n return summary;\n }\n\n /**\n * Run one sync pass, serialized across tabs when possible.\n *\n * With `crossTab` on and the Web Locks API available, the pass is wrapped in\n * an `ifAvailable` lock request: whichever tab holds the lock runs, and the\n * others get `null` back instead of duplicating the work — their `SyncState`\n * catches up through the `BroadcastChannel`. The no-op summary keeps\n * `skipped: false` on purpose: `skipped` means \"device offline\" (it maps to\n * `phase: \"offline\"`), which is not what happened here. Falls back to a plain\n * per-tab run when `crossTab` is off or Web Locks is missing.\n *\n * @param trigger - What asked for this run, carried into the summary.\n * @returns The run summary, or an empty summary when another tab held the lock.\n */\n async function runGuarded(trigger: SyncTrigger): Promise<SyncRunSummary> {\n const locks = typeof navigator !== \"undefined\" ? navigator.locks : undefined;\n if (!crossTab || !locks) return runOnce(trigger);\n const result = await locks.request(\n `${channelName}:flush`,\n { ifAvailable: true },\n async (lock) => (lock ? runOnce(trigger) : null),\n );\n return (\n result ?? {\n trigger,\n succeeded: 0,\n failed: 0,\n durationMs: 0,\n skipped: false,\n lastError: null,\n }\n );\n }\n\n void refreshPending();\n\n let lastEnqueuedAt = 0;\n\n /**\n * Timestamp for a new outbox entry, guaranteed to be strictly greater than\n * the previous one.\n *\n * `enqueuedAt` is the sort key for both `listPending()` and the delivery loop\n * in `flush()`. A plain `Date.now()` ties whenever two mutations are queued\n * within the same millisecond — which is normal in a burst — and a tie leaves\n * the order to the index, so a `create` could be delivered *after* the\n * `update` that depends on it. Advancing by 1ms on a tie keeps the queue FIFO\n * at the cost of a timestamp that can run a few milliseconds ahead of the wall\n * clock during a burst.\n *\n * Scope: this is per engine instance. Two tabs enqueueing in the same\n * millisecond can still tie; cross-tab FIFO would need a persisted sequence,\n * and the delivery loop is already single-flight across tabs via Web Locks.\n */\n function nextEnqueuedAt(): number {\n const now = Date.now();\n lastEnqueuedAt = now > lastEnqueuedAt ? now : lastEnqueuedAt + 1;\n return lastEnqueuedAt;\n }\n\n return {\n async enqueue(op, recordId, payload) {\n const entry: OutboxEntry<TPayload> = {\n id: randomId(idPrefix),\n op,\n recordId,\n enqueuedAt: nextEnqueuedAt(),\n attempts: 0,\n payload,\n };\n await outbox.put(entry);\n await refreshPending();\n return entry.id;\n },\n flush(trigger: SyncTrigger = \"manual\") {\n if (!inflight) {\n setState({ phase: \"syncing\" });\n inflight = runGuarded(trigger)\n .then(async (summary) => {\n await refreshPending();\n setState({\n phase: summary.skipped\n ? \"offline\"\n : summary.failed > 0\n ? \"error\"\n : \"idle\",\n lastSummary: summary,\n lastError: summary.lastError,\n lastSyncedAt: summary.skipped ? state.lastSyncedAt : Date.now(),\n });\n return summary;\n })\n .finally(() => {\n inflight = null;\n });\n }\n return inflight;\n },\n pendingCount() {\n return outbox.count();\n },\n listPending() {\n return outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n },\n async clearOutbox() {\n await outbox.clear();\n await refreshPending();\n },\n resetWatermark() {\n watermark.clear();\n },\n getState() {\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n closed = true;\n channel?.close();\n },\n };\n}\n"],"mappings":"4EAgPA,SAAS,EAAsB,EAA6B,CACxD,IAAM,EAAY,OAAO,aAAiB,IAC1C,MAAO,CACH,QAAY,EAAY,aAAa,QAAQ,CAAG,EAAI,KACpD,IAAM,GAAkB,CAChB,GAAW,aAAa,QAAQ,EAAK,CAAK,CAClD,EACA,UAAa,CACL,GAAW,aAAa,WAAW,C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D,CACX,CAEA,MAAO,CACH,MAAM,QAAQ,EAAI,EAAU,EAAS,CACjC,IAAM,EAA+B,CACjC,GAAI,EAAA,SAAS,CAAQ,EACrB,KACA,WACA,WAAY,EAAe,EAC3B,SAAU,EACV,SACJ,EAGA,OAFA,MAAM,EAAO,IAAI,CAAK,EACtB,MAAM,EAAe,EACd,EAAM,EACjB,EACA,MAAM,EAAuB,SAAU,CAsBnC,MArBA,CAEI,KADA,EAAS,CAAE,MAAO,SAAU,CAAC,EAClB,EAAW,CAAO,CAAC,CACzB,KAAK,KAAO,KACT,MAAM,EAAe,EACrB,EAAS,CACL,MAAO,EAAQ,QACT,UACA,EAAQ,OAAS,EACf,QACA,OACR,YAAa,EACb,UAAW,EAAQ,UACnB,aAAc,EAAQ,QAAU,EAAM,aAAe,KAAK,IAAI,CAClE,CAAC,EACM,EACV,CAAC,CACD,YAAc,CACX,EAAW,IACf,CAAC,GAEF,CACX,EACA,cAAe,CACX,OAAO,EAAO,MAAM,CACxB,EACA,aAAc,CACV,OAAO,EAAO,KAAK,IAAA,GAAW,CAAE,QAAS,YAAa,CAAC,CAC3D,EACA,MAAM,aAAc,CAChB,MAAM,EAAO,MAAM,EACnB,MAAM,EAAe,CACzB,EACA,gBAAiB,CACb,EAAU,MAAM,CACpB,EACA,UAAW,CACP,OAAO,CACX,EACA,UAAU,EAAU,CAEhB,OADA,EAAU,IAAI,CAAQ,MACT,CACT,EAAU,OAAO,CAAQ,CAC7B,CACJ,EACA,SAAU,CACN,EAAS,GACT,GAAS,MAAM,CACnB,CACJ,CACJ"}
@@ -85,13 +85,19 @@ function r(r) {
85
85
  lastError: null
86
86
  };
87
87
  }
88
- return _(), {
88
+ _();
89
+ let S = 0;
90
+ function C() {
91
+ let e = Date.now();
92
+ return S = e > S ? e : S + 1, S;
93
+ }
94
+ return {
89
95
  async enqueue(t, n, r) {
90
96
  let a = {
91
97
  id: e(o),
92
98
  op: t,
93
99
  recordId: n,
94
- enqueuedAt: Date.now(),
100
+ enqueuedAt: C(),
95
101
  attempts: 0,
96
102
  payload: r
97
103
  };
@@ -1 +1 @@
1
- {"version":3,"file":"create-offline-sync.js","names":[],"sources":["../../src/offline/create-offline-sync.ts"],"sourcesContent":["import { randomId } from \"../utils/ids\";\nimport { createOfflineStore } from \"./create-offline-store\";\n\n/**\n * Mutation kinds queued in the outbox.\n *\n * `create`/`update` carry a snapshot of the record; `delete` needs only the\n * record id. The distinction between `create` and `update` is advisory — the\n * engine treats both as \"deliver this record\" and leaves the create-vs-update\n * decision to the app's `deliver` callback (a `PUT` upsert usually ignores it).\n */\nexport type OutboxOp = \"create\" | \"update\" | \"delete\";\n\n/**\n * A single queued mutation.\n *\n * @typeParam TPayload - The record snapshot shape carried by\n * `create`/`update` entries (omitted for `delete`).\n */\nexport interface OutboxEntry<TPayload = unknown> {\n /** Stable per-entry id (generated with {@link randomId}). */\n id: string;\n /** The mutation kind. */\n op: OutboxOp;\n /** Primary key of the record the mutation targets. */\n recordId: string;\n /** Epoch milliseconds when the mutation was queued. */\n enqueuedAt: number;\n /** How many delivery attempts have been made so far. */\n attempts: number;\n /** Last delivery error message, kept for UI/debug. */\n lastError?: string;\n /** Record snapshot for `create`/`update`. Omitted for `delete`. */\n payload?: TPayload;\n}\n\n/**\n * Why a sync run was triggered. The listed values are the common ones; any\n * string is accepted so apps can add their own telemetry labels.\n */\nexport type SyncTrigger =\n \"boot\" | \"online-event\" | \"after-mutation\" | \"manual\" | \"interval\" | (string & {});\n\n/**\n * One page of the server delta pull.\n *\n * @typeParam TRemote - The server-side item shape.\n */\nexport interface PullPage<TRemote> {\n /** Items changed since the watermark, in this page. */\n items: TRemote[];\n /** Cursor for the next page, or `null` when this is the last page. */\n nextCursor: string | null;\n /**\n * Server clock to persist as the next watermark once the whole delta is\n * applied. `null` leaves the watermark unchanged.\n */\n serverTime: string | null;\n}\n\n/** Outcome of a single {@link OfflineSync.flush} run. */\nexport interface SyncRunSummary {\n /** The trigger passed to `flush`. */\n trigger: SyncTrigger;\n /** Entries delivered to the server this run. */\n succeeded: number;\n /** Entries that failed and stay queued for the next run. */\n failed: number;\n /** Total wall-clock milliseconds the run took. */\n durationMs: number;\n /** `true` when the run was skipped because the device was offline. */\n skipped: boolean;\n /** Last delivery error message seen this run, or `null` when none failed. */\n lastError: string | null;\n}\n\n/**\n * Coarse lifecycle phase of the sync engine, surfaced through\n * {@link OfflineSync.getState} / {@link OfflineSync.subscribe} for reactive UI.\n *\n * - `\"idle\"` — nothing in flight and the last run (if any) fully succeeded.\n * - `\"syncing\"` — a `flush` run is currently in progress.\n * - `\"offline\"` — the last run was skipped because the device was offline.\n * - `\"error\"` — the last run left at least one entry queued after a failure.\n */\nexport type SyncPhase = \"idle\" | \"syncing\" | \"offline\" | \"error\";\n\n/**\n * Immutable snapshot of the engine's reactive state. A fresh object is emitted\n * to subscribers on every change, so it is safe to use as a\n * `useSyncExternalStore` snapshot (reference equality signals \"no change\").\n */\nexport interface SyncState {\n /** Current lifecycle phase. */\n phase: SyncPhase;\n /** Number of mutations still queued in the outbox. */\n pending: number;\n /** Summary of the most recent `flush` run, or `null` before the first. */\n lastSummary: SyncRunSummary | null;\n /** Message of the most recent delivery failure, or `null`. */\n lastError: string | null;\n /** Epoch ms of the last non-skipped run, or `null` before the first. */\n lastSyncedAt: number | null;\n}\n\n/**\n * Pluggable persistence for the pull watermark (the \"changed since\" cursor).\n * Pass an object with a `storageKey` to use a `localStorage`-backed default.\n */\nexport interface WatermarkStore {\n /** Read the current watermark, or `null` when none is stored. */\n get: () => string | null;\n /** Persist a new watermark. */\n set: (value: string) => void;\n /** Drop the watermark (e.g. on logout / account switch). */\n clear: () => void;\n}\n\n/**\n * Configuration for {@link createOfflineSync}.\n *\n * The engine owns the outbox, the single-flight flush, the offline guard, the\n * paginated pull loop and the watermark; the three transport callbacks\n * (`deliver`, `pullPage`, `applyRemote`) are where the app plugs in its own\n * endpoints, record shape and conflict resolution.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n * @typeParam TRemote - Server item shape returned by `pullPage`.\n */\nexport interface OfflineSyncConfig<TPayload, TRemote> {\n /** IndexedDB database name for the outbox (kept separate per queue). */\n databaseName: string;\n /** Outbox object-store name. Default `\"outbox\"`. */\n tableName?: string;\n /** Outbox schema version. Default `1`. */\n version?: number;\n /** Prefix for generated entry ids. Default `\"outbox\"`. */\n idPrefix?: string;\n /**\n * Deliver one queued mutation to the server. Throwing keeps the entry\n * queued (its `attempts`/`lastError` are bumped) for the next run.\n */\n deliver: (entry: OutboxEntry<TPayload>) => Promise<void>;\n /** Fetch one page of the server delta since `since`, from `cursor`. */\n pullPage: (since: string | null, cursor: string | null) => Promise<PullPage<TRemote>>;\n /**\n * Merge one pulled item into the local store. The app owns conflict\n * resolution here (e.g. last-write-wins, keeping newer local pending\n * edits, resolving tombstones and downloading blobs).\n */\n applyRemote: (item: TRemote) => Promise<void>;\n /** Watermark persistence, or `{ storageKey }` for a `localStorage` default. */\n watermark: WatermarkStore | { storageKey: string };\n /** Called after an entry is delivered and acked. */\n onEntryDelivered?: (entry: OutboxEntry<TPayload>) => void | Promise<void>;\n /** Called after an entry fails delivery (it stays queued). */\n onEntryFailed?: (entry: OutboxEntry<TPayload>, error: unknown) => void | Promise<void>;\n /**\n * Connectivity check. Default reads `navigator.onLine` (always online in\n * non-browser environments). When it returns `false`, `flush` is skipped.\n */\n isOnline?: () => boolean;\n /**\n * Broadcast {@link SyncState} across browser tabs of the same origin via a\n * `BroadcastChannel`, so every tab shows a coherent pending count / phase\n * (e.g. one tab flushing drops the badge to zero everywhere). The outbox is\n * already a shared IndexedDB; this only shares the in-memory state. Silently\n * ignored where `BroadcastChannel` is unavailable. Default `false`.\n *\n * When the Web Locks API is available, `flush` is additionally coordinated\n * *across* tabs: only one tab runs at a time and others skip while the lock\n * is held (they pick up the result via the broadcast). Delivery should still\n * be idempotent (upsert by client id). Without Web Locks, `flush` falls back\n * to per-tab single-flight.\n */\n crossTab?: boolean;\n /** Channel name when `crossTab` is on. Default `tempest-sync:${databaseName}`. */\n broadcastChannelName?: string;\n}\n\n/**\n * Offline-first sync engine: a durable outbox plus a paginated delta pull.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n */\nexport interface OfflineSync<TPayload> {\n /**\n * Queue a mutation. Returns the generated entry id.\n *\n * @param op - The mutation kind.\n * @param recordId - Primary key of the affected record.\n * @param payload - Record snapshot (for `create`/`update`).\n */\n enqueue: (op: OutboxOp, recordId: string, payload?: TPayload) => Promise<string>;\n /**\n * Run a full sync (drain the outbox, then pull the delta). Concurrent\n * calls share one in-flight promise, so triggers never overlap.\n *\n * @param trigger - Label for why the run happened. Default `\"manual\"`.\n */\n flush: (trigger?: SyncTrigger) => Promise<SyncRunSummary>;\n /** Number of mutations still queued. */\n pendingCount: () => Promise<number>;\n /** The queued mutations in FIFO order. */\n listPending: () => Promise<OutboxEntry<TPayload>[]>;\n /** Drop every queued mutation (e.g. on logout). */\n clearOutbox: () => Promise<void>;\n /** Reset the pull watermark (e.g. on logout / account switch). */\n resetWatermark: () => void;\n /** Read the current reactive {@link SyncState} snapshot synchronously. */\n getState: () => SyncState;\n /**\n * Subscribe to {@link SyncState} changes. The listener fires on every\n * enqueue, flush transition and outbox clear.\n *\n * @param listener - Called with the new snapshot on each change.\n * @returns An unsubscribe function.\n */\n subscribe: (listener: (state: SyncState) => void) => () => void;\n /**\n * Release resources held by the engine — currently the cross-tab\n * `BroadcastChannel` when `crossTab` is enabled. Safe to call when none was\n * opened. Optional in long-lived apps (the channel is reclaimed on tab\n * close); call it in tests and on teardown.\n */\n dispose: () => void;\n}\n\n/**\n * Build a `localStorage`-backed {@link WatermarkStore}. Reads/writes are no-ops\n * when `localStorage` is unavailable (SSR / non-browser).\n *\n * @param key - The `localStorage` key.\n * @returns A watermark store persisting to `localStorage`.\n */\nfunction localStorageWatermark(key: string): WatermarkStore {\n const available = typeof localStorage !== \"undefined\";\n return {\n get: () => (available ? localStorage.getItem(key) : null),\n set: (value: string) => {\n if (available) localStorage.setItem(key, value);\n },\n clear: () => {\n if (available) localStorage.removeItem(key);\n },\n };\n}\n\n/**\n * Create an offline-first sync engine over an IndexedDB outbox.\n *\n * The engine drains queued mutations to the server (`deliver`) and pulls the\n * server delta back (`pullPage` + `applyRemote`), advancing a watermark so each\n * run only fetches what changed. `flush` is single-flight and skips cleanly\n * while offline; failed deliveries stay queued with their attempt count bumped.\n *\n * Dexie is an **optional peer dependency** (via {@link createOfflineStore}) —\n * install it (`npm i dexie`) when you use this engine.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n * @typeParam TRemote - Server item shape returned by `pullPage`.\n * @param config - Transport callbacks + outbox/watermark configuration.\n * @returns The sync handle (`enqueue`, `flush`, `pendingCount`, …).\n *\n * @example\n * const sync = createOfflineSync<Note, NoteDto>({\n * databaseName: \"NotesOutbox\",\n * watermark: { storageKey: \"notes.watermark\" },\n * deliver: async (entry) => {\n * if (entry.op === \"delete\") return api.remove(entry.recordId);\n * await api.upsert(entry.recordId, entry.payload!);\n * },\n * pullPage: async (since, cursor) => {\n * const page = await api.changes(since, cursor);\n * return { items: page.items, nextCursor: page.next, serverTime: page.now };\n * },\n * applyRemote: async (dto) => {\n * if (dto.deleted) return localStore.remove(dto.id);\n * await localStore.save(fromDto(dto));\n * },\n * });\n * await sync.enqueue(\"create\", note.id, note);\n * await sync.flush(\"after-mutation\");\n */\nexport function createOfflineSync<TPayload = unknown, TRemote = unknown>(\n config: OfflineSyncConfig<TPayload, TRemote>,\n): OfflineSync<TPayload> {\n const outbox = createOfflineStore<OutboxEntry<TPayload>, string>({\n databaseName: config.databaseName,\n version: config.version ?? 1,\n tableName: config.tableName ?? \"outbox\",\n indexes: \"&id, recordId, enqueuedAt\",\n keyPath: \"id\",\n });\n\n const watermark: WatermarkStore =\n \"get\" in config.watermark\n ? config.watermark\n : localStorageWatermark(config.watermark.storageKey);\n\n const idPrefix = config.idPrefix ?? \"outbox\";\n const isOnline =\n config.isOnline ?? (() => (typeof navigator !== \"undefined\" ? navigator.onLine : true));\n\n let inflight: Promise<SyncRunSummary> | null = null;\n\n const listeners = new Set<(state: SyncState) => void>();\n let state: SyncState = {\n phase: \"idle\",\n pending: 0,\n lastSummary: null,\n lastError: null,\n lastSyncedAt: null,\n };\n\n const crossTab = config.crossTab === true;\n const channelName = config.broadcastChannelName ?? `tempest-sync:${config.databaseName}`;\n const channel: BroadcastChannel | null =\n crossTab && typeof BroadcastChannel !== \"undefined\"\n ? new BroadcastChannel(channelName)\n : null;\n let closed = false;\n\n function notify(): void {\n for (const listener of listeners) listener(state);\n }\n\n function setState(patch: Partial<SyncState>): void {\n state = { ...state, ...patch };\n notify();\n if (channel && !closed) channel.postMessage(state);\n }\n\n if (channel) {\n channel.onmessage = (event: MessageEvent<SyncState>) => {\n if (closed) return;\n state = event.data;\n notify();\n };\n }\n\n async function refreshPending(): Promise<void> {\n setState({ pending: await outbox.count() });\n }\n\n async function push(summary: SyncRunSummary): Promise<void> {\n const entries = await outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n for (const entry of entries) {\n try {\n await config.deliver(entry);\n await outbox.delete(entry.id);\n await config.onEntryDelivered?.(entry);\n summary.succeeded += 1;\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : \"delivery failed\";\n await outbox.update(entry.id, {\n attempts: entry.attempts + 1,\n lastError: message,\n } as Partial<OutboxEntry<TPayload>>);\n await config.onEntryFailed?.(entry, cause);\n summary.failed += 1;\n summary.lastError = message;\n }\n }\n }\n\n async function pull(): Promise<void> {\n const since = watermark.get();\n let cursor: string | null = null;\n let serverTime: string | null;\n do {\n const page = await config.pullPage(since, cursor);\n for (const item of page.items) {\n await config.applyRemote(item);\n }\n cursor = page.nextCursor;\n serverTime = page.serverTime;\n } while (cursor);\n if (serverTime) watermark.set(serverTime);\n }\n\n async function runOnce(trigger: SyncTrigger): Promise<SyncRunSummary> {\n const startedAt = Date.now();\n const summary: SyncRunSummary = {\n trigger,\n succeeded: 0,\n failed: 0,\n durationMs: 0,\n skipped: false,\n lastError: null,\n };\n if (!isOnline()) {\n summary.skipped = true;\n summary.durationMs = Date.now() - startedAt;\n return summary;\n }\n await push(summary);\n await pull();\n summary.durationMs = Date.now() - startedAt;\n return summary;\n }\n\n /**\n * Run one sync pass, serialized across tabs when possible.\n *\n * With `crossTab` on and the Web Locks API available, the pass is wrapped in\n * an `ifAvailable` lock request: whichever tab holds the lock runs, and the\n * others get `null` back instead of duplicating the work — their `SyncState`\n * catches up through the `BroadcastChannel`. The no-op summary keeps\n * `skipped: false` on purpose: `skipped` means \"device offline\" (it maps to\n * `phase: \"offline\"`), which is not what happened here. Falls back to a plain\n * per-tab run when `crossTab` is off or Web Locks is missing.\n *\n * @param trigger - What asked for this run, carried into the summary.\n * @returns The run summary, or an empty summary when another tab held the lock.\n */\n async function runGuarded(trigger: SyncTrigger): Promise<SyncRunSummary> {\n const locks = typeof navigator !== \"undefined\" ? navigator.locks : undefined;\n if (!crossTab || !locks) return runOnce(trigger);\n const result = await locks.request(\n `${channelName}:flush`,\n { ifAvailable: true },\n async (lock) => (lock ? runOnce(trigger) : null),\n );\n return (\n result ?? {\n trigger,\n succeeded: 0,\n failed: 0,\n durationMs: 0,\n skipped: false,\n lastError: null,\n }\n );\n }\n\n void refreshPending();\n\n return {\n async enqueue(op, recordId, payload) {\n const entry: OutboxEntry<TPayload> = {\n id: randomId(idPrefix),\n op,\n recordId,\n enqueuedAt: Date.now(),\n attempts: 0,\n payload,\n };\n await outbox.put(entry);\n await refreshPending();\n return entry.id;\n },\n flush(trigger: SyncTrigger = \"manual\") {\n if (!inflight) {\n setState({ phase: \"syncing\" });\n inflight = runGuarded(trigger)\n .then(async (summary) => {\n await refreshPending();\n setState({\n phase: summary.skipped\n ? \"offline\"\n : summary.failed > 0\n ? \"error\"\n : \"idle\",\n lastSummary: summary,\n lastError: summary.lastError,\n lastSyncedAt: summary.skipped ? state.lastSyncedAt : Date.now(),\n });\n return summary;\n })\n .finally(() => {\n inflight = null;\n });\n }\n return inflight;\n },\n pendingCount() {\n return outbox.count();\n },\n listPending() {\n return outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n },\n async clearOutbox() {\n await outbox.clear();\n await refreshPending();\n },\n resetWatermark() {\n watermark.clear();\n },\n getState() {\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n closed = true;\n channel?.close();\n },\n };\n}\n"],"mappings":";;;AA2OA,SAAS,EAAsB,GAA6B;CACxD,IAAM,IAAY,OAAO,eAAiB;CAC1C,OAAO;EACH,WAAY,IAAY,aAAa,QAAQ,CAAG,IAAI;EACpD,MAAM,MAAkB;GACpB,AAAI,KAAW,aAAa,QAAQ,GAAK,CAAK;EAClD;EACA,aAAa;GACT,AAAI,KAAW,aAAa,WAAW,CAAG;EAC9C;CACJ;AACJ;AAsCA,SAAgB,EACZ,GACqB;CACrB,IAAM,IAAS,EAAkD;EAC7D,cAAc,EAAO;EACrB,SAAS,EAAO,WAAW;EAC3B,WAAW,EAAO,aAAa;EAC/B,SAAS;EACT,SAAS;CACb,CAAC,GAEK,IACF,SAAS,EAAO,YACV,EAAO,YACP,EAAsB,EAAO,UAAU,UAAU,GAErD,IAAW,EAAO,YAAY,UAC9B,IACF,EAAO,mBAAoB,OAAO,YAAc,MAAc,UAAU,SAAS,KAEjF,IAA2C,MAEzC,oBAAY,IAAI,IAAgC,GAClD,IAAmB;EACnB,OAAO;EACP,SAAS;EACT,aAAa;EACb,WAAW;EACX,cAAc;CAClB,GAEM,IAAW,EAAO,aAAa,IAC/B,IAAc,EAAO,wBAAwB,gBAAgB,EAAO,gBACpE,IACF,KAAY,OAAO,mBAAqB,MAClC,IAAI,iBAAiB,CAAW,IAChC,MACN,IAAS;CAEb,SAAS,IAAe;EACpB,KAAK,IAAM,KAAY,GAAW,EAAS,CAAK;CACpD;CAEA,SAAS,EAAS,GAAiC;EAG/C,AAFA,IAAQ;GAAE,GAAG;GAAO,GAAG;EAAM,GAC7B,EAAO,GACH,KAAW,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AAU;GAEhB,OADA,EAAU,IAAI,CAAQ,SACT;IACT,EAAU,OAAO,CAAQ;GAC7B;EACJ;EACA,UAAU;GAEN,AADA,IAAS,IACT,GAAS,MAAM;EACnB;CACJ;AACJ"}
1
+ {"version":3,"file":"create-offline-sync.js","names":[],"sources":["../../src/offline/create-offline-sync.ts"],"sourcesContent":["import { randomId } from \"../utils/ids\";\nimport { createOfflineStore } from \"./create-offline-store\";\n\n/**\n * Mutation kinds queued in the outbox.\n *\n * `create`/`update` carry a snapshot of the record; `delete` needs only the\n * record id. The distinction between `create` and `update` is advisory — the\n * engine treats both as \"deliver this record\" and leaves the create-vs-update\n * decision to the app's `deliver` callback (a `PUT` upsert usually ignores it).\n */\nexport type OutboxOp = \"create\" | \"update\" | \"delete\";\n\n/**\n * A single queued mutation.\n *\n * @typeParam TPayload - The record snapshot shape carried by\n * `create`/`update` entries (omitted for `delete`).\n */\nexport interface OutboxEntry<TPayload = unknown> {\n /** Stable per-entry id (generated with {@link randomId}). */\n id: string;\n /** The mutation kind. */\n op: OutboxOp;\n /** Primary key of the record the mutation targets. */\n recordId: string;\n /**\n * Epoch milliseconds when the mutation was queued, and the FIFO sort key for\n * `listPending()` and the delivery loop. Strictly increasing per engine\n * instance: entries queued inside the same millisecond are spaced by 1ms so\n * the order never depends on how the index breaks a tie.\n */\n enqueuedAt: number;\n /** How many delivery attempts have been made so far. */\n attempts: number;\n /** Last delivery error message, kept for UI/debug. */\n lastError?: string;\n /** Record snapshot for `create`/`update`. Omitted for `delete`. */\n payload?: TPayload;\n}\n\n/**\n * Why a sync run was triggered. The listed values are the common ones; any\n * string is accepted so apps can add their own telemetry labels.\n */\nexport type SyncTrigger =\n \"boot\" | \"online-event\" | \"after-mutation\" | \"manual\" | \"interval\" | (string & {});\n\n/**\n * One page of the server delta pull.\n *\n * @typeParam TRemote - The server-side item shape.\n */\nexport interface PullPage<TRemote> {\n /** Items changed since the watermark, in this page. */\n items: TRemote[];\n /** Cursor for the next page, or `null` when this is the last page. */\n nextCursor: string | null;\n /**\n * Server clock to persist as the next watermark once the whole delta is\n * applied. `null` leaves the watermark unchanged.\n */\n serverTime: string | null;\n}\n\n/** Outcome of a single {@link OfflineSync.flush} run. */\nexport interface SyncRunSummary {\n /** The trigger passed to `flush`. */\n trigger: SyncTrigger;\n /** Entries delivered to the server this run. */\n succeeded: number;\n /** Entries that failed and stay queued for the next run. */\n failed: number;\n /** Total wall-clock milliseconds the run took. */\n durationMs: number;\n /** `true` when the run was skipped because the device was offline. */\n skipped: boolean;\n /** Last delivery error message seen this run, or `null` when none failed. */\n lastError: string | null;\n}\n\n/**\n * Coarse lifecycle phase of the sync engine, surfaced through\n * {@link OfflineSync.getState} / {@link OfflineSync.subscribe} for reactive UI.\n *\n * - `\"idle\"` — nothing in flight and the last run (if any) fully succeeded.\n * - `\"syncing\"` — a `flush` run is currently in progress.\n * - `\"offline\"` — the last run was skipped because the device was offline.\n * - `\"error\"` — the last run left at least one entry queued after a failure.\n */\nexport type SyncPhase = \"idle\" | \"syncing\" | \"offline\" | \"error\";\n\n/**\n * Immutable snapshot of the engine's reactive state. A fresh object is emitted\n * to subscribers on every change, so it is safe to use as a\n * `useSyncExternalStore` snapshot (reference equality signals \"no change\").\n */\nexport interface SyncState {\n /** Current lifecycle phase. */\n phase: SyncPhase;\n /** Number of mutations still queued in the outbox. */\n pending: number;\n /** Summary of the most recent `flush` run, or `null` before the first. */\n lastSummary: SyncRunSummary | null;\n /** Message of the most recent delivery failure, or `null`. */\n lastError: string | null;\n /** Epoch ms of the last non-skipped run, or `null` before the first. */\n lastSyncedAt: number | null;\n}\n\n/**\n * Pluggable persistence for the pull watermark (the \"changed since\" cursor).\n * Pass an object with a `storageKey` to use a `localStorage`-backed default.\n */\nexport interface WatermarkStore {\n /** Read the current watermark, or `null` when none is stored. */\n get: () => string | null;\n /** Persist a new watermark. */\n set: (value: string) => void;\n /** Drop the watermark (e.g. on logout / account switch). */\n clear: () => void;\n}\n\n/**\n * Configuration for {@link createOfflineSync}.\n *\n * The engine owns the outbox, the single-flight flush, the offline guard, the\n * paginated pull loop and the watermark; the three transport callbacks\n * (`deliver`, `pullPage`, `applyRemote`) are where the app plugs in its own\n * endpoints, record shape and conflict resolution.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n * @typeParam TRemote - Server item shape returned by `pullPage`.\n */\nexport interface OfflineSyncConfig<TPayload, TRemote> {\n /** IndexedDB database name for the outbox (kept separate per queue). */\n databaseName: string;\n /** Outbox object-store name. Default `\"outbox\"`. */\n tableName?: string;\n /** Outbox schema version. Default `1`. */\n version?: number;\n /** Prefix for generated entry ids. Default `\"outbox\"`. */\n idPrefix?: string;\n /**\n * Deliver one queued mutation to the server. Throwing keeps the entry\n * queued (its `attempts`/`lastError` are bumped) for the next run.\n */\n deliver: (entry: OutboxEntry<TPayload>) => Promise<void>;\n /** Fetch one page of the server delta since `since`, from `cursor`. */\n pullPage: (since: string | null, cursor: string | null) => Promise<PullPage<TRemote>>;\n /**\n * Merge one pulled item into the local store. The app owns conflict\n * resolution here (e.g. last-write-wins, keeping newer local pending\n * edits, resolving tombstones and downloading blobs).\n */\n applyRemote: (item: TRemote) => Promise<void>;\n /** Watermark persistence, or `{ storageKey }` for a `localStorage` default. */\n watermark: WatermarkStore | { storageKey: string };\n /** Called after an entry is delivered and acked. */\n onEntryDelivered?: (entry: OutboxEntry<TPayload>) => void | Promise<void>;\n /** Called after an entry fails delivery (it stays queued). */\n onEntryFailed?: (entry: OutboxEntry<TPayload>, error: unknown) => void | Promise<void>;\n /**\n * Connectivity check. Default reads `navigator.onLine` (always online in\n * non-browser environments). When it returns `false`, `flush` is skipped.\n */\n isOnline?: () => boolean;\n /**\n * Broadcast {@link SyncState} across browser tabs of the same origin via a\n * `BroadcastChannel`, so every tab shows a coherent pending count / phase\n * (e.g. one tab flushing drops the badge to zero everywhere). The outbox is\n * already a shared IndexedDB; this only shares the in-memory state. Silently\n * ignored where `BroadcastChannel` is unavailable. Default `false`.\n *\n * When the Web Locks API is available, `flush` is additionally coordinated\n * *across* tabs: only one tab runs at a time and others skip while the lock\n * is held (they pick up the result via the broadcast). Delivery should still\n * be idempotent (upsert by client id). Without Web Locks, `flush` falls back\n * to per-tab single-flight.\n */\n crossTab?: boolean;\n /** Channel name when `crossTab` is on. Default `tempest-sync:${databaseName}`. */\n broadcastChannelName?: string;\n}\n\n/**\n * Offline-first sync engine: a durable outbox plus a paginated delta pull.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n */\nexport interface OfflineSync<TPayload> {\n /**\n * Queue a mutation. Returns the generated entry id.\n *\n * @param op - The mutation kind.\n * @param recordId - Primary key of the affected record.\n * @param payload - Record snapshot (for `create`/`update`).\n */\n enqueue: (op: OutboxOp, recordId: string, payload?: TPayload) => Promise<string>;\n /**\n * Run a full sync (drain the outbox, then pull the delta). Concurrent\n * calls share one in-flight promise, so triggers never overlap.\n *\n * @param trigger - Label for why the run happened. Default `\"manual\"`.\n */\n flush: (trigger?: SyncTrigger) => Promise<SyncRunSummary>;\n /** Number of mutations still queued. */\n pendingCount: () => Promise<number>;\n /** The queued mutations in FIFO order. */\n listPending: () => Promise<OutboxEntry<TPayload>[]>;\n /** Drop every queued mutation (e.g. on logout). */\n clearOutbox: () => Promise<void>;\n /** Reset the pull watermark (e.g. on logout / account switch). */\n resetWatermark: () => void;\n /** Read the current reactive {@link SyncState} snapshot synchronously. */\n getState: () => SyncState;\n /**\n * Subscribe to {@link SyncState} changes. The listener fires on every\n * enqueue, flush transition and outbox clear.\n *\n * @param listener - Called with the new snapshot on each change.\n * @returns An unsubscribe function.\n */\n subscribe: (listener: (state: SyncState) => void) => () => void;\n /**\n * Release resources held by the engine — currently the cross-tab\n * `BroadcastChannel` when `crossTab` is enabled. Safe to call when none was\n * opened. Optional in long-lived apps (the channel is reclaimed on tab\n * close); call it in tests and on teardown.\n */\n dispose: () => void;\n}\n\n/**\n * Build a `localStorage`-backed {@link WatermarkStore}. Reads/writes are no-ops\n * when `localStorage` is unavailable (SSR / non-browser).\n *\n * @param key - The `localStorage` key.\n * @returns A watermark store persisting to `localStorage`.\n */\nfunction localStorageWatermark(key: string): WatermarkStore {\n const available = typeof localStorage !== \"undefined\";\n return {\n get: () => (available ? localStorage.getItem(key) : null),\n set: (value: string) => {\n if (available) localStorage.setItem(key, value);\n },\n clear: () => {\n if (available) localStorage.removeItem(key);\n },\n };\n}\n\n/**\n * Create an offline-first sync engine over an IndexedDB outbox.\n *\n * The engine drains queued mutations to the server (`deliver`) and pulls the\n * server delta back (`pullPage` + `applyRemote`), advancing a watermark so each\n * run only fetches what changed. `flush` is single-flight and skips cleanly\n * while offline; failed deliveries stay queued with their attempt count bumped.\n *\n * Dexie is an **optional peer dependency** (via {@link createOfflineStore}) —\n * install it (`npm i dexie`) when you use this engine.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n * @typeParam TRemote - Server item shape returned by `pullPage`.\n * @param config - Transport callbacks + outbox/watermark configuration.\n * @returns The sync handle (`enqueue`, `flush`, `pendingCount`, …).\n *\n * @example\n * const sync = createOfflineSync<Note, NoteDto>({\n * databaseName: \"NotesOutbox\",\n * watermark: { storageKey: \"notes.watermark\" },\n * deliver: async (entry) => {\n * if (entry.op === \"delete\") return api.remove(entry.recordId);\n * await api.upsert(entry.recordId, entry.payload!);\n * },\n * pullPage: async (since, cursor) => {\n * const page = await api.changes(since, cursor);\n * return { items: page.items, nextCursor: page.next, serverTime: page.now };\n * },\n * applyRemote: async (dto) => {\n * if (dto.deleted) return localStore.remove(dto.id);\n * await localStore.save(fromDto(dto));\n * },\n * });\n * await sync.enqueue(\"create\", note.id, note);\n * await sync.flush(\"after-mutation\");\n */\nexport function createOfflineSync<TPayload = unknown, TRemote = unknown>(\n config: OfflineSyncConfig<TPayload, TRemote>,\n): OfflineSync<TPayload> {\n const outbox = createOfflineStore<OutboxEntry<TPayload>, string>({\n databaseName: config.databaseName,\n version: config.version ?? 1,\n tableName: config.tableName ?? \"outbox\",\n indexes: \"&id, recordId, enqueuedAt\",\n keyPath: \"id\",\n });\n\n const watermark: WatermarkStore =\n \"get\" in config.watermark\n ? config.watermark\n : localStorageWatermark(config.watermark.storageKey);\n\n const idPrefix = config.idPrefix ?? \"outbox\";\n const isOnline =\n config.isOnline ?? (() => (typeof navigator !== \"undefined\" ? navigator.onLine : true));\n\n let inflight: Promise<SyncRunSummary> | null = null;\n\n const listeners = new Set<(state: SyncState) => void>();\n let state: SyncState = {\n phase: \"idle\",\n pending: 0,\n lastSummary: null,\n lastError: null,\n lastSyncedAt: null,\n };\n\n const crossTab = config.crossTab === true;\n const channelName = config.broadcastChannelName ?? `tempest-sync:${config.databaseName}`;\n const channel: BroadcastChannel | null =\n crossTab && typeof BroadcastChannel !== \"undefined\"\n ? new BroadcastChannel(channelName)\n : null;\n let closed = false;\n\n function notify(): void {\n for (const listener of listeners) listener(state);\n }\n\n function setState(patch: Partial<SyncState>): void {\n state = { ...state, ...patch };\n notify();\n if (channel && !closed) channel.postMessage(state);\n }\n\n if (channel) {\n channel.onmessage = (event: MessageEvent<SyncState>) => {\n if (closed) return;\n state = event.data;\n notify();\n };\n }\n\n async function refreshPending(): Promise<void> {\n setState({ pending: await outbox.count() });\n }\n\n async function push(summary: SyncRunSummary): Promise<void> {\n const entries = await outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n for (const entry of entries) {\n try {\n await config.deliver(entry);\n await outbox.delete(entry.id);\n await config.onEntryDelivered?.(entry);\n summary.succeeded += 1;\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : \"delivery failed\";\n await outbox.update(entry.id, {\n attempts: entry.attempts + 1,\n lastError: message,\n } as Partial<OutboxEntry<TPayload>>);\n await config.onEntryFailed?.(entry, cause);\n summary.failed += 1;\n summary.lastError = message;\n }\n }\n }\n\n async function pull(): Promise<void> {\n const since = watermark.get();\n let cursor: string | null = null;\n let serverTime: string | null;\n do {\n const page = await config.pullPage(since, cursor);\n for (const item of page.items) {\n await config.applyRemote(item);\n }\n cursor = page.nextCursor;\n serverTime = page.serverTime;\n } while (cursor);\n if (serverTime) watermark.set(serverTime);\n }\n\n async function runOnce(trigger: SyncTrigger): Promise<SyncRunSummary> {\n const startedAt = Date.now();\n const summary: SyncRunSummary = {\n trigger,\n succeeded: 0,\n failed: 0,\n durationMs: 0,\n skipped: false,\n lastError: null,\n };\n if (!isOnline()) {\n summary.skipped = true;\n summary.durationMs = Date.now() - startedAt;\n return summary;\n }\n await push(summary);\n await pull();\n summary.durationMs = Date.now() - startedAt;\n return summary;\n }\n\n /**\n * Run one sync pass, serialized across tabs when possible.\n *\n * With `crossTab` on and the Web Locks API available, the pass is wrapped in\n * an `ifAvailable` lock request: whichever tab holds the lock runs, and the\n * others get `null` back instead of duplicating the work — their `SyncState`\n * catches up through the `BroadcastChannel`. The no-op summary keeps\n * `skipped: false` on purpose: `skipped` means \"device offline\" (it maps to\n * `phase: \"offline\"`), which is not what happened here. Falls back to a plain\n * per-tab run when `crossTab` is off or Web Locks is missing.\n *\n * @param trigger - What asked for this run, carried into the summary.\n * @returns The run summary, or an empty summary when another tab held the lock.\n */\n async function runGuarded(trigger: SyncTrigger): Promise<SyncRunSummary> {\n const locks = typeof navigator !== \"undefined\" ? navigator.locks : undefined;\n if (!crossTab || !locks) return runOnce(trigger);\n const result = await locks.request(\n `${channelName}:flush`,\n { ifAvailable: true },\n async (lock) => (lock ? runOnce(trigger) : null),\n );\n return (\n result ?? {\n trigger,\n succeeded: 0,\n failed: 0,\n durationMs: 0,\n skipped: false,\n lastError: null,\n }\n );\n }\n\n void refreshPending();\n\n let lastEnqueuedAt = 0;\n\n /**\n * Timestamp for a new outbox entry, guaranteed to be strictly greater than\n * the previous one.\n *\n * `enqueuedAt` is the sort key for both `listPending()` and the delivery loop\n * in `flush()`. A plain `Date.now()` ties whenever two mutations are queued\n * within the same millisecond — which is normal in a burst — and a tie leaves\n * the order to the index, so a `create` could be delivered *after* the\n * `update` that depends on it. Advancing by 1ms on a tie keeps the queue FIFO\n * at the cost of a timestamp that can run a few milliseconds ahead of the wall\n * clock during a burst.\n *\n * Scope: this is per engine instance. Two tabs enqueueing in the same\n * millisecond can still tie; cross-tab FIFO would need a persisted sequence,\n * and the delivery loop is already single-flight across tabs via Web Locks.\n */\n function nextEnqueuedAt(): number {\n const now = Date.now();\n lastEnqueuedAt = now > lastEnqueuedAt ? now : lastEnqueuedAt + 1;\n return lastEnqueuedAt;\n }\n\n return {\n async enqueue(op, recordId, payload) {\n const entry: OutboxEntry<TPayload> = {\n id: randomId(idPrefix),\n op,\n recordId,\n enqueuedAt: nextEnqueuedAt(),\n attempts: 0,\n payload,\n };\n await outbox.put(entry);\n await refreshPending();\n return entry.id;\n },\n flush(trigger: SyncTrigger = \"manual\") {\n if (!inflight) {\n setState({ phase: \"syncing\" });\n inflight = runGuarded(trigger)\n .then(async (summary) => {\n await refreshPending();\n setState({\n phase: summary.skipped\n ? \"offline\"\n : summary.failed > 0\n ? \"error\"\n : \"idle\",\n lastSummary: summary,\n lastError: summary.lastError,\n lastSyncedAt: summary.skipped ? state.lastSyncedAt : Date.now(),\n });\n return summary;\n })\n .finally(() => {\n inflight = null;\n });\n }\n return inflight;\n },\n pendingCount() {\n return outbox.count();\n },\n listPending() {\n return outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n },\n async clearOutbox() {\n await outbox.clear();\n await refreshPending();\n },\n resetWatermark() {\n watermark.clear();\n },\n getState() {\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n closed = true;\n channel?.close();\n },\n };\n}\n"],"mappings":";;;AAgPA,SAAS,EAAsB,GAA6B;CACxD,IAAM,IAAY,OAAO,eAAiB;CAC1C,OAAO;EACH,WAAY,IAAY,aAAa,QAAQ,CAAG,IAAI;EACpD,MAAM,MAAkB;GACpB,AAAI,KAAW,aAAa,QAAQ,GAAK,CAAK;EAClD;EACA,aAAa;GACT,AAAI,KAAW,aAAa,WAAW,CAAG;EAC9C;CACJ;AACJ;AAsCA,SA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