tempest-react-sdk 0.80.0 → 0.82.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 (247) hide show
  1. package/README.md +40 -10
  2. package/bin/create-tempest-app.e2e.test.mjs +31 -0
  3. package/bin/create-tempest-app.mjs +11 -1
  4. package/bin/lib/component/generate.test.mjs +13 -1
  5. package/bin/lib/doctor/doctor.e2e.test.mjs +29 -0
  6. package/bin/lib/doctor/vitest.mjs +120 -0
  7. package/bin/lib/doctor/vitest.test.mjs +139 -0
  8. package/bin/lib/fs/contain.mjs +7 -0
  9. package/bin/lib/openapi/escape.mjs +68 -4
  10. package/bin/lib/openapi/generate.hostile.test.mjs +150 -1
  11. package/bin/lib/openapi/generate.mjs +78 -13
  12. package/bin/lib/openapi/generate.test.mjs +13 -1
  13. package/bin/lib/openapi/pattern-risk.mjs +134 -0
  14. package/bin/lib/openapi/pattern-risk.test.mjs +45 -0
  15. package/bin/tempest-gen.test.mjs +100 -0
  16. package/bin/tempest.mjs +24 -8
  17. package/dist/access/use-can.cjs +1 -1
  18. package/dist/access/use-can.cjs.map +1 -1
  19. package/dist/access/use-can.js +25 -28
  20. package/dist/access/use-can.js.map +1 -1
  21. package/dist/auth/create-tempest-auth.cjs +1 -1
  22. package/dist/auth/create-tempest-auth.cjs.map +1 -1
  23. package/dist/auth/create-tempest-auth.js +234 -122
  24. package/dist/auth/create-tempest-auth.js.map +1 -1
  25. package/dist/auth/session-identity.cjs +2 -0
  26. package/dist/auth/session-identity.cjs.map +1 -0
  27. package/dist/auth/session-identity.js +12 -0
  28. package/dist/auth/session-identity.js.map +1 -0
  29. package/dist/br/boleto.cjs +1 -1
  30. package/dist/br/boleto.cjs.map +1 -1
  31. package/dist/br/boleto.js +2 -1
  32. package/dist/br/boleto.js.map +1 -1
  33. package/dist/br.d.ts +22 -3
  34. package/dist/components/AuthForm/AuthFieldControl.cjs +2 -0
  35. package/dist/components/AuthForm/AuthFieldControl.cjs.map +1 -0
  36. package/dist/components/AuthForm/AuthFieldControl.js +85 -0
  37. package/dist/components/AuthForm/AuthFieldControl.js.map +1 -0
  38. package/dist/components/AuthForm/AuthForm.cjs +2 -0
  39. package/dist/components/AuthForm/AuthForm.cjs.map +1 -0
  40. package/dist/components/AuthForm/AuthForm.js +83 -0
  41. package/dist/components/AuthForm/AuthForm.js.map +1 -0
  42. package/dist/components/AuthForm/AuthForm.module.cjs +3 -0
  43. package/dist/components/AuthForm/AuthForm.module.cjs.map +1 -0
  44. package/dist/components/AuthForm/AuthForm.module.js +14 -0
  45. package/dist/components/AuthForm/AuthForm.module.js.map +1 -0
  46. package/dist/components/AuthForm/AuthLinks.cjs +2 -0
  47. package/dist/components/AuthForm/AuthLinks.cjs.map +1 -0
  48. package/dist/components/AuthForm/AuthLinks.js +32 -0
  49. package/dist/components/AuthForm/AuthLinks.js.map +1 -0
  50. package/dist/components/AuthForm/ForgotPasswordForm.cjs +2 -0
  51. package/dist/components/AuthForm/ForgotPasswordForm.cjs.map +1 -0
  52. package/dist/components/AuthForm/ForgotPasswordForm.js +32 -0
  53. package/dist/components/AuthForm/ForgotPasswordForm.js.map +1 -0
  54. package/dist/components/AuthForm/LoginForm.cjs +2 -0
  55. package/dist/components/AuthForm/LoginForm.cjs.map +1 -0
  56. package/dist/components/AuthForm/LoginForm.js +39 -0
  57. package/dist/components/AuthForm/LoginForm.js.map +1 -0
  58. package/dist/components/AuthForm/ResetPasswordForm.cjs +2 -0
  59. package/dist/components/AuthForm/ResetPasswordForm.cjs.map +1 -0
  60. package/dist/components/AuthForm/ResetPasswordForm.js +39 -0
  61. package/dist/components/AuthForm/ResetPasswordForm.js.map +1 -0
  62. package/dist/components/AuthForm/SignUpForm.cjs +2 -0
  63. package/dist/components/AuthForm/SignUpForm.cjs.map +1 -0
  64. package/dist/components/AuthForm/SignUpForm.js +32 -0
  65. package/dist/components/AuthForm/SignUpForm.js.map +1 -0
  66. package/dist/components/AuthForm/auth-defaults.cjs +2 -0
  67. package/dist/components/AuthForm/auth-defaults.cjs.map +1 -0
  68. package/dist/components/AuthForm/auth-defaults.js +54 -0
  69. package/dist/components/AuthForm/auth-defaults.js.map +1 -0
  70. package/dist/components/AuthForm/auth-schemas.cjs +2 -0
  71. package/dist/components/AuthForm/auth-schemas.cjs.map +1 -0
  72. package/dist/components/AuthForm/auth-schemas.js +26 -0
  73. package/dist/components/AuthForm/auth-schemas.js.map +1 -0
  74. package/dist/components/AuthPage/AuthPage.cjs +2 -0
  75. package/dist/components/AuthPage/AuthPage.cjs.map +1 -0
  76. package/dist/components/AuthPage/AuthPage.js +97 -0
  77. package/dist/components/AuthPage/AuthPage.js.map +1 -0
  78. package/dist/components/AuthPage/AuthPage.module.cjs +3 -0
  79. package/dist/components/AuthPage/AuthPage.module.cjs.map +1 -0
  80. package/dist/components/AuthPage/AuthPage.module.js +24 -0
  81. package/dist/components/AuthPage/AuthPage.module.js.map +1 -0
  82. package/dist/components/Breadcrumbs/Breadcrumbs.cjs +1 -1
  83. package/dist/components/Breadcrumbs/Breadcrumbs.cjs.map +1 -1
  84. package/dist/components/Breadcrumbs/Breadcrumbs.js +22 -21
  85. package/dist/components/Breadcrumbs/Breadcrumbs.js.map +1 -1
  86. package/dist/components/Button/Button.cjs +1 -1
  87. package/dist/components/Button/Button.cjs.map +1 -1
  88. package/dist/components/Button/Button.js +41 -40
  89. package/dist/components/Button/Button.js.map +1 -1
  90. package/dist/components/Chat/ChatAttachments.cjs +1 -1
  91. package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
  92. package/dist/components/Chat/ChatAttachments.js +38 -38
  93. package/dist/components/FilterBar/filter-apply.cjs +1 -1
  94. package/dist/components/FilterBar/filter-apply.cjs.map +1 -1
  95. package/dist/components/FilterBar/filter-apply.js +7 -7
  96. package/dist/components/Form/Form.cjs +1 -1
  97. package/dist/components/Form/Form.cjs.map +1 -1
  98. package/dist/components/Form/Form.js +30 -32
  99. package/dist/components/Form/Form.js.map +1 -1
  100. package/dist/components/Layout/Layout.cjs +1 -1
  101. package/dist/components/Layout/Layout.cjs.map +1 -1
  102. package/dist/components/Layout/Layout.js +25 -24
  103. package/dist/components/Layout/Layout.js.map +1 -1
  104. package/dist/components/Layout/gap.cjs +2 -0
  105. package/dist/components/Layout/gap.cjs.map +1 -0
  106. package/dist/components/Layout/gap.js +15 -0
  107. package/dist/components/Layout/gap.js.map +1 -0
  108. package/dist/components/NavigationMenu/NavigationMenu.cjs +1 -1
  109. package/dist/components/NavigationMenu/NavigationMenu.cjs.map +1 -1
  110. package/dist/components/NavigationMenu/NavigationMenu.js +71 -70
  111. package/dist/components/NavigationMenu/NavigationMenu.js.map +1 -1
  112. package/dist/components/Sidebar/Sidebar.cjs.map +1 -1
  113. package/dist/components/Sidebar/Sidebar.js.map +1 -1
  114. package/dist/components/Sidebar/SidebarEntry.cjs +1 -1
  115. package/dist/components/Sidebar/SidebarEntry.cjs.map +1 -1
  116. package/dist/components/Sidebar/SidebarEntry.js +30 -29
  117. package/dist/components/Sidebar/SidebarEntry.js.map +1 -1
  118. package/dist/data/create-data-provider.cjs +1 -1
  119. package/dist/data/create-data-provider.cjs.map +1 -1
  120. package/dist/data/create-data-provider.js +1 -2
  121. package/dist/data/create-data-provider.js.map +1 -1
  122. package/dist/forms/index.js +7 -7
  123. package/dist/forms/masked-inputs.cjs +1 -1
  124. package/dist/forms/masked-inputs.cjs.map +1 -1
  125. package/dist/forms/masked-inputs.js +15 -15
  126. package/dist/forms/validate-form.cjs +1 -1
  127. package/dist/forms/validate-form.cjs.map +1 -1
  128. package/dist/forms/validate-form.js +6 -1
  129. package/dist/forms/validate-form.js.map +1 -1
  130. package/dist/forms/zod-resolver.cjs +1 -1
  131. package/dist/forms/zod-resolver.cjs.map +1 -1
  132. package/dist/forms/zod-resolver.js +8 -3
  133. package/dist/forms/zod-resolver.js.map +1 -1
  134. package/dist/http/api-client.cjs +1 -1
  135. package/dist/http/api-client.cjs.map +1 -1
  136. package/dist/http/api-client.js +137 -116
  137. package/dist/http/api-client.js.map +1 -1
  138. package/dist/http/credential-scope.cjs +1 -1
  139. package/dist/http/credential-scope.cjs.map +1 -1
  140. package/dist/http/credential-scope.js +33 -9
  141. package/dist/http/credential-scope.js.map +1 -1
  142. package/dist/http/presigned-post.cjs.map +1 -1
  143. package/dist/http/presigned-post.js.map +1 -1
  144. package/dist/http/resumable-upload.cjs +1 -1
  145. package/dist/http/resumable-upload.cjs.map +1 -1
  146. package/dist/http/resumable-upload.js +140 -134
  147. package/dist/http/resumable-upload.js.map +1 -1
  148. package/dist/http/upload-with-progress.cjs +1 -1
  149. package/dist/http/upload-with-progress.cjs.map +1 -1
  150. package/dist/http/upload-with-progress.js +17 -17
  151. package/dist/http/upload-with-progress.js.map +1 -1
  152. package/dist/http/use-describe-api-error.cjs +1 -1
  153. package/dist/http/use-describe-api-error.cjs.map +1 -1
  154. package/dist/http/use-describe-api-error.js +9 -9
  155. package/dist/oauth/GoogleSignIn.cjs +1 -1
  156. package/dist/oauth/GoogleSignIn.cjs.map +1 -1
  157. package/dist/oauth/GoogleSignIn.js +5 -4
  158. package/dist/oauth/GoogleSignIn.js.map +1 -1
  159. package/dist/offline/create-offline-sync.cjs +1 -1
  160. package/dist/offline/create-offline-sync.cjs.map +1 -1
  161. package/dist/offline/create-offline-sync.js +108 -68
  162. package/dist/offline/create-offline-sync.js.map +1 -1
  163. package/dist/query/offline-persistence.cjs +1 -1
  164. package/dist/query/offline-persistence.cjs.map +1 -1
  165. package/dist/query/offline-persistence.js +54 -44
  166. package/dist/query/offline-persistence.js.map +1 -1
  167. package/dist/sse/create-event-stream.cjs +1 -1
  168. package/dist/sse/create-event-stream.cjs.map +1 -1
  169. package/dist/sse/create-event-stream.js +48 -41
  170. package/dist/sse/create-event-stream.js.map +1 -1
  171. package/dist/sse/ticket-event-stream.cjs +1 -1
  172. package/dist/sse/ticket-event-stream.cjs.map +1 -1
  173. package/dist/sse/ticket-event-stream.js +48 -19
  174. package/dist/sse/ticket-event-stream.js.map +1 -1
  175. package/dist/sse/use-event-stream.cjs +1 -1
  176. package/dist/sse/use-event-stream.cjs.map +1 -1
  177. package/dist/sse/use-event-stream.js +19 -14
  178. package/dist/sse/use-event-stream.js.map +1 -1
  179. package/dist/styles/AuthForm.css +2 -0
  180. package/dist/styles/AuthPage.css +2 -0
  181. package/dist/styles/component/AuthForm.css +9 -0
  182. package/dist/styles/component/AuthPage.css +29 -0
  183. package/dist/styles/forms.css +36 -0
  184. package/dist/styles/manifest.json +63 -0
  185. package/dist/styles.css +1 -1
  186. package/dist/sw/background-sync.cjs +1 -1
  187. package/dist/sw/background-sync.cjs.map +1 -1
  188. package/dist/sw/background-sync.js +132 -112
  189. package/dist/sw/background-sync.js.map +1 -1
  190. package/dist/sw/cache.cjs +1 -1
  191. package/dist/sw/cache.cjs.map +1 -1
  192. package/dist/sw/cache.js +36 -30
  193. package/dist/sw/cache.js.map +1 -1
  194. package/dist/sw/create-push-handler.cjs +1 -1
  195. package/dist/sw/create-push-handler.cjs.map +1 -1
  196. package/dist/sw/create-push-handler.js +20 -10
  197. package/dist/sw/create-push-handler.js.map +1 -1
  198. package/dist/sw.d.ts +93 -28
  199. package/dist/tabular/compact.cjs +1 -1
  200. package/dist/tabular/compact.cjs.map +1 -1
  201. package/dist/tabular/compact.js +35 -16
  202. package/dist/tabular/compact.js.map +1 -1
  203. package/dist/tabular/manifest.cjs +1 -1
  204. package/dist/tabular/manifest.cjs.map +1 -1
  205. package/dist/tabular/manifest.js +33 -15
  206. package/dist/tabular/manifest.js.map +1 -1
  207. package/dist/tabular.d.ts +11 -1
  208. package/dist/tempest-react-sdk.cjs +1 -1
  209. package/dist/tempest-react-sdk.d.ts +1057 -83
  210. package/dist/tempest-react-sdk.js +373 -365
  211. package/dist/theme/initial-theme.cjs +4 -4
  212. package/dist/theme/initial-theme.cjs.map +1 -1
  213. package/dist/theme/initial-theme.js +8 -5
  214. package/dist/theme/initial-theme.js.map +1 -1
  215. package/dist/utils/compressed-storage.cjs +1 -1
  216. package/dist/utils/compressed-storage.cjs.map +1 -1
  217. package/dist/utils/compressed-storage.js +13 -7
  218. package/dist/utils/compressed-storage.js.map +1 -1
  219. package/dist/utils/format.cjs +1 -1
  220. package/dist/utils/format.cjs.map +1 -1
  221. package/dist/utils/format.js +25 -25
  222. package/dist/utils/numbers.cjs +1 -1
  223. package/dist/utils/numbers.cjs.map +1 -1
  224. package/dist/utils/numbers.js +7 -7
  225. package/dist/utils/objects.cjs +1 -1
  226. package/dist/utils/objects.cjs.map +1 -1
  227. package/dist/utils/objects.js +13 -7
  228. package/dist/utils/objects.js.map +1 -1
  229. package/dist/utils/safe-url.cjs +1 -1
  230. package/dist/utils/safe-url.cjs.map +1 -1
  231. package/dist/utils/safe-url.js +4 -1
  232. package/dist/utils/safe-url.js.map +1 -1
  233. package/dist/webrtc/peer-mesh.cjs +1 -1
  234. package/dist/webrtc/peer-mesh.cjs.map +1 -1
  235. package/dist/webrtc/peer-mesh.js +7 -1
  236. package/dist/webrtc/peer-mesh.js.map +1 -1
  237. package/dist/ws/create-web-socket.cjs +1 -1
  238. package/dist/ws/create-web-socket.cjs.map +1 -1
  239. package/dist/ws/create-web-socket.js +77 -61
  240. package/dist/ws/create-web-socket.js.map +1 -1
  241. package/dist/ws/use-web-socket.cjs +1 -1
  242. package/dist/ws/use-web-socket.cjs.map +1 -1
  243. package/dist/ws/use-web-socket.js +4 -3
  244. package/dist/ws/use-web-socket.js.map +1 -1
  245. package/package.json +1 -1
  246. package/template-pwa/src/pwa.tsx +42 -0
  247. package/template-pwa/src/sw.ts +15 -10
@@ -1 +1 @@
1
- {"version":3,"file":"GoogleSignIn.js","names":["GoogleSignIn","Component","response","onSuccess","disableOneTap"],"sources":["../../src/oauth/GoogleSignIn.tsx"],"sourcesContent":["/**\n * @tempest-limits props-count — component, theme, text, shape, size and width are\n * Google's own button parameters, passed through with their names intact so the\n * reader can match them to Google's documentation;\n * onSuccess/onError/locale/disableOneTap are the wrapper's.\n */\nimport type { CSSProperties, ReactNode } from \"react\";\nimport type { OAuthCredential, OAuthError } from \"./types\";\n\nexport type GoogleSignInTheme = \"filled_blue\" | \"filled_black\" | \"outline\";\nexport type GoogleSignInText = \"signin_with\" | \"signup_with\" | \"continue_with\" | \"signin\";\nexport type GoogleSignInShape = \"rectangular\" | \"pill\" | \"circle\" | \"square\";\nexport type GoogleSignInSize = \"large\" | \"medium\" | \"small\";\n\nexport interface GoogleSignInProps {\n /**\n * `GoogleLogin` component from `@react-oauth/google`. The caller imports\n * it and passes it through so the SDK doesn't take `@react-oauth/google`\n * as a peer dep.\n */\n component: (props: Record<string, unknown>) => ReactNode;\n /** Fired with the validated credential on success. */\n onSuccess: (credential: OAuthCredential) => void | Promise<void>;\n /** Fired with a normalised error on failure. */\n onError?: (error: OAuthError) => void;\n /** Optional locale override (e.g. `\"pt-BR\"`). Falls back to browser locale. */\n locale?: string;\n /** Visual theme — passed through to `<GoogleLogin>`. */\n theme?: GoogleSignInTheme;\n /** Button text variant. */\n text?: GoogleSignInText;\n /** Button shape. */\n shape?: GoogleSignInShape;\n /** Button size. */\n size?: GoogleSignInSize;\n /** Disable Google's \"One Tap\" auto-prompt. Default `false`. */\n disableOneTap?: boolean;\n /** Optional `width` override (px) — Google's button is fixed-width. */\n width?: number;\n /** Optional className applied to the wrapper. */\n className?: string;\n /** Optional inline style applied to the wrapper. */\n style?: CSSProperties;\n}\n\n/**\n * Thin wrapper over `@react-oauth/google`'s `<GoogleLogin>` that:\n *\n * 1. Normalises the success payload into [[OAuthCredential]] (`idToken`,\n * `provider: \"google\"`, `raw`).\n * 2. Normalises errors into [[OAuthError]].\n * 3. Lets you pass `GoogleLogin` via the `component` prop, so the SDK does\n * not declare `@react-oauth/google` as a peer dep — apps that don't use\n * Google never pay for it.\n *\n * @example\n * import { GoogleLogin, GoogleOAuthProvider } from \"@react-oauth/google\";\n * import { GoogleSignIn } from \"tempest-react-sdk\";\n *\n * <GoogleOAuthProvider clientId={import.meta.env.VITE_GOOGLE_CLIENT_ID}>\n * <GoogleSignIn\n * component={GoogleLogin}\n * onSuccess={async ({ idToken }) => {\n * await api.post(\"/auth/google\", { body: { id_token: idToken } });\n * }}\n * onError={(err) => toast.error(err.message)}\n * />\n * </GoogleOAuthProvider>\n */\nexport function GoogleSignIn({\n component: Component,\n onSuccess,\n onError,\n locale,\n theme,\n text,\n shape,\n size,\n disableOneTap,\n width,\n className,\n style,\n}: GoogleSignInProps) {\n return (\n <div className={className} style={style}>\n {Component({\n onSuccess: (response: { credential?: string }) => {\n if (!response.credential) {\n onError?.({\n provider: \"google\",\n message: \"Google returned no credential\",\n raw: response,\n });\n return;\n }\n return onSuccess({\n idToken: response.credential,\n provider: \"google\",\n raw: response,\n });\n },\n onError: () => {\n onError?.({\n provider: \"google\",\n message: \"Google login failed\",\n });\n },\n locale,\n theme,\n text,\n shape,\n size,\n useOneTap: !disableOneTap,\n width,\n })}\n </div>\n );\n}\n"],"mappings":";;AAqEA,SAAgBA,EAAa,EACzB,WAAWC,GACX,cACA,YACA,WACA,UACA,SACA,UACA,SACA,kBACA,UACA,cACA,YACkB;CAClB,OACI,kBAAC,OAAD;EAAgB;EAAkB;EAC7B,UAAAA,EAAU;GACP,YAAY,MAAsC;IAC9C,IAAI,CAACC,EAAS,YACV,IAAU;KACN,UAAU;KACV,SAAS;KACT,KAAKA;IACT,CAAC;SAGL,OAAOC,EAAU;KACb,SAASD,EAAS;KAClB,UAAU;KACV,KAAKA;IACT,CAAC;GACL;GACA,eAAe;IACX,IAAU;KACN,UAAU;KACV,SAAS;IACb,CAAC;GACL;GACA;GACA;GACA;GACA;GACA;GACA,WAAW,CAACE;GACZ;EACJ,CAAC;CACA,CAAA;AAEb"}
1
+ {"version":3,"file":"GoogleSignIn.js","names":["GoogleSignIn","Component","response","onSuccess","disableOneTap"],"sources":["../../src/oauth/GoogleSignIn.tsx"],"sourcesContent":["/**\n * @tempest-limits props-count — component, theme, text, shape, size and width are\n * Google's own button parameters, and nonce Google's ID-token parameter, passed\n * through with their names intact so the reader can match them to Google's\n * documentation; onSuccess/onError/locale/disableOneTap are the wrapper's.\n */\nimport type { CSSProperties, ReactNode } from \"react\";\nimport type { OAuthCredential, OAuthError } from \"./types\";\n\nexport type GoogleSignInTheme = \"filled_blue\" | \"filled_black\" | \"outline\";\nexport type GoogleSignInText = \"signin_with\" | \"signup_with\" | \"continue_with\" | \"signin\";\nexport type GoogleSignInShape = \"rectangular\" | \"pill\" | \"circle\" | \"square\";\nexport type GoogleSignInSize = \"large\" | \"medium\" | \"small\";\n\nexport interface GoogleSignInProps {\n /**\n * `GoogleLogin` component from `@react-oauth/google`. The caller imports\n * it and passes it through so the SDK doesn't take `@react-oauth/google`\n * as a peer dep.\n */\n component: (props: Record<string, unknown>) => ReactNode;\n /** Fired with the validated credential on success. */\n onSuccess: (credential: OAuthCredential) => void | Promise<void>;\n /** Fired with a normalised error on failure. */\n onError?: (error: OAuthError) => void;\n /** Optional locale override (e.g. `\"pt-BR\"`). Falls back to browser locale. */\n locale?: string;\n /** Visual theme — passed through to `<GoogleLogin>`. */\n theme?: GoogleSignInTheme;\n /** Button text variant. */\n text?: GoogleSignInText;\n /** Button shape. */\n shape?: GoogleSignInShape;\n /** Button size. */\n size?: GoogleSignInSize;\n /** Disable Google's \"One Tap\" auto-prompt. Default `false`. */\n disableOneTap?: boolean;\n /** Optional `width` override (px) — Google's button is fixed-width. */\n width?: number;\n /**\n * Server-issued nonce Google copies into the ID token's `nonce` claim.\n *\n * The backend issues one per sign-in attempt, keeps it, and rejects an\n * `id_token` whose claim does not match — which is what stops a token\n * captured elsewhere from being replayed against your API. Until 0.82.0\n * the wrapper dropped it, so an app could not bind the token through\n * `<GoogleSignIn>` at all (#530).\n */\n nonce?: string;\n /** Optional className applied to the wrapper. */\n className?: string;\n /** Optional inline style applied to the wrapper. */\n style?: CSSProperties;\n}\n\n/**\n * Thin wrapper over `@react-oauth/google`'s `<GoogleLogin>` that:\n *\n * 1. Normalises the success payload into [[OAuthCredential]] (`idToken`,\n * `provider: \"google\"`, `raw`).\n * 2. Normalises errors into [[OAuthError]].\n * 3. Lets you pass `GoogleLogin` via the `component` prop, so the SDK does\n * not declare `@react-oauth/google` as a peer dep — apps that don't use\n * Google never pay for it.\n *\n * @example\n * import { GoogleLogin, GoogleOAuthProvider } from \"@react-oauth/google\";\n * import { GoogleSignIn } from \"tempest-react-sdk\";\n *\n * <GoogleOAuthProvider clientId={import.meta.env.VITE_GOOGLE_CLIENT_ID}>\n * <GoogleSignIn\n * component={GoogleLogin}\n * onSuccess={async ({ idToken }) => {\n * await api.post(\"/auth/google\", { body: { id_token: idToken } });\n * }}\n * onError={(err) => toast.error(err.message)}\n * />\n * </GoogleOAuthProvider>\n */\nexport function GoogleSignIn({\n component: Component,\n onSuccess,\n onError,\n locale,\n theme,\n text,\n shape,\n size,\n disableOneTap,\n width,\n nonce,\n className,\n style,\n}: GoogleSignInProps) {\n return (\n <div className={className} style={style}>\n {Component({\n onSuccess: (response: { credential?: string }) => {\n if (!response.credential) {\n onError?.({\n provider: \"google\",\n message: \"Google returned no credential\",\n raw: response,\n });\n return;\n }\n return onSuccess({\n idToken: response.credential,\n provider: \"google\",\n raw: response,\n });\n },\n onError: () => {\n onError?.({\n provider: \"google\",\n message: \"Google login failed\",\n });\n },\n locale,\n theme,\n text,\n shape,\n size,\n useOneTap: !disableOneTap,\n width,\n nonce,\n })}\n </div>\n );\n}\n"],"mappings":";;AA+EA,SAAgBA,EAAa,EACzB,WAAWC,GACX,cACA,YACA,WACA,UACA,SACA,UACA,SACA,kBACA,UACA,UACA,cACA,YACkB;CAClB,OACI,kBAAC,OAAD;EAAgB;EAAkB;EAC7B,UAAAA,EAAU;GACP,YAAY,MAAsC;IAC9C,IAAI,CAACC,EAAS,YACV,IAAU;KACN,UAAU;KACV,SAAS;KACT,KAAKA;IACT,CAAC;SAGL,OAAOC,EAAU;KACb,SAASD,EAAS;KAClB,UAAU;KACV,KAAKA;IACT,CAAC;GACL;GACA,eAAe;IACX,IAAU;KACN,UAAU;KACV,SAAS;IACb,CAAC;GACL;GACA;GACA;GACA;GACA;GACA;GACA,WAAW,CAACE;GACZ;GACA;EACJ,CAAC;CACA,CAAA;AAEb"}
@@ -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`}),n=new Set;for(let a of t)if(n.has(a.recordId))e.deferred+=1;else try{await r.deliver(a),await i.delete(a.id),await r.onEntryDelivered?.(a),e.succeeded+=1}catch(t){let o=t instanceof Error?t.message:`delivery failed`;await i.update(a.id,{attempts:a.attempts+1,lastError:o}),await r.onEntryFailed?.(a,t),n.add(a.recordId),e.failed+=1,e.lastError=o}}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,deferred: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,deferred: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;
1
+ const e=require("../utils/ids.cjs"),t=require("../utils/owner-fingerprint.cjs"),n=require("./create-offline-store.cjs");function r(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 i(i){let a=n.createOfflineStore({databaseName:i.databaseName,version:i.version??1,tableName:i.tableName??`outbox`,indexes:`&id, recordId, enqueuedAt`,keyPath:`id`}),o=`get`in i.watermark?i.watermark:r(i.watermark.storageKey),s=i.idPrefix??`outbox`,c=i.isOnline??(()=>typeof navigator<`u`?navigator.onLine:!0),{getPrincipal:l}=i;function u(e){try{return t.ownerFingerprint(`p`,e())}catch{return null}}function d(e){if(!l||e.owner===void 0)return`deliver`;let t=u(l);return t===e.owner?`deliver`:t===null?`hold`:`drop`}let f=null,p=0,m=new Set,h={phase:`idle`,pending:0,lastSummary:null,lastError:null,lastSyncedAt:null},g=i.crossTab===!0,_=i.broadcastChannelName??`tempest-sync:${i.databaseName}`,v=g&&typeof BroadcastChannel<`u`?new BroadcastChannel(_):null,y=!1;function b(){for(let e of m)e(h)}function x(e){h={...h,...e},b(),v&&!y&&v.postMessage(h)}v&&(v.onmessage=e=>{y||(h=e.data,b())});async function S(){x({pending:await a.count()})}function C(){p+=1,f&&(f=null,x({phase:`idle`}))}async function w(e,t){let n=await a.list(void 0,{orderBy:`enqueuedAt`}),r=new Set;for(let o of n){if(r.has(o.recordId)){e.deferred+=1;continue}let n=await a.get(o.id);if(p!==t)return!1;if(!n)continue;let s=d(o);if(s===`hold`)e.held=(e.held??0)+1;else if(s===`drop`)await a.delete(o.id),e.dropped=(e.dropped??0)+1;else try{if(await i.deliver(o),await a.delete(o.id),e.succeeded+=1,p!==t)return!1;await i.onEntryDelivered?.(o)}catch(n){let s=n instanceof Error?n.message:`delivery failed`;if(await a.update(o.id,{attempts:o.attempts+1,lastError:s}),r.add(o.recordId),e.failed+=1,e.lastError=s,p!==t)return!1;await i.onEntryFailed?.(o,n)}}return p===t}async function T(e){let t=o.get(),n=null,r;do{let a=await i.pullPage(t,n);for(let t of a.items){if(p!==e)return!1;await i.applyRemote(t)}if(p!==e)return!1;n=a.nextCursor,r=a.serverTime}while(n);return r&&o.set(r),!0}async function E(e,t){let n=Date.now(),r={trigger:e,succeeded:0,failed:0,deferred:0,durationMs:0,skipped:!1,lastError:null};return c()?(await w(r,t)&&await T(t)||(r.interrupted=!0),r.durationMs=Date.now()-n,r):(r.skipped=!0,r.durationMs=Date.now()-n,r)}async function D(e,t){let n=typeof navigator<`u`?navigator.locks:void 0;return!g||!n?E(e,t):await n.request(`${_}:flush`,{ifAvailable:!0},async n=>n?E(e,t):null)??{trigger:e,succeeded:0,failed:0,deferred:0,durationMs:0,skipped:!1,lastError:null}}S();let O=0;function k(){let e=Date.now();return O=e>O?e:O+1,O}return{async enqueue(t,n,r){let i={id:e.randomId(s),op:t,recordId:n,enqueuedAt:k(),attempts:0,payload:r};return l&&(i.owner=u(l)),await a.put(i),await S(),i.id},flush(e=`manual`){if(!f){x({phase:`syncing`});let t=p,n=D(e,t).then(async e=>(await S(),p===t&&x({phase:e.skipped?`offline`:e.failed>0?`error`:`idle`,lastSummary:e,lastError:e.lastError,lastSyncedAt:e.skipped?h.lastSyncedAt:Date.now()}),e)).finally(()=>{f===n&&(f=null)});f=n}return f},pendingCount(){return a.count()},listPending(){return a.list(void 0,{orderBy:`enqueuedAt`})},async clearOutbox(){C(),await a.clear(),await S()},resetWatermark(){C(),o.clear()},getState(){return h},subscribe(e){return m.add(e),()=>{m.delete(e)}},dispose(){y=!0,v?.close()}}}exports.createOfflineSync=i;
2
2
  //# sourceMappingURL=create-offline-sync.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-offline-sync.cjs","names":["createOfflineStore","randomId","require_ids","require_create_offline_store","localStorageWatermark","available","key","value","createOfflineSync","outbox","config","watermark","idPrefix","isOnline","inflight","listeners","state","crossTab","channelName","channel","closed","notify","listener","setState","patch","event","refreshPending","push","entries","blocked","entry","cause","message","pull","since","cursor","serverTime","page","item","runOnce","startedAt","summary","runGuarded","locks","trigger","lock","lastEnqueuedAt","nextEnqueuedAt","now"],"sources":["../../src/offline/create-offline-sync.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — outbox drain, pull-with-watermark,\n * conflict resolution and the single-flight guard are one loop by necessity: a pull\n * that lands mid-drain must not advance the watermark past records the outbox has\n * not pushed yet. Splitting the phases hands that ordering to whoever calls them in\n * the right sequence.\n */\nimport { 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 /**\n * Entries left untried because an earlier entry for the **same record**\n * failed this run.\n *\n * They stay queued and are attempted next run, in order. Counted apart from\n * `failed` because they were never sent: reporting them as failures would\n * blame the server for a decision this engine made, and folding them in would\n * make `succeeded + failed` stop accounting for the queue.\n */\n deferred: 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 /**\n * Drain the outbox in `enqueuedAt` order, one record at a time.\n *\n * Once an entry for a record fails, the remaining entries **for that record**\n * are left untried this run. `enqueuedAt` is a FIFO guarantee the engine goes\n * out of its way to keep (see `nextEnqueuedAt`), precisely because delivering\n * an `update` before the `create` it depends on is wrong — and continuing past\n * a failure broke exactly that guarantee. With a `PUT` upsert `deliver`, which\n * is the usual shape, the server would create the record from the *update*\n * payload and the retried `create` would then overwrite it with the older\n * snapshot: the user's edit disappears with nothing reported.\n *\n * Skipping is per record, not per run. Records are independent, so a record\n * the server is rejecting must not hold up every other pending change.\n *\n * @param summary - Mutated with the per-entry outcome counts.\n */\n async function push(summary: SyncRunSummary): Promise<void> {\n const entries = await outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n const blocked = new Set<string>();\n for (const entry of entries) {\n if (blocked.has(entry.recordId)) {\n summary.deferred += 1;\n continue;\n }\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 blocked.add(entry.recordId);\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 deferred: 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 deferred: 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":"A,4EAiQA,SAASI,EAAsB,EAA6B,CACxD,IAAMC,EAAY,OAA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,EAAO,MAAM,EACnB,MAAMiB,EAAe,CACzB,EACA,gBAAiB,CACbf,EAAU,MAAM,CACpB,EACA,UAAW,CACP,OAAOK,CACX,EACA,UAAU,EAAU,CAEhB,OADAD,EAAU,IAAIO,CAAQ,MACT,CACTP,EAAU,OAAOO,CAAQ,CAC7B,CACJ,EACA,SAAU,CACN,EAAS,GACTH,GAAS,MAAM,CACnB,CACJ,CACJ,C"}
1
+ {"version":3,"file":"create-offline-sync.cjs","names":["createOfflineStore","ownerFingerprint","randomId","require_ids","require_owner_fingerprint","require_create_offline_store","localStorageWatermark","available","key","value","createOfflineSync","outbox","config","watermark","idPrefix","isOnline","currentOwner","principal","ownership","getPrincipal","entry","owner","inflight","generation","listeners","state","crossTab","channelName","channel","closed","notify","listener","setState","patch","event","refreshPending","endSession","push","entries","blocked","stillQueued","runGeneration","verdict","summary","cause","message","pull","since","cursor","serverTime","page","item","runOnce","startedAt","runGuarded","locks","trigger","lock","lastEnqueuedAt","nextEnqueuedAt","now","run"],"sources":["../../src/offline/create-offline-sync.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — outbox drain, pull-with-watermark,\n * conflict resolution and the single-flight guard are one loop by necessity: a pull\n * that lands mid-drain must not advance the watermark past records the outbox has\n * not pushed yet. Splitting the phases hands that ordering to whoever calls them in\n * the right sequence.\n */\nimport { randomId } from \"../utils/ids\";\nimport { ownerFingerprint } from \"../utils/owner-fingerprint\";\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 * One-way fingerprint of whoever was signed in when the entry was queued\n * (`null` for nobody), stamped only when the engine has\n * {@link OfflineSyncConfig.getPrincipal}. Absent on entries queued without\n * it, which are delivered as before.\n */\n owner?: string | null;\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 /**\n * Entries left untried because an earlier entry for the **same record**\n * failed this run.\n *\n * They stay queued and are attempted next run, in order. Counted apart from\n * `failed` because they were never sent: reporting them as failures would\n * blame the server for a decision this engine made, and folding them in would\n * make `succeeded + failed` stop accounting for the queue.\n */\n deferred: 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 * `true` when {@link OfflineSync.clearOutbox} or {@link OfflineSync.resetWatermark}\n * ended the session while this run was in flight, so it stopped early.\n *\n * The counts cover only what happened before the stop: a delivery already in\n * progress at logout is still counted, but no later entry was sent, no further\n * page was pulled or applied, and the watermark was not written. Absent on a\n * run that went to completion.\n */\n interrupted?: true;\n /**\n * Entries left queued because nobody is signed in and they belong to\n * somebody (see {@link OfflineSyncConfig.getPrincipal}). Absent when zero.\n */\n held?: number;\n /**\n * Entries deleted unsent because they were queued under another principal —\n * or while signed out — and somebody else is signed in now (see\n * {@link OfflineSyncConfig.getPrincipal}). Absent when zero.\n */\n dropped?: number;\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 * Who is signed in right now — a stable, non-secret id such as the user id;\n * `null`/`undefined` when nobody is. Read synchronously when an entry is\n * queued, which stamps it with a one-way fingerprint (`entry.owner`, never\n * the id itself), and again right before each delivery:\n *\n * - same principal → delivered;\n * - nobody signed in now → held: it stays queued and goes out when its owner\n * signs back in, so a flush fired by the `online` event before login loses\n * nothing;\n * - anybody else → deleted unsent and counted in `summary.dropped`, because\n * delivering it would send the previous account's mutation with the next\n * account's session.\n *\n * `clearOutbox()` on logout already empties the queue; this covers the app\n * that forgets it, or a session that ends without a logout (#531). Entries\n * queued before this option was set carry no stamp and are delivered as\n * before — they are the user's own unsynced edits, and holding them would\n * strand every queue on upgrade.\n *\n * A non-string, non-number value (the `Promise` of an `async` getter) or a\n * getter that throws reads as nobody. Default: no owner binding.\n */\n getPrincipal?: () => string | number | null | undefined;\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 /**\n * Drop every queued mutation (e.g. on logout).\n *\n * Also ends the current session for any `flush` already in flight: that run\n * delivers no further entry, pulls and applies nothing more and writes no\n * watermark, and resolves with `interrupted: true`. A `flush` called after this\n * starts a fresh run instead of joining the abandoned one.\n */\n clearOutbox: () => Promise<void>;\n /**\n * Reset the pull watermark (e.g. on logout / account switch).\n *\n * Ends the current session for an in-flight `flush` exactly like\n * {@link OfflineSync.clearOutbox}, so the run cannot write the ended\n * session's watermark back after the reset.\n */\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 const { getPrincipal } = config;\n\n /**\n * Fingerprint whoever `getPrincipal` says is signed in.\n *\n * @param principal - The app's principal getter.\n * @returns The fingerprint, or `null` for nobody, a non-identity value or a\n * getter that throws.\n */\n function currentOwner(principal: () => unknown): string | null {\n try {\n return ownerFingerprint(\"p\", principal());\n } catch {\n return null;\n }\n }\n\n /**\n * What the current session may do with an entry, by its owner stamp.\n *\n * @param entry - The queued entry.\n * @returns `\"deliver\"`, `\"hold\"` (nobody signed in) or `\"drop\"` (someone else).\n */\n function ownership(entry: OutboxEntry<TPayload>): \"deliver\" | \"hold\" | \"drop\" {\n if (!getPrincipal || entry.owner === undefined) return \"deliver\";\n const owner = currentOwner(getPrincipal);\n if (owner === entry.owner) return \"deliver\";\n return owner === null ? \"hold\" : \"drop\";\n }\n\n let inflight: Promise<SyncRunSummary> | null = null;\n let generation = 0;\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 /**\n * End the current session: every run started before this call is fenced off.\n *\n * Runs capture `generation` when they start and re-check it after every\n * `await`, so the next step of a run started under the previous user — the\n * next `deliver`, the next `pullPage`, an `applyRemote`, the watermark write —\n * never executes under the next user's session. The await already pending (a\n * `deliver` in flight) cannot be recalled; it was issued under the old session\n * and is only bookkept.\n *\n * Detaching `inflight` is what lets the next session's `flush` start its own\n * run instead of joining the abandoned one, which would hand the new user a\n * summary of the old user's queue and leave their own entries waiting. The\n * phase drops back to `\"idle\"` because nothing of the current session is\n * syncing any more.\n */\n function endSession(): void {\n generation += 1;\n if (inflight) {\n inflight = null;\n setState({ phase: \"idle\" });\n }\n }\n\n /**\n * Drain the outbox in `enqueuedAt` order, one record at a time.\n *\n * Once an entry for a record fails, the remaining entries **for that record**\n * are left untried this run. `enqueuedAt` is a FIFO guarantee the engine goes\n * out of its way to keep (see `nextEnqueuedAt`), precisely because delivering\n * an `update` before the `create` it depends on is wrong — and continuing past\n * a failure broke exactly that guarantee. With a `PUT` upsert `deliver`, which\n * is the usual shape, the server would create the record from the *update*\n * payload and the retried `create` would then overwrite it with the older\n * snapshot: the user's edit disappears with nothing reported.\n *\n * Skipping is per record, not per run. Records are independent, so a record\n * the server is rejecting must not hold up every other pending change.\n *\n * The entry list is a snapshot, so before each `deliver` the run checks that\n * its session is still current (see `endSession`) and that the entry is still\n * in the outbox — another tab sharing the IndexedDB may have cleared it on\n * logout. With `getPrincipal`, the entry's owner stamp is checked at the same\n * point (see `ownership`): another principal's entry is deleted unsent, and\n * one owned by somebody while nobody is signed in stays queued; neither blocks\n * later entries of the same record. A delivery already in progress when the\n * session ended still has its\n * row deleted or its attempt bumped, because that outcome is true for the\n * server; its `onEntryDelivered`/`onEntryFailed` callback is not fired, since\n * it would act on the next user's local state.\n *\n * @param summary - Mutated with the per-entry outcome counts.\n * @param runGeneration - The session the run started under.\n * @returns `false` when the session ended mid-drain and the run must stop.\n */\n async function push(summary: SyncRunSummary, runGeneration: number): Promise<boolean> {\n const entries = await outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n const blocked = new Set<string>();\n for (const entry of entries) {\n if (blocked.has(entry.recordId)) {\n summary.deferred += 1;\n continue;\n }\n const stillQueued = await outbox.get(entry.id);\n if (generation !== runGeneration) return false;\n if (!stillQueued) continue;\n const verdict = ownership(entry);\n if (verdict === \"hold\") {\n summary.held = (summary.held ?? 0) + 1;\n continue;\n }\n if (verdict === \"drop\") {\n await outbox.delete(entry.id);\n summary.dropped = (summary.dropped ?? 0) + 1;\n continue;\n }\n try {\n await config.deliver(entry);\n await outbox.delete(entry.id);\n summary.succeeded += 1;\n if (generation !== runGeneration) return false;\n await config.onEntryDelivered?.(entry);\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 blocked.add(entry.recordId);\n summary.failed += 1;\n summary.lastError = message;\n if (generation !== runGeneration) return false;\n await config.onEntryFailed?.(entry, cause);\n }\n }\n return generation === runGeneration;\n }\n\n /**\n * Pull the server delta page by page, then advance the watermark.\n *\n * Checks the session (see `endSession`) before every `applyRemote`, before the\n * next `pullPage` and before the watermark write: a page fetched under the\n * previous user is never merged into the local store after logout, the next\n * page is never requested with the previous user's cursor, and\n * `resetWatermark()` is never undone by the run it was meant to end.\n *\n * @param runGeneration - The session the run started under.\n * @returns `false` when the session ended mid-pull and the run stopped.\n */\n async function pull(runGeneration: number): Promise<boolean> {\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 if (generation !== runGeneration) return false;\n await config.applyRemote(item);\n }\n if (generation !== runGeneration) return false;\n cursor = page.nextCursor;\n serverTime = page.serverTime;\n } while (cursor);\n if (serverTime) watermark.set(serverTime);\n return true;\n }\n\n /**\n * One push-then-pull pass, stopped early when the session it belongs to ends.\n *\n * @param trigger - What asked for this run, carried into the summary.\n * @param runGeneration - The session captured when `flush` was called, not\n * when the pass starts: with Web Locks the pass can start after a logout that\n * happened while the lock was being granted, and must not adopt the new\n * session.\n * @returns The run summary, with `interrupted: true` when the session ended.\n */\n async function runOnce(trigger: SyncTrigger, runGeneration: number): Promise<SyncRunSummary> {\n const startedAt = Date.now();\n const summary: SyncRunSummary = {\n trigger,\n succeeded: 0,\n failed: 0,\n deferred: 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 const completed = (await push(summary, runGeneration)) && (await pull(runGeneration));\n if (!completed) summary.interrupted = true;\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 * @param runGeneration - The session the run belongs to (see `runOnce`).\n * @returns The run summary, or an empty summary when another tab held the lock.\n */\n async function runGuarded(\n trigger: SyncTrigger,\n runGeneration: number,\n ): Promise<SyncRunSummary> {\n const locks = typeof navigator !== \"undefined\" ? navigator.locks : undefined;\n if (!crossTab || !locks) return runOnce(trigger, runGeneration);\n const result = await locks.request(\n `${channelName}:flush`,\n { ifAvailable: true },\n async (lock) => (lock ? runOnce(trigger, runGeneration) : null),\n );\n return (\n result ?? {\n trigger,\n succeeded: 0,\n failed: 0,\n deferred: 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 if (getPrincipal) entry.owner = currentOwner(getPrincipal);\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 const runGeneration = generation;\n const run: Promise<SyncRunSummary> = runGuarded(trigger, runGeneration)\n .then(async (summary) => {\n await refreshPending();\n if (generation !== runGeneration) return summary;\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 if (inflight === run) inflight = null;\n });\n inflight = run;\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 endSession();\n await outbox.clear();\n await refreshPending();\n },\n resetWatermark() {\n endSession();\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":"A,wHAmUA,SAASM,EAAsB,EAA6B,CACxD,IAAMC,EAAY,OAAO,aAAiB,IAC1C,MAAO,CACH,QAAYA,EAAY,aAAa,QAAQC,CAAG,EAAI,KACpD,IAAM,GAAkB,CAChBD,GAAW,aAAa,QAAQC,EAAKC,CAAK,CAClD,EACA,UAAa,CACLF,GAAW,aAAa,WAAWC,CAAG,CAC9C,CACJ,CACJ,CAsCA,SAAgBE,EACZ,EACqB,CACrB,IAAMC,E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@
1
1
  import { randomId as e } from "../utils/ids.js";
2
- import { createOfflineStore as t } from "./create-offline-store.js";
2
+ import { ownerFingerprint as t } from "../utils/owner-fingerprint.js";
3
+ import { createOfflineStore as n } from "./create-offline-store.js";
3
4
  //#region src/offline/create-offline-sync.ts
4
- function n(e) {
5
+ function r(e) {
5
6
  let t = typeof localStorage < "u";
6
7
  return {
7
8
  get: () => t ? localStorage.getItem(e) : null,
@@ -13,59 +14,93 @@ function n(e) {
13
14
  }
14
15
  };
15
16
  }
16
- function r(r) {
17
- let i = t({
18
- databaseName: r.databaseName,
19
- version: r.version ?? 1,
20
- tableName: r.tableName ?? "outbox",
17
+ function i(i) {
18
+ let a = n({
19
+ databaseName: i.databaseName,
20
+ version: i.version ?? 1,
21
+ tableName: i.tableName ?? "outbox",
21
22
  indexes: "&id, recordId, enqueuedAt",
22
23
  keyPath: "id"
23
- }), 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 = /* @__PURE__ */ new Set(), u = {
24
+ }), o = "get" in i.watermark ? i.watermark : r(i.watermark.storageKey), s = i.idPrefix ?? "outbox", c = i.isOnline ?? (() => typeof navigator < "u" ? navigator.onLine : !0), { getPrincipal: l } = i;
25
+ function u(e) {
26
+ try {
27
+ return t("p", e());
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+ function d(e) {
33
+ if (!l || e.owner === void 0) return "deliver";
34
+ let t = u(l);
35
+ return t === e.owner ? "deliver" : t === null ? "hold" : "drop";
36
+ }
37
+ let f = null, p = 0, m = /* @__PURE__ */ new Set(), h = {
24
38
  phase: "idle",
25
39
  pending: 0,
26
40
  lastSummary: null,
27
41
  lastError: null,
28
42
  lastSyncedAt: null
29
- }, d = r.crossTab === !0, f = r.broadcastChannelName ?? `tempest-sync:${r.databaseName}`, p = d && typeof BroadcastChannel < "u" ? new BroadcastChannel(f) : null, m = !1;
30
- function h() {
31
- for (let e of l) e(u);
43
+ }, g = i.crossTab === !0, _ = i.broadcastChannelName ?? `tempest-sync:${i.databaseName}`, v = g && typeof BroadcastChannel < "u" ? new BroadcastChannel(_) : null, y = !1;
44
+ function b() {
45
+ for (let e of m) e(h);
32
46
  }
33
- function g(e) {
34
- u = {
35
- ...u,
47
+ function x(e) {
48
+ h = {
49
+ ...h,
36
50
  ...e
37
- }, h(), p && !m && p.postMessage(u);
51
+ }, b(), v && !y && v.postMessage(h);
38
52
  }
39
- p && (p.onmessage = (e) => {
40
- m || (u = e.data, h());
53
+ v && (v.onmessage = (e) => {
54
+ y || (h = e.data, b());
41
55
  });
42
- async function _() {
43
- g({ pending: await i.count() });
56
+ async function S() {
57
+ x({ pending: await a.count() });
44
58
  }
45
- async function v(e) {
46
- let t = await i.list(void 0, { orderBy: "enqueuedAt" }), n = /* @__PURE__ */ new Set();
47
- for (let a of t) if (n.has(a.recordId)) e.deferred += 1;
48
- else try {
49
- await r.deliver(a), await i.delete(a.id), await r.onEntryDelivered?.(a), e.succeeded += 1;
50
- } catch (t) {
51
- let o = t instanceof Error ? t.message : "delivery failed";
52
- await i.update(a.id, {
53
- attempts: a.attempts + 1,
54
- lastError: o
55
- }), await r.onEntryFailed?.(a, t), n.add(a.recordId), e.failed += 1, e.lastError = o;
59
+ function C() {
60
+ p += 1, f && (f = null, x({ phase: "idle" }));
61
+ }
62
+ async function w(e, t) {
63
+ let n = await a.list(void 0, { orderBy: "enqueuedAt" }), r = /* @__PURE__ */ new Set();
64
+ for (let o of n) {
65
+ if (r.has(o.recordId)) {
66
+ e.deferred += 1;
67
+ continue;
68
+ }
69
+ let n = await a.get(o.id);
70
+ if (p !== t) return !1;
71
+ if (!n) continue;
72
+ let s = d(o);
73
+ if (s === "hold") e.held = (e.held ?? 0) + 1;
74
+ else if (s === "drop") await a.delete(o.id), e.dropped = (e.dropped ?? 0) + 1;
75
+ else try {
76
+ if (await i.deliver(o), await a.delete(o.id), e.succeeded += 1, p !== t) return !1;
77
+ await i.onEntryDelivered?.(o);
78
+ } catch (n) {
79
+ let s = n instanceof Error ? n.message : "delivery failed";
80
+ if (await a.update(o.id, {
81
+ attempts: o.attempts + 1,
82
+ lastError: s
83
+ }), r.add(o.recordId), e.failed += 1, e.lastError = s, p !== t) return !1;
84
+ await i.onEntryFailed?.(o, n);
85
+ }
56
86
  }
87
+ return p === t;
57
88
  }
58
- async function y() {
59
- let e = a.get(), t = null, n;
89
+ async function T(e) {
90
+ let t = o.get(), n = null, r;
60
91
  do {
61
- let i = await r.pullPage(e, t);
62
- for (let e of i.items) await r.applyRemote(e);
63
- t = i.nextCursor, n = i.serverTime;
64
- } while (t);
65
- n && a.set(n);
92
+ let a = await i.pullPage(t, n);
93
+ for (let t of a.items) {
94
+ if (p !== e) return !1;
95
+ await i.applyRemote(t);
96
+ }
97
+ if (p !== e) return !1;
98
+ n = a.nextCursor, r = a.serverTime;
99
+ } while (n);
100
+ return r && o.set(r), !0;
66
101
  }
67
- async function b(e) {
68
- let t = Date.now(), n = {
102
+ async function E(e, t) {
103
+ let n = Date.now(), r = {
69
104
  trigger: e,
70
105
  succeeded: 0,
71
106
  failed: 0,
@@ -74,11 +109,11 @@ function r(r) {
74
109
  skipped: !1,
75
110
  lastError: null
76
111
  };
77
- return s() ? (await v(n), await y(), n.durationMs = Date.now() - t, n) : (n.skipped = !0, n.durationMs = Date.now() - t, n);
112
+ return c() ? (await w(r, t) && await T(t) || (r.interrupted = !0), r.durationMs = Date.now() - n, r) : (r.skipped = !0, r.durationMs = Date.now() - n, r);
78
113
  }
79
- async function x(e) {
80
- let t = typeof navigator < "u" ? navigator.locks : void 0;
81
- return !d || !t ? b(e) : await t.request(`${f}:flush`, { ifAvailable: !0 }, async (t) => t ? b(e) : null) ?? {
114
+ async function D(e, t) {
115
+ let n = typeof navigator < "u" ? navigator.locks : void 0;
116
+ return !g || !n ? E(e, t) : await n.request(`${_}:flush`, { ifAvailable: !0 }, async (n) => n ? E(e, t) : null) ?? {
82
117
  trigger: e,
83
118
  succeeded: 0,
84
119
  failed: 0,
@@ -88,60 +123,65 @@ function r(r) {
88
123
  lastError: null
89
124
  };
90
125
  }
91
- _();
92
- let S = 0;
93
- function C() {
126
+ S();
127
+ let O = 0;
128
+ function k() {
94
129
  let e = Date.now();
95
- return S = e > S ? e : S + 1, S;
130
+ return O = e > O ? e : O + 1, O;
96
131
  }
97
132
  return {
98
133
  async enqueue(t, n, r) {
99
- let a = {
100
- id: e(o),
134
+ let i = {
135
+ id: e(s),
101
136
  op: t,
102
137
  recordId: n,
103
- enqueuedAt: C(),
138
+ enqueuedAt: k(),
104
139
  attempts: 0,
105
140
  payload: r
106
141
  };
107
- return await i.put(a), await _(), a.id;
142
+ return l && (i.owner = u(l)), await a.put(i), await S(), i.id;
108
143
  },
109
144
  flush(e = "manual") {
110
- return c ||= (g({ phase: "syncing" }), x(e).then(async (e) => (await _(), g({
111
- phase: e.skipped ? "offline" : e.failed > 0 ? "error" : "idle",
112
- lastSummary: e,
113
- lastError: e.lastError,
114
- lastSyncedAt: e.skipped ? u.lastSyncedAt : Date.now()
115
- }), e)).finally(() => {
116
- c = null;
117
- })), c;
145
+ if (!f) {
146
+ x({ phase: "syncing" });
147
+ let t = p, n = D(e, t).then(async (e) => (await S(), p === t && x({
148
+ phase: e.skipped ? "offline" : e.failed > 0 ? "error" : "idle",
149
+ lastSummary: e,
150
+ lastError: e.lastError,
151
+ lastSyncedAt: e.skipped ? h.lastSyncedAt : Date.now()
152
+ }), e)).finally(() => {
153
+ f === n && (f = null);
154
+ });
155
+ f = n;
156
+ }
157
+ return f;
118
158
  },
119
159
  pendingCount() {
120
- return i.count();
160
+ return a.count();
121
161
  },
122
162
  listPending() {
123
- return i.list(void 0, { orderBy: "enqueuedAt" });
163
+ return a.list(void 0, { orderBy: "enqueuedAt" });
124
164
  },
125
165
  async clearOutbox() {
126
- await i.clear(), await _();
166
+ C(), await a.clear(), await S();
127
167
  },
128
168
  resetWatermark() {
129
- a.clear();
169
+ C(), o.clear();
130
170
  },
131
171
  getState() {
132
- return u;
172
+ return h;
133
173
  },
134
174
  subscribe(e) {
135
- return l.add(e), () => {
136
- l.delete(e);
175
+ return m.add(e), () => {
176
+ m.delete(e);
137
177
  };
138
178
  },
139
179
  dispose() {
140
- m = !0, p?.close();
180
+ y = !0, v?.close();
141
181
  }
142
182
  };
143
183
  }
144
184
  //#endregion
145
- export { r as createOfflineSync };
185
+ export { i as createOfflineSync };
146
186
 
147
187
  //# sourceMappingURL=create-offline-sync.js.map