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.
- package/README.md +40 -10
- package/bin/create-tempest-app.e2e.test.mjs +31 -0
- package/bin/create-tempest-app.mjs +11 -1
- package/bin/lib/component/generate.test.mjs +13 -1
- package/bin/lib/doctor/doctor.e2e.test.mjs +29 -0
- package/bin/lib/doctor/vitest.mjs +120 -0
- package/bin/lib/doctor/vitest.test.mjs +139 -0
- package/bin/lib/fs/contain.mjs +7 -0
- package/bin/lib/openapi/escape.mjs +68 -4
- package/bin/lib/openapi/generate.hostile.test.mjs +150 -1
- package/bin/lib/openapi/generate.mjs +78 -13
- package/bin/lib/openapi/generate.test.mjs +13 -1
- package/bin/lib/openapi/pattern-risk.mjs +134 -0
- package/bin/lib/openapi/pattern-risk.test.mjs +45 -0
- package/bin/tempest-gen.test.mjs +100 -0
- package/bin/tempest.mjs +24 -8
- package/dist/access/use-can.cjs +1 -1
- package/dist/access/use-can.cjs.map +1 -1
- package/dist/access/use-can.js +25 -28
- package/dist/access/use-can.js.map +1 -1
- package/dist/auth/create-tempest-auth.cjs +1 -1
- package/dist/auth/create-tempest-auth.cjs.map +1 -1
- package/dist/auth/create-tempest-auth.js +234 -122
- package/dist/auth/create-tempest-auth.js.map +1 -1
- package/dist/auth/session-identity.cjs +2 -0
- package/dist/auth/session-identity.cjs.map +1 -0
- package/dist/auth/session-identity.js +12 -0
- package/dist/auth/session-identity.js.map +1 -0
- package/dist/br/boleto.cjs +1 -1
- package/dist/br/boleto.cjs.map +1 -1
- package/dist/br/boleto.js +2 -1
- package/dist/br/boleto.js.map +1 -1
- package/dist/br.d.ts +22 -3
- package/dist/components/AuthForm/AuthFieldControl.cjs +2 -0
- package/dist/components/AuthForm/AuthFieldControl.cjs.map +1 -0
- package/dist/components/AuthForm/AuthFieldControl.js +85 -0
- package/dist/components/AuthForm/AuthFieldControl.js.map +1 -0
- package/dist/components/AuthForm/AuthForm.cjs +2 -0
- package/dist/components/AuthForm/AuthForm.cjs.map +1 -0
- package/dist/components/AuthForm/AuthForm.js +83 -0
- package/dist/components/AuthForm/AuthForm.js.map +1 -0
- package/dist/components/AuthForm/AuthForm.module.cjs +3 -0
- package/dist/components/AuthForm/AuthForm.module.cjs.map +1 -0
- package/dist/components/AuthForm/AuthForm.module.js +14 -0
- package/dist/components/AuthForm/AuthForm.module.js.map +1 -0
- package/dist/components/AuthForm/AuthLinks.cjs +2 -0
- package/dist/components/AuthForm/AuthLinks.cjs.map +1 -0
- package/dist/components/AuthForm/AuthLinks.js +32 -0
- package/dist/components/AuthForm/AuthLinks.js.map +1 -0
- package/dist/components/AuthForm/ForgotPasswordForm.cjs +2 -0
- package/dist/components/AuthForm/ForgotPasswordForm.cjs.map +1 -0
- package/dist/components/AuthForm/ForgotPasswordForm.js +32 -0
- package/dist/components/AuthForm/ForgotPasswordForm.js.map +1 -0
- package/dist/components/AuthForm/LoginForm.cjs +2 -0
- package/dist/components/AuthForm/LoginForm.cjs.map +1 -0
- package/dist/components/AuthForm/LoginForm.js +39 -0
- package/dist/components/AuthForm/LoginForm.js.map +1 -0
- package/dist/components/AuthForm/ResetPasswordForm.cjs +2 -0
- package/dist/components/AuthForm/ResetPasswordForm.cjs.map +1 -0
- package/dist/components/AuthForm/ResetPasswordForm.js +39 -0
- package/dist/components/AuthForm/ResetPasswordForm.js.map +1 -0
- package/dist/components/AuthForm/SignUpForm.cjs +2 -0
- package/dist/components/AuthForm/SignUpForm.cjs.map +1 -0
- package/dist/components/AuthForm/SignUpForm.js +32 -0
- package/dist/components/AuthForm/SignUpForm.js.map +1 -0
- package/dist/components/AuthForm/auth-defaults.cjs +2 -0
- package/dist/components/AuthForm/auth-defaults.cjs.map +1 -0
- package/dist/components/AuthForm/auth-defaults.js +54 -0
- package/dist/components/AuthForm/auth-defaults.js.map +1 -0
- package/dist/components/AuthForm/auth-schemas.cjs +2 -0
- package/dist/components/AuthForm/auth-schemas.cjs.map +1 -0
- package/dist/components/AuthForm/auth-schemas.js +26 -0
- package/dist/components/AuthForm/auth-schemas.js.map +1 -0
- package/dist/components/AuthPage/AuthPage.cjs +2 -0
- package/dist/components/AuthPage/AuthPage.cjs.map +1 -0
- package/dist/components/AuthPage/AuthPage.js +97 -0
- package/dist/components/AuthPage/AuthPage.js.map +1 -0
- package/dist/components/AuthPage/AuthPage.module.cjs +3 -0
- package/dist/components/AuthPage/AuthPage.module.cjs.map +1 -0
- package/dist/components/AuthPage/AuthPage.module.js +24 -0
- package/dist/components/AuthPage/AuthPage.module.js.map +1 -0
- package/dist/components/Breadcrumbs/Breadcrumbs.cjs +1 -1
- package/dist/components/Breadcrumbs/Breadcrumbs.cjs.map +1 -1
- package/dist/components/Breadcrumbs/Breadcrumbs.js +22 -21
- package/dist/components/Breadcrumbs/Breadcrumbs.js.map +1 -1
- package/dist/components/Button/Button.cjs +1 -1
- package/dist/components/Button/Button.cjs.map +1 -1
- package/dist/components/Button/Button.js +41 -40
- package/dist/components/Button/Button.js.map +1 -1
- package/dist/components/Chat/ChatAttachments.cjs +1 -1
- package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
- package/dist/components/Chat/ChatAttachments.js +38 -38
- package/dist/components/FilterBar/filter-apply.cjs +1 -1
- package/dist/components/FilterBar/filter-apply.cjs.map +1 -1
- package/dist/components/FilterBar/filter-apply.js +7 -7
- package/dist/components/Form/Form.cjs +1 -1
- package/dist/components/Form/Form.cjs.map +1 -1
- package/dist/components/Form/Form.js +30 -32
- package/dist/components/Form/Form.js.map +1 -1
- package/dist/components/Layout/Layout.cjs +1 -1
- package/dist/components/Layout/Layout.cjs.map +1 -1
- package/dist/components/Layout/Layout.js +25 -24
- package/dist/components/Layout/Layout.js.map +1 -1
- package/dist/components/Layout/gap.cjs +2 -0
- package/dist/components/Layout/gap.cjs.map +1 -0
- package/dist/components/Layout/gap.js +15 -0
- package/dist/components/Layout/gap.js.map +1 -0
- package/dist/components/NavigationMenu/NavigationMenu.cjs +1 -1
- package/dist/components/NavigationMenu/NavigationMenu.cjs.map +1 -1
- package/dist/components/NavigationMenu/NavigationMenu.js +71 -70
- package/dist/components/NavigationMenu/NavigationMenu.js.map +1 -1
- package/dist/components/Sidebar/Sidebar.cjs.map +1 -1
- package/dist/components/Sidebar/Sidebar.js.map +1 -1
- package/dist/components/Sidebar/SidebarEntry.cjs +1 -1
- package/dist/components/Sidebar/SidebarEntry.cjs.map +1 -1
- package/dist/components/Sidebar/SidebarEntry.js +30 -29
- package/dist/components/Sidebar/SidebarEntry.js.map +1 -1
- package/dist/data/create-data-provider.cjs +1 -1
- package/dist/data/create-data-provider.cjs.map +1 -1
- package/dist/data/create-data-provider.js +1 -2
- package/dist/data/create-data-provider.js.map +1 -1
- package/dist/forms/index.js +7 -7
- package/dist/forms/masked-inputs.cjs +1 -1
- package/dist/forms/masked-inputs.cjs.map +1 -1
- package/dist/forms/masked-inputs.js +15 -15
- package/dist/forms/validate-form.cjs +1 -1
- package/dist/forms/validate-form.cjs.map +1 -1
- package/dist/forms/validate-form.js +6 -1
- package/dist/forms/validate-form.js.map +1 -1
- package/dist/forms/zod-resolver.cjs +1 -1
- package/dist/forms/zod-resolver.cjs.map +1 -1
- package/dist/forms/zod-resolver.js +8 -3
- package/dist/forms/zod-resolver.js.map +1 -1
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +137 -116
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/credential-scope.cjs +1 -1
- package/dist/http/credential-scope.cjs.map +1 -1
- package/dist/http/credential-scope.js +33 -9
- package/dist/http/credential-scope.js.map +1 -1
- package/dist/http/presigned-post.cjs.map +1 -1
- package/dist/http/presigned-post.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +140 -134
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/upload-with-progress.cjs +1 -1
- package/dist/http/upload-with-progress.cjs.map +1 -1
- package/dist/http/upload-with-progress.js +17 -17
- package/dist/http/upload-with-progress.js.map +1 -1
- package/dist/http/use-describe-api-error.cjs +1 -1
- package/dist/http/use-describe-api-error.cjs.map +1 -1
- package/dist/http/use-describe-api-error.js +9 -9
- package/dist/oauth/GoogleSignIn.cjs +1 -1
- package/dist/oauth/GoogleSignIn.cjs.map +1 -1
- package/dist/oauth/GoogleSignIn.js +5 -4
- package/dist/oauth/GoogleSignIn.js.map +1 -1
- package/dist/offline/create-offline-sync.cjs +1 -1
- package/dist/offline/create-offline-sync.cjs.map +1 -1
- package/dist/offline/create-offline-sync.js +108 -68
- package/dist/offline/create-offline-sync.js.map +1 -1
- package/dist/query/offline-persistence.cjs +1 -1
- package/dist/query/offline-persistence.cjs.map +1 -1
- package/dist/query/offline-persistence.js +54 -44
- package/dist/query/offline-persistence.js.map +1 -1
- package/dist/sse/create-event-stream.cjs +1 -1
- package/dist/sse/create-event-stream.cjs.map +1 -1
- package/dist/sse/create-event-stream.js +48 -41
- package/dist/sse/create-event-stream.js.map +1 -1
- package/dist/sse/ticket-event-stream.cjs +1 -1
- package/dist/sse/ticket-event-stream.cjs.map +1 -1
- package/dist/sse/ticket-event-stream.js +48 -19
- package/dist/sse/ticket-event-stream.js.map +1 -1
- package/dist/sse/use-event-stream.cjs +1 -1
- package/dist/sse/use-event-stream.cjs.map +1 -1
- package/dist/sse/use-event-stream.js +19 -14
- package/dist/sse/use-event-stream.js.map +1 -1
- package/dist/styles/AuthForm.css +2 -0
- package/dist/styles/AuthPage.css +2 -0
- package/dist/styles/component/AuthForm.css +9 -0
- package/dist/styles/component/AuthPage.css +29 -0
- package/dist/styles/forms.css +36 -0
- package/dist/styles/manifest.json +63 -0
- package/dist/styles.css +1 -1
- package/dist/sw/background-sync.cjs +1 -1
- package/dist/sw/background-sync.cjs.map +1 -1
- package/dist/sw/background-sync.js +132 -112
- package/dist/sw/background-sync.js.map +1 -1
- package/dist/sw/cache.cjs +1 -1
- package/dist/sw/cache.cjs.map +1 -1
- package/dist/sw/cache.js +36 -30
- package/dist/sw/cache.js.map +1 -1
- package/dist/sw/create-push-handler.cjs +1 -1
- package/dist/sw/create-push-handler.cjs.map +1 -1
- package/dist/sw/create-push-handler.js +20 -10
- package/dist/sw/create-push-handler.js.map +1 -1
- package/dist/sw.d.ts +93 -28
- package/dist/tabular/compact.cjs +1 -1
- package/dist/tabular/compact.cjs.map +1 -1
- package/dist/tabular/compact.js +35 -16
- package/dist/tabular/compact.js.map +1 -1
- package/dist/tabular/manifest.cjs +1 -1
- package/dist/tabular/manifest.cjs.map +1 -1
- package/dist/tabular/manifest.js +33 -15
- package/dist/tabular/manifest.js.map +1 -1
- package/dist/tabular.d.ts +11 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +1057 -83
- package/dist/tempest-react-sdk.js +373 -365
- package/dist/theme/initial-theme.cjs +4 -4
- package/dist/theme/initial-theme.cjs.map +1 -1
- package/dist/theme/initial-theme.js +8 -5
- package/dist/theme/initial-theme.js.map +1 -1
- package/dist/utils/compressed-storage.cjs +1 -1
- package/dist/utils/compressed-storage.cjs.map +1 -1
- package/dist/utils/compressed-storage.js +13 -7
- package/dist/utils/compressed-storage.js.map +1 -1
- package/dist/utils/format.cjs +1 -1
- package/dist/utils/format.cjs.map +1 -1
- package/dist/utils/format.js +25 -25
- package/dist/utils/numbers.cjs +1 -1
- package/dist/utils/numbers.cjs.map +1 -1
- package/dist/utils/numbers.js +7 -7
- package/dist/utils/objects.cjs +1 -1
- package/dist/utils/objects.cjs.map +1 -1
- package/dist/utils/objects.js +13 -7
- package/dist/utils/objects.js.map +1 -1
- package/dist/utils/safe-url.cjs +1 -1
- package/dist/utils/safe-url.cjs.map +1 -1
- package/dist/utils/safe-url.js +4 -1
- package/dist/utils/safe-url.js.map +1 -1
- package/dist/webrtc/peer-mesh.cjs +1 -1
- package/dist/webrtc/peer-mesh.cjs.map +1 -1
- package/dist/webrtc/peer-mesh.js +7 -1
- package/dist/webrtc/peer-mesh.js.map +1 -1
- package/dist/ws/create-web-socket.cjs +1 -1
- package/dist/ws/create-web-socket.cjs.map +1 -1
- package/dist/ws/create-web-socket.js +77 -61
- package/dist/ws/create-web-socket.js.map +1 -1
- package/dist/ws/use-web-socket.cjs +1 -1
- package/dist/ws/use-web-socket.cjs.map +1 -1
- package/dist/ws/use-web-socket.js +4 -3
- package/dist/ws/use-web-socket.js.map +1 -1
- package/package.json +1 -1
- package/template-pwa/src/pwa.tsx +42 -0
- package/template-pwa/src/sw.ts +15 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-offline-sync.js","names":["localStorageWatermark","available","key","value","createOfflineSync","outbox","createOfflineStore","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","randomId"],"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":";;;AAiQA,SAASA,EAAsB,GAA6B;CACxD,IAAMC,IAAY,OAAO,eAAiB;CAC1C,OAAO;EACH,WAAYA,IAAY,aAAa,QAAQC,CAAG,IAAI;EACpD,MAAM,MAAkB;GACpB,AAAID,KAAW,aAAa,QAAQC,GAAKC,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EACpB;EACA,WAAW;GACP,OAAOV;EACX;EACA,UAAU,GAAU;GAEhB,OADAD,EAAU,IAAIO,CAAQ,SACT;IACT,EAAU,OAAOA,CAAQ;GAC7B;EACJ;EACA,UAAU;GAEN,AADA,IAAS,IACTH,GAAS,MAAM;EACnB;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"create-offline-sync.js","names":["localStorageWatermark","available","key","value","createOfflineSync","outbox","createOfflineStore","config","watermark","idPrefix","isOnline","currentOwner","ownerFingerprint","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","randomId","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":";;;;AAmUA,SAASA,EAAsB,GAA6B;CACxD,IAAMC,IAAY,OAAO,eAAiB;CAC1C,OAAO;EACH,WAAYA,IAAY,aAAa,QAAQC,CAAG,IAAI;EACpD,MAAM,MAAkB;GACpB,AAAID,KAAW,aAAa,QAAQC,GAAKC,CAAK;EAClD;EACA,aAAa;GACT,AAAIF,KAAW,aAAa,WAAWC,CAAG;EAC9C;CACJ;AACJ;AAsCA,SAAgBE,EACZ,GACqB;CACrB,IAAMC,IAASC,EAAkD;EAC7D,cAAcC,EAAO;EACrB,SAASA,EAAO,WAAW;EAC3B,WAAWA,EAAO,aAAa;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ode.cjs"),t=require("../offline/create-offline-store.cjs");let
|
|
1
|
+
const e=require("../utils/dev-mode.cjs"),t=require("../utils/owner-fingerprint.cjs"),n=require("../offline/create-offline-store.cjs");let r=require("@tanstack/react-query");var i=new Map;function a(e){try{return t.ownerFingerprint(`p`,e())}catch{return null}}function o(t){let{queryClient:o,throttleMs:s=1e3,getPrincipal:c}=t,l=t.key??`tanstack-query`,u=t.databaseName??`TempestQueryCache`,d=n.createOfflineStore({databaseName:u,version:1,tableName:`cache`,indexes:`&id`,keyPath:`id`}),f=`${u}\u0000${l}`,p=!1,m=!1,h=null,g=new Set;async function _(){let e=i.get(f);e&&await e}function v(){!m&&e.isDevBuild()&&(m=!0,console.warn(`[tempest-react-sdk] persistQueryClientOffline: handle ended by clear(); create a new one after login to keep persisting.`))}async function y(){if(p||(await _(),p))return;let e={id:l,state:(0,r.dehydrate)(o)};c&&(e.owner=a(c));let t=d.put(e);g.add(t);try{await t}finally{g.delete(t)}}function b(){h&&=(clearTimeout(h),null)}function x(){h||p||(h=setTimeout(()=>{h=null,y()},s))}function S(e){p?(e.type===`added`||e.type===`updated`)&&(C(),v()):x()}let C=o.getQueryCache().subscribe(S);async function w(e){try{await Promise.allSettled([...g]),await d.delete(l)}finally{e&&o.clear()}}return{async restore(){if(p){v();return}if(await _(),p)return;let e=await d.get(l);e&&!p&&(c&&e.owner!==a(c)||(0,r.hydrate)(o,e.state))},async flush(){p?v():(b(),await y())},unsubscribe(){b(),C()},async clear(e={}){p=!0,b();let t=i.get(f),n=w(e.resetClient??!1),r=Promise.allSettled([t,n]);i.set(f,r),r.then(()=>{i.get(f)===r&&i.delete(f)}),await n}}}exports.persistQueryClientOffline=o;
|
|
2
2
|
//# sourceMappingURL=offline-persistence.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"offline-persistence.cjs","names":["createOfflineStore","isDevBuild","dehydrate","require_dev_mode","require_create_offline_store","_tanstack_react_query","pendingClears","persistQueryClientOffline","options","key","databaseName","store","slot","ended","warnedEnded","timer","inFlight","afterPendingClear","pending","warnEnded","save","write","queryClient","cancelTimer","schedule","throttleMs","onCacheEvent","event","unsubscribeCache","endSession","resetClient","snapshot","previous","run","clearOptions","settled"],"sources":["../../src/query/offline-persistence.ts"],"sourcesContent":["import {\n dehydrate,\n hydrate,\n type QueryCacheNotifyEvent,\n type QueryClient,\n} from \"@tanstack/react-query\";\nimport { createOfflineStore } from \"../offline/create-offline-store\";\nimport { isDevBuild } from \"../utils/dev-mode\";\n\n/**\n * Clears still running, per `databaseName` + `key` slot, across every handle.\n *\n * A handle's `clear()` deletes by key with no ordering against other handles,\n * so a new handle created on login while the previous one is still clearing\n * could `restore()` the previous user's snapshot before the delete lands, or\n * have its first write deleted by it. Every handle's `restore()` and writes\n * wait for the slot's pending clear first; the entry is dropped once settled.\n */\nconst pendingClears = new Map<string, Promise<unknown>>();\n\n/** Options for {@link persistQueryClientOffline}. */\nexport interface OfflineQueryPersistenceOptions {\n /** The `QueryClient` to snapshot and restore. */\n queryClient: QueryClient;\n /** IndexedDB database name for the snapshot. Default `\"TempestQueryCache\"`. */\n databaseName?: string;\n /** Row key under which the snapshot is stored. Default `\"tanstack-query\"`. */\n key?: string;\n /**\n * Minimum gap between snapshot writes, in ms — cache churn is coalesced into\n * one trailing write per window. Default `1000`.\n */\n throttleMs?: number;\n}\n\n/** Options for {@link OfflineQueryPersistence.clear}. */\nexport interface OfflineQueryClearOptions {\n /**\n * Also clear the in-memory `QueryClient` (`queryClient.clear()`) once\n * persistence has stopped and the snapshot is deleted — the one-call logout.\n * Default `false`: the client belongs to the app, which may want to keep\n * public queries (a catalog, feature flags) across sessions and drop only\n * the user-scoped keys with `removeQueries`.\n */\n resetClient?: boolean;\n}\n\n/** Handle returned by {@link persistQueryClientOffline}. */\nexport interface OfflineQueryPersistence {\n /**\n * Load the persisted snapshot into the `QueryClient`. Call once on boot,\n * before rendering queries, so cached data is available offline. A no-op\n * once {@link OfflineQueryPersistence.clear} has been called.\n */\n restore: () => Promise<void>;\n /**\n * Write the current cache snapshot immediately (bypassing the throttle). A\n * no-op once {@link OfflineQueryPersistence.clear} has been called.\n */\n flush: () => Promise<void>;\n /** Stop persisting and drop the pending write. Idempotent. */\n unsubscribe: () => void;\n /**\n * End the persisted session (e.g. on logout) and delete the snapshot.\n *\n * Terminal for this handle: it cancels the pending throttled write, stops\n * persisting cache changes, waits for any write already in flight and only\n * then deletes the row — so neither a write pending in the last throttle\n * window nor cache activity after logout (the next user's first query) can\n * re-persist the previous user's responses. Afterwards `restore`/`flush`\n * are no-ops; to persist a new session, call\n * {@link persistQueryClientOffline} again after login. In a dev build\n * (`isDevBuild()`), the first `restore`, `flush` or added/updated query on\n * an ended handle logs one `console.warn` saying so, because a handle kept\n * at module scope would otherwise stop persisting in silence.\n *\n * Ordered against other handles on the same `databaseName` + `key`: until\n * this clear settles, a new handle's `restore()` and writes wait for it, so\n * a handle created on login without awaiting the logout neither hydrates\n * the previous snapshot nor has its first write deleted.\n *\n * If the delete rejects, `resetClient` still clears the client and the\n * rejection reaches the caller.\n *\n * The in-memory `QueryClient` is cleared only with `resetClient: true`, and\n * then only after persistence has stopped, so the reset itself cannot\n * trigger a write. It is opt-in because the app owns the client and the\n * shape of its logout: it may keep public queries and drop only the\n * user-scoped keys with `removeQueries`. Because persistence is already\n * off, that manual call can come before or after this one.\n *\n * Idempotent and safe to call concurrently; every call deletes the row\n * again.\n *\n * @param options - `resetClient` also clears the in-memory `QueryClient`.\n */\n clear: (options?: OfflineQueryClearOptions) => Promise<void>;\n}\n\ninterface Snapshot {\n id: string;\n state: ReturnType<typeof dehydrate>;\n}\n\n/**\n * Persist a TanStack `QueryClient` cache to IndexedDB (via\n * {@link createOfflineStore}) and restore it on boot — so a reload or a cold\n * offline start shows the last-known data instead of empty screens.\n *\n * Self-contained: uses `dehydrate`/`hydrate` from `@tanstack/react-query`\n * directly, so no `@tanstack/react-query-persist-client` dependency is needed.\n * Writes are throttled and subscribe to the query cache; call `unsubscribe` on\n * teardown. Dexie is a peer dependency of the offline store — install it.\n *\n * @param options - The client plus storage/throttle configuration.\n * @returns A handle with `restore`, `flush`, `clear` and `unsubscribe`.\n *\n * `clear()` is terminal for the handle (see {@link OfflineQueryPersistence.clear}):\n * a logout that only deleted the row used to be undone by the pending write or\n * by the next cache event, restoring the previous user's data on the next boot\n * (#440).\n *\n * @example\n * const persistence = persistQueryClientOffline({ queryClient });\n * await persistence.restore();\n *\n * async function logout(): Promise<void> {\n * await persistence.clear({ resetClient: true });\n * }\n */\nexport function persistQueryClientOffline(\n options: OfflineQueryPersistenceOptions,\n): OfflineQueryPersistence {\n const { queryClient, throttleMs = 1000 } = options;\n const key = options.key ?? \"tanstack-query\";\n const databaseName = options.databaseName ?? \"TempestQueryCache\";\n const store = createOfflineStore<Snapshot, string>({\n databaseName,\n version: 1,\n tableName: \"cache\",\n indexes: \"&id\",\n keyPath: \"id\",\n });\n\n const slot = `${databaseName}\\u0000${key}`;\n let ended = false;\n let warnedEnded = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const inFlight = new Set<Promise<unknown>>();\n\n async function afterPendingClear(): Promise<void> {\n const pending = pendingClears.get(slot);\n if (pending) await pending;\n }\n\n function warnEnded(): void {\n if (warnedEnded || !isDevBuild()) return;\n warnedEnded = true;\n console.warn(\n \"[tempest-react-sdk] persistQueryClientOffline: handle ended by clear(); \" +\n \"create a new one after login to keep persisting.\",\n );\n }\n\n async function save(): Promise<void> {\n if (ended) return;\n await afterPendingClear();\n if (ended) return;\n const write = store.put({ id: key, state: dehydrate(queryClient) });\n inFlight.add(write);\n try {\n await write;\n } finally {\n inFlight.delete(write);\n }\n }\n\n function cancelTimer(): void {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n function schedule(): void {\n if (timer || ended) return;\n timer = setTimeout(() => {\n timer = null;\n void save();\n }, throttleMs);\n }\n\n function onCacheEvent(event: QueryCacheNotifyEvent): void {\n if (!ended) {\n schedule();\n return;\n }\n if (event.type !== \"added\" && event.type !== \"updated\") return;\n unsubscribeCache();\n warnEnded();\n }\n\n const unsubscribeCache = queryClient.getQueryCache().subscribe(onCacheEvent);\n\n async function endSession(resetClient: boolean): Promise<void> {\n try {\n await Promise.allSettled([...inFlight]);\n await store.delete(key);\n } finally {\n if (resetClient) queryClient.clear();\n }\n }\n\n return {\n async restore() {\n if (ended) {\n warnEnded();\n return;\n }\n await afterPendingClear();\n if (ended) return;\n const snapshot = await store.get(key);\n if (snapshot && !ended) hydrate(queryClient, snapshot.state);\n },\n async flush() {\n if (ended) {\n warnEnded();\n return;\n }\n cancelTimer();\n await save();\n },\n unsubscribe() {\n cancelTimer();\n unsubscribeCache();\n },\n async clear(clearOptions = {}) {\n ended = true;\n cancelTimer();\n const previous = pendingClears.get(slot);\n const run = endSession(clearOptions.resetClient ?? false);\n const settled = Promise.allSettled([previous, run]);\n pendingClears.set(slot, settled);\n void settled.then(() => {\n if (pendingClears.get(slot) === settled) pendingClears.delete(slot);\n });\n await run;\n },\n };\n}\n"],"mappings":"A,iIAkBA,IAAMM,EAAgB,IAAI,IAgH1B,SAAgBC,EACZ,EACuB,CACvB,GAAM,CAAE,cAAa,aAAa,KAASC,EACrCC,EAAMD,EAAQ,KAAO,iBACrBE,EAAeF,EAAQ,cAAgB,oBACvCG,EAAQX,EAAAA,mBAAqC,CAC/C,eACA,QAAS,EACT,UAAW,QACX,QAAS,MACT,QAAS,IACb,CAAC,EAEKY,EAAO,GAAGF,EAAa,QAAQD,IACjCI,EAAQ,GACRC,EAAc,GACdC,EAA8C,KAC5CC,EAAW,IAAI,IAErB,eAAeC,GAAmC,CAC9C,IAAMC,EAAUZ,EAAc,IAAIM,CAAI,EAClCM,GAAS,MAAMA,CACvB,CAEA,SAASC,GAAkB,CACnB,IAAgBlB,EAAAA,WAAW,IAC/B,EAAc,GACd,QAAQ,KACJ,0HAEJ,EACJ,CAEA,eAAemB,GAAsB,CAGjC,GAFIP,IACJ,MAAMI,EAAkB,EACpBJ,GAAO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AU,QAAQ,WAAW,CAACH,EAAUC,CAAG,CAAC,EAClD3B,EAAc,IAAIM,EAAMuB,CAAO,EAC/BA,EAAa,SAAW,CAChB7B,EAAc,IAAIM,CAAI,IAAMuB,GAAS7B,EAAc,OAAOM,CAAI,CACtE,CAAC,EACD,MAAMqB,CACV,CACJ,CACJ,C"}
|
|
1
|
+
{"version":3,"file":"offline-persistence.cjs","names":["ownerFingerprint","createOfflineStore","isDevBuild","dehydrate","require_dev_mode","require_owner_fingerprint","require_create_offline_store","_tanstack_react_query","pendingClears","currentOwner","getPrincipal","persistQueryClientOffline","options","key","databaseName","store","slot","ended","warnedEnded","timer","inFlight","afterPendingClear","pending","warnEnded","save","snapshot","queryClient","write","cancelTimer","schedule","throttleMs","onCacheEvent","event","unsubscribeCache","endSession","resetClient","previous","run","clearOptions","settled"],"sources":["../../src/query/offline-persistence.ts"],"sourcesContent":["import {\n dehydrate,\n hydrate,\n type QueryCacheNotifyEvent,\n type QueryClient,\n} from \"@tanstack/react-query\";\nimport { createOfflineStore } from \"../offline/create-offline-store\";\nimport { isDevBuild } from \"../utils/dev-mode\";\nimport { ownerFingerprint } from \"../utils/owner-fingerprint\";\n\n/**\n * Clears still running, per `databaseName` + `key` slot, across every handle.\n *\n * A handle's `clear()` deletes by key with no ordering against other handles,\n * so a new handle created on login while the previous one is still clearing\n * could `restore()` the previous user's snapshot before the delete lands, or\n * have its first write deleted by it. Every handle's `restore()` and writes\n * wait for the slot's pending clear first; the entry is dropped once settled.\n */\nconst pendingClears = new Map<string, Promise<unknown>>();\n\n/** Options for {@link persistQueryClientOffline}. */\nexport interface OfflineQueryPersistenceOptions {\n /** The `QueryClient` to snapshot and restore. */\n queryClient: QueryClient;\n /** IndexedDB database name for the snapshot. Default `\"TempestQueryCache\"`. */\n databaseName?: string;\n /** Row key under which the snapshot is stored. Default `\"tanstack-query\"`. */\n key?: string;\n /**\n * Minimum gap between snapshot writes, in ms — cache churn is coalesced into\n * one trailing write per window. Default `1000`.\n */\n throttleMs?: number;\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 on every write, which stamps the\n * snapshot with a one-way fingerprint of it (never the id itself), and on\n * `restore()`, which hydrates only a snapshot stamped with the same\n * fingerprint.\n *\n * `clear()` on logout already deletes the snapshot; this covers the session\n * that ends without it — a token that expired, a crash, a tab closed while\n * signed in. Without it, the next account to boot on the browser is shown\n * the previous account's cached responses (#531). A snapshot written before\n * this option was set carries no stamp and is not restored either; it is a\n * cache, so the cost is one cold start.\n *\n * A foreign snapshot is skipped, not deleted: a cookie app that only learns\n * the principal after a `/me` round trip would otherwise wipe its own cache\n * on every cold start. The next write replaces it.\n *\n * Read synchronously. A non-string, non-number value (the `Promise` of an\n * `async` getter) or a getter that throws reads as nobody. Omit it to restore\n * every snapshot, as before 0.82.0.\n */\n getPrincipal?: () => string | number | null | undefined;\n}\n\n/** Options for {@link OfflineQueryPersistence.clear}. */\nexport interface OfflineQueryClearOptions {\n /**\n * Also clear the in-memory `QueryClient` (`queryClient.clear()`) once\n * persistence has stopped and the snapshot is deleted — the one-call logout.\n * Default `false`: the client belongs to the app, which may want to keep\n * public queries (a catalog, feature flags) across sessions and drop only\n * the user-scoped keys with `removeQueries`.\n */\n resetClient?: boolean;\n}\n\n/** Handle returned by {@link persistQueryClientOffline}. */\nexport interface OfflineQueryPersistence {\n /**\n * Load the persisted snapshot into the `QueryClient`. Call once on boot,\n * before rendering queries, so cached data is available offline. A no-op\n * once {@link OfflineQueryPersistence.clear} has been called, and — with\n * `getPrincipal` — for a snapshot written under another principal.\n */\n restore: () => Promise<void>;\n /**\n * Write the current cache snapshot immediately (bypassing the throttle). A\n * no-op once {@link OfflineQueryPersistence.clear} has been called.\n */\n flush: () => Promise<void>;\n /** Stop persisting and drop the pending write. Idempotent. */\n unsubscribe: () => void;\n /**\n * End the persisted session (e.g. on logout) and delete the snapshot.\n *\n * Terminal for this handle: it cancels the pending throttled write, stops\n * persisting cache changes, waits for any write already in flight and only\n * then deletes the row — so neither a write pending in the last throttle\n * window nor cache activity after logout (the next user's first query) can\n * re-persist the previous user's responses. Afterwards `restore`/`flush`\n * are no-ops; to persist a new session, call\n * {@link persistQueryClientOffline} again after login. In a dev build\n * (`isDevBuild()`), the first `restore`, `flush` or added/updated query on\n * an ended handle logs one `console.warn` saying so, because a handle kept\n * at module scope would otherwise stop persisting in silence.\n *\n * Ordered against other handles on the same `databaseName` + `key`: until\n * this clear settles, a new handle's `restore()` and writes wait for it, so\n * a handle created on login without awaiting the logout neither hydrates\n * the previous snapshot nor has its first write deleted.\n *\n * If the delete rejects, `resetClient` still clears the client and the\n * rejection reaches the caller.\n *\n * The in-memory `QueryClient` is cleared only with `resetClient: true`, and\n * then only after persistence has stopped, so the reset itself cannot\n * trigger a write. It is opt-in because the app owns the client and the\n * shape of its logout: it may keep public queries and drop only the\n * user-scoped keys with `removeQueries`. Because persistence is already\n * off, that manual call can come before or after this one.\n *\n * Idempotent and safe to call concurrently; every call deletes the row\n * again.\n *\n * @param options - `resetClient` also clears the in-memory `QueryClient`.\n */\n clear: (options?: OfflineQueryClearOptions) => Promise<void>;\n}\n\ninterface Snapshot {\n id: string;\n state: ReturnType<typeof dehydrate>;\n /** Owner fingerprint when `getPrincipal` was set at write time; absent otherwise. */\n owner?: string | null;\n}\n\n/**\n * Fingerprint whoever `getPrincipal` says is signed in.\n *\n * @param getPrincipal - The app's principal getter.\n * @returns The fingerprint, or `null` for nobody, a non-identity value or a throw.\n */\nfunction currentOwner(getPrincipal: () => unknown): string | null {\n try {\n return ownerFingerprint(\"p\", getPrincipal());\n } catch {\n return null;\n }\n}\n\n/**\n * Persist a TanStack `QueryClient` cache to IndexedDB (via\n * {@link createOfflineStore}) and restore it on boot — so a reload or a cold\n * offline start shows the last-known data instead of empty screens.\n *\n * Self-contained: uses `dehydrate`/`hydrate` from `@tanstack/react-query`\n * directly, so no `@tanstack/react-query-persist-client` dependency is needed.\n * Writes are throttled and subscribe to the query cache; call `unsubscribe` on\n * teardown. Dexie is a peer dependency of the offline store — install it.\n *\n * @param options - The client plus storage/throttle configuration.\n * @returns A handle with `restore`, `flush`, `clear` and `unsubscribe`.\n *\n * `clear()` is terminal for the handle (see {@link OfflineQueryPersistence.clear}):\n * a logout that only deleted the row used to be undone by the pending write or\n * by the next cache event, restoring the previous user's data on the next boot\n * (#440).\n *\n * @example\n * const persistence = persistQueryClientOffline({ queryClient });\n * await persistence.restore();\n *\n * async function logout(): Promise<void> {\n * await persistence.clear({ resetClient: true });\n * }\n */\nexport function persistQueryClientOffline(\n options: OfflineQueryPersistenceOptions,\n): OfflineQueryPersistence {\n const { queryClient, throttleMs = 1000, getPrincipal } = options;\n const key = options.key ?? \"tanstack-query\";\n const databaseName = options.databaseName ?? \"TempestQueryCache\";\n const store = createOfflineStore<Snapshot, string>({\n databaseName,\n version: 1,\n tableName: \"cache\",\n indexes: \"&id\",\n keyPath: \"id\",\n });\n\n const slot = `${databaseName}\\u0000${key}`;\n let ended = false;\n let warnedEnded = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const inFlight = new Set<Promise<unknown>>();\n\n async function afterPendingClear(): Promise<void> {\n const pending = pendingClears.get(slot);\n if (pending) await pending;\n }\n\n function warnEnded(): void {\n if (warnedEnded || !isDevBuild()) return;\n warnedEnded = true;\n console.warn(\n \"[tempest-react-sdk] persistQueryClientOffline: handle ended by clear(); \" +\n \"create a new one after login to keep persisting.\",\n );\n }\n\n async function save(): Promise<void> {\n if (ended) return;\n await afterPendingClear();\n if (ended) return;\n const snapshot: Snapshot = { id: key, state: dehydrate(queryClient) };\n if (getPrincipal) snapshot.owner = currentOwner(getPrincipal);\n const write = store.put(snapshot);\n inFlight.add(write);\n try {\n await write;\n } finally {\n inFlight.delete(write);\n }\n }\n\n function cancelTimer(): void {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n function schedule(): void {\n if (timer || ended) return;\n timer = setTimeout(() => {\n timer = null;\n void save();\n }, throttleMs);\n }\n\n function onCacheEvent(event: QueryCacheNotifyEvent): void {\n if (!ended) {\n schedule();\n return;\n }\n if (event.type !== \"added\" && event.type !== \"updated\") return;\n unsubscribeCache();\n warnEnded();\n }\n\n const unsubscribeCache = queryClient.getQueryCache().subscribe(onCacheEvent);\n\n async function endSession(resetClient: boolean): Promise<void> {\n try {\n await Promise.allSettled([...inFlight]);\n await store.delete(key);\n } finally {\n if (resetClient) queryClient.clear();\n }\n }\n\n return {\n async restore() {\n if (ended) {\n warnEnded();\n return;\n }\n await afterPendingClear();\n if (ended) return;\n const snapshot = await store.get(key);\n if (!snapshot || ended) return;\n if (getPrincipal && snapshot.owner !== currentOwner(getPrincipal)) return;\n hydrate(queryClient, snapshot.state);\n },\n async flush() {\n if (ended) {\n warnEnded();\n return;\n }\n cancelTimer();\n await save();\n },\n unsubscribe() {\n cancelTimer();\n unsubscribeCache();\n },\n async clear(clearOptions = {}) {\n ended = true;\n cancelTimer();\n const previous = pendingClears.get(slot);\n const run = endSession(clearOptions.resetClient ?? false);\n const settled = Promise.allSettled([previous, run]);\n pendingClears.set(slot, settled);\n void settled.then(() => {\n if (pendingClears.get(slot) === settled) pendingClears.delete(slot);\n });\n await run;\n },\n };\n}\n"],"mappings":"A,6KAmBA,IAAMQ,EAAgB,IAAI,IAsH1B,SAASC,EAAa,EAA4C,CAC9D,GAAI,CACA,OAAOT,EAAAA,iBAAiB,IAAKU,EAAa,CAAC,CAC/C,MAAQ,CACJ,OAAO,IACX,CACJ,CA4BA,SAAgBC,EACZ,EACuB,CACvB,GAAM,CAAE,cAAa,aAAa,IAAM,gBAAiBC,EACnDC,EAAMD,EAAQ,KAAO,iBACrBE,EAAeF,EAAQ,cAAgB,oBACvCG,EAAQd,EAAAA,mBAAqC,CAC/C,eACA,QAAS,EACT,UAAW,QACX,QAAS,MACT,QAAS,IACb,CAAC,EAEKe,EAAO,GAAGF,EAAa,QAAQD,IACjCI,EAAQ,GACRC,EAAc,GACdC,EAA8C,KAC5CC,EAAW,IAAI,I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QAAUhB,EAAaC,CAAY,IAChE,EAAAH,EAAA,QAAA,CAAQmB,EAAaD,EAAS,KAAK,EACvC,EACA,MAAM,OAAQ,CACNR,EACAM,EAAU,GAGdK,EAAY,EACZ,MAAMJ,EAAK,EACf,EACA,aAAc,CACVI,EAAY,EACZK,EAAiB,CACrB,EACA,MAAM,MAAM,EAAe,CAAC,EAAG,CAC3B,EAAQ,GACRL,EAAY,EACZ,IAAMQ,EAAW5B,EAAc,IAAIQ,CAAI,EACjCqB,EAAMH,EAAWI,EAAa,aAAe,EAAK,EAClDC,EAAU,QAAQ,WAAW,CAACH,EAAUC,CAAG,CAAC,EAClD7B,EAAc,IAAIQ,EAAMuB,CAAO,EAC/BA,EAAa,SAAW,CAChB/B,EAAc,IAAIQ,CAAI,IAAMuB,GAAS/B,EAAc,OAAOQ,CAAI,CACtE,CAAC,EACD,MAAMqB,CACV,CACJ,CACJ,C"}
|
|
@@ -1,81 +1,91 @@
|
|
|
1
1
|
import { isDevBuild as e } from "../utils/dev-mode.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { ownerFingerprint as t } from "../utils/owner-fingerprint.js";
|
|
3
|
+
import { createOfflineStore as n } from "../offline/create-offline-store.js";
|
|
4
|
+
import { dehydrate as r, hydrate as i } from "@tanstack/react-query";
|
|
4
5
|
//#region src/query/offline-persistence.ts
|
|
5
|
-
var
|
|
6
|
-
function
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
var a = /* @__PURE__ */ new Map();
|
|
7
|
+
function o(e) {
|
|
8
|
+
try {
|
|
9
|
+
return t("p", e());
|
|
10
|
+
} catch {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function s(t) {
|
|
15
|
+
let { queryClient: s, throttleMs: c = 1e3, getPrincipal: l } = t, u = t.key ?? "tanstack-query", d = t.databaseName ?? "TempestQueryCache", f = n({
|
|
16
|
+
databaseName: d,
|
|
9
17
|
version: 1,
|
|
10
18
|
tableName: "cache",
|
|
11
19
|
indexes: "&id",
|
|
12
20
|
keyPath: "id"
|
|
13
|
-
}),
|
|
14
|
-
async function
|
|
15
|
-
let e =
|
|
21
|
+
}), p = `${d}\u0000${u}`, m = !1, h = !1, g = null, _ = /* @__PURE__ */ new Set();
|
|
22
|
+
async function v() {
|
|
23
|
+
let e = a.get(p);
|
|
16
24
|
e && await e;
|
|
17
25
|
}
|
|
18
|
-
function
|
|
19
|
-
!
|
|
26
|
+
function y() {
|
|
27
|
+
!h && e() && (h = !0, console.warn("[tempest-react-sdk] persistQueryClientOffline: handle ended by clear(); create a new one after login to keep persisting."));
|
|
20
28
|
}
|
|
21
|
-
async function
|
|
22
|
-
if (
|
|
23
|
-
let e =
|
|
24
|
-
id:
|
|
25
|
-
state:
|
|
26
|
-
}
|
|
27
|
-
|
|
29
|
+
async function b() {
|
|
30
|
+
if (m || (await v(), m)) return;
|
|
31
|
+
let e = {
|
|
32
|
+
id: u,
|
|
33
|
+
state: r(s)
|
|
34
|
+
};
|
|
35
|
+
l && (e.owner = o(l));
|
|
36
|
+
let t = f.put(e);
|
|
37
|
+
_.add(t);
|
|
28
38
|
try {
|
|
29
|
-
await
|
|
39
|
+
await t;
|
|
30
40
|
} finally {
|
|
31
|
-
|
|
41
|
+
_.delete(t);
|
|
32
42
|
}
|
|
33
43
|
}
|
|
34
|
-
function
|
|
35
|
-
|
|
44
|
+
function x() {
|
|
45
|
+
g &&= (clearTimeout(g), null);
|
|
36
46
|
}
|
|
37
|
-
function
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
},
|
|
47
|
+
function S() {
|
|
48
|
+
g || m || (g = setTimeout(() => {
|
|
49
|
+
g = null, b();
|
|
50
|
+
}, c));
|
|
41
51
|
}
|
|
42
|
-
function
|
|
43
|
-
|
|
52
|
+
function C(e) {
|
|
53
|
+
m ? (e.type === "added" || e.type === "updated") && (w(), y()) : S();
|
|
44
54
|
}
|
|
45
|
-
let
|
|
46
|
-
async function
|
|
55
|
+
let w = s.getQueryCache().subscribe(C);
|
|
56
|
+
async function T(e) {
|
|
47
57
|
try {
|
|
48
|
-
await Promise.allSettled([...
|
|
58
|
+
await Promise.allSettled([..._]), await f.delete(u);
|
|
49
59
|
} finally {
|
|
50
|
-
e &&
|
|
60
|
+
e && s.clear();
|
|
51
61
|
}
|
|
52
62
|
}
|
|
53
63
|
return {
|
|
54
64
|
async restore() {
|
|
55
|
-
if (
|
|
56
|
-
|
|
65
|
+
if (m) {
|
|
66
|
+
y();
|
|
57
67
|
return;
|
|
58
68
|
}
|
|
59
|
-
if (await
|
|
60
|
-
let e = await
|
|
61
|
-
e && !
|
|
69
|
+
if (await v(), m) return;
|
|
70
|
+
let e = await f.get(u);
|
|
71
|
+
e && !m && (l && e.owner !== o(l) || i(s, e.state));
|
|
62
72
|
},
|
|
63
73
|
async flush() {
|
|
64
|
-
|
|
74
|
+
m ? y() : (x(), await b());
|
|
65
75
|
},
|
|
66
76
|
unsubscribe() {
|
|
67
|
-
|
|
77
|
+
x(), w();
|
|
68
78
|
},
|
|
69
79
|
async clear(e = {}) {
|
|
70
|
-
|
|
71
|
-
let t =
|
|
72
|
-
|
|
73
|
-
|
|
80
|
+
m = !0, x();
|
|
81
|
+
let t = a.get(p), n = T(e.resetClient ?? !1), r = Promise.allSettled([t, n]);
|
|
82
|
+
a.set(p, r), r.then(() => {
|
|
83
|
+
a.get(p) === r && a.delete(p);
|
|
74
84
|
}), await n;
|
|
75
85
|
}
|
|
76
86
|
};
|
|
77
87
|
}
|
|
78
88
|
//#endregion
|
|
79
|
-
export {
|
|
89
|
+
export { s as persistQueryClientOffline };
|
|
80
90
|
|
|
81
91
|
//# sourceMappingURL=offline-persistence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"offline-persistence.js","names":["pendingClears","persistQueryClientOffline","options","key","databaseName","store","createOfflineStore","slot","ended","warnedEnded","timer","inFlight","afterPendingClear","pending","warnEnded","isDevBuild","save","write","dehydrate","queryClient","cancelTimer","schedule","throttleMs","onCacheEvent","event","unsubscribeCache","endSession","resetClient","snapshot","hydrate","previous","run","clearOptions","settled"],"sources":["../../src/query/offline-persistence.ts"],"sourcesContent":["import {\n dehydrate,\n hydrate,\n type QueryCacheNotifyEvent,\n type QueryClient,\n} from \"@tanstack/react-query\";\nimport { createOfflineStore } from \"../offline/create-offline-store\";\nimport { isDevBuild } from \"../utils/dev-mode\";\n\n/**\n * Clears still running, per `databaseName` + `key` slot, across every handle.\n *\n * A handle's `clear()` deletes by key with no ordering against other handles,\n * so a new handle created on login while the previous one is still clearing\n * could `restore()` the previous user's snapshot before the delete lands, or\n * have its first write deleted by it. Every handle's `restore()` and writes\n * wait for the slot's pending clear first; the entry is dropped once settled.\n */\nconst pendingClears = new Map<string, Promise<unknown>>();\n\n/** Options for {@link persistQueryClientOffline}. */\nexport interface OfflineQueryPersistenceOptions {\n /** The `QueryClient` to snapshot and restore. */\n queryClient: QueryClient;\n /** IndexedDB database name for the snapshot. Default `\"TempestQueryCache\"`. */\n databaseName?: string;\n /** Row key under which the snapshot is stored. Default `\"tanstack-query\"`. */\n key?: string;\n /**\n * Minimum gap between snapshot writes, in ms — cache churn is coalesced into\n * one trailing write per window. Default `1000`.\n */\n throttleMs?: number;\n}\n\n/** Options for {@link OfflineQueryPersistence.clear}. */\nexport interface OfflineQueryClearOptions {\n /**\n * Also clear the in-memory `QueryClient` (`queryClient.clear()`) once\n * persistence has stopped and the snapshot is deleted — the one-call logout.\n * Default `false`: the client belongs to the app, which may want to keep\n * public queries (a catalog, feature flags) across sessions and drop only\n * the user-scoped keys with `removeQueries`.\n */\n resetClient?: boolean;\n}\n\n/** Handle returned by {@link persistQueryClientOffline}. */\nexport interface OfflineQueryPersistence {\n /**\n * Load the persisted snapshot into the `QueryClient`. Call once on boot,\n * before rendering queries, so cached data is available offline. A no-op\n * once {@link OfflineQueryPersistence.clear} has been called.\n */\n restore: () => Promise<void>;\n /**\n * Write the current cache snapshot immediately (bypassing the throttle). A\n * no-op once {@link OfflineQueryPersistence.clear} has been called.\n */\n flush: () => Promise<void>;\n /** Stop persisting and drop the pending write. Idempotent. */\n unsubscribe: () => void;\n /**\n * End the persisted session (e.g. on logout) and delete the snapshot.\n *\n * Terminal for this handle: it cancels the pending throttled write, stops\n * persisting cache changes, waits for any write already in flight and only\n * then deletes the row — so neither a write pending in the last throttle\n * window nor cache activity after logout (the next user's first query) can\n * re-persist the previous user's responses. Afterwards `restore`/`flush`\n * are no-ops; to persist a new session, call\n * {@link persistQueryClientOffline} again after login. In a dev build\n * (`isDevBuild()`), the first `restore`, `flush` or added/updated query on\n * an ended handle logs one `console.warn` saying so, because a handle kept\n * at module scope would otherwise stop persisting in silence.\n *\n * Ordered against other handles on the same `databaseName` + `key`: until\n * this clear settles, a new handle's `restore()` and writes wait for it, so\n * a handle created on login without awaiting the logout neither hydrates\n * the previous snapshot nor has its first write deleted.\n *\n * If the delete rejects, `resetClient` still clears the client and the\n * rejection reaches the caller.\n *\n * The in-memory `QueryClient` is cleared only with `resetClient: true`, and\n * then only after persistence has stopped, so the reset itself cannot\n * trigger a write. It is opt-in because the app owns the client and the\n * shape of its logout: it may keep public queries and drop only the\n * user-scoped keys with `removeQueries`. Because persistence is already\n * off, that manual call can come before or after this one.\n *\n * Idempotent and safe to call concurrently; every call deletes the row\n * again.\n *\n * @param options - `resetClient` also clears the in-memory `QueryClient`.\n */\n clear: (options?: OfflineQueryClearOptions) => Promise<void>;\n}\n\ninterface Snapshot {\n id: string;\n state: ReturnType<typeof dehydrate>;\n}\n\n/**\n * Persist a TanStack `QueryClient` cache to IndexedDB (via\n * {@link createOfflineStore}) and restore it on boot — so a reload or a cold\n * offline start shows the last-known data instead of empty screens.\n *\n * Self-contained: uses `dehydrate`/`hydrate` from `@tanstack/react-query`\n * directly, so no `@tanstack/react-query-persist-client` dependency is needed.\n * Writes are throttled and subscribe to the query cache; call `unsubscribe` on\n * teardown. Dexie is a peer dependency of the offline store — install it.\n *\n * @param options - The client plus storage/throttle configuration.\n * @returns A handle with `restore`, `flush`, `clear` and `unsubscribe`.\n *\n * `clear()` is terminal for the handle (see {@link OfflineQueryPersistence.clear}):\n * a logout that only deleted the row used to be undone by the pending write or\n * by the next cache event, restoring the previous user's data on the next boot\n * (#440).\n *\n * @example\n * const persistence = persistQueryClientOffline({ queryClient });\n * await persistence.restore();\n *\n * async function logout(): Promise<void> {\n * await persistence.clear({ resetClient: true });\n * }\n */\nexport function persistQueryClientOffline(\n options: OfflineQueryPersistenceOptions,\n): OfflineQueryPersistence {\n const { queryClient, throttleMs = 1000 } = options;\n const key = options.key ?? \"tanstack-query\";\n const databaseName = options.databaseName ?? \"TempestQueryCache\";\n const store = createOfflineStore<Snapshot, string>({\n databaseName,\n version: 1,\n tableName: \"cache\",\n indexes: \"&id\",\n keyPath: \"id\",\n });\n\n const slot = `${databaseName}\\u0000${key}`;\n let ended = false;\n let warnedEnded = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const inFlight = new Set<Promise<unknown>>();\n\n async function afterPendingClear(): Promise<void> {\n const pending = pendingClears.get(slot);\n if (pending) await pending;\n }\n\n function warnEnded(): void {\n if (warnedEnded || !isDevBuild()) return;\n warnedEnded = true;\n console.warn(\n \"[tempest-react-sdk] persistQueryClientOffline: handle ended by clear(); \" +\n \"create a new one after login to keep persisting.\",\n );\n }\n\n async function save(): Promise<void> {\n if (ended) return;\n await afterPendingClear();\n if (ended) return;\n const write = store.put({ id: key, state: dehydrate(queryClient) });\n inFlight.add(write);\n try {\n await write;\n } finally {\n inFlight.delete(write);\n }\n }\n\n function cancelTimer(): void {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n function schedule(): void {\n if (timer || ended) return;\n timer = setTimeout(() => {\n timer = null;\n void save();\n }, throttleMs);\n }\n\n function onCacheEvent(event: QueryCacheNotifyEvent): void {\n if (!ended) {\n schedule();\n return;\n }\n if (event.type !== \"added\" && event.type !== \"updated\") return;\n unsubscribeCache();\n warnEnded();\n }\n\n const unsubscribeCache = queryClient.getQueryCache().subscribe(onCacheEvent);\n\n async function endSession(resetClient: boolean): Promise<void> {\n try {\n await Promise.allSettled([...inFlight]);\n await store.delete(key);\n } finally {\n if (resetClient) queryClient.clear();\n }\n }\n\n return {\n async restore() {\n if (ended) {\n warnEnded();\n return;\n }\n await afterPendingClear();\n if (ended) return;\n const snapshot = await store.get(key);\n if (snapshot && !ended) hydrate(queryClient, snapshot.state);\n },\n async flush() {\n if (ended) {\n warnEnded();\n return;\n }\n cancelTimer();\n await save();\n },\n unsubscribe() {\n cancelTimer();\n unsubscribeCache();\n },\n async clear(clearOptions = {}) {\n ended = true;\n cancelTimer();\n const previous = pendingClears.get(slot);\n const run = endSession(clearOptions.resetClient ?? false);\n const settled = Promise.allSettled([previous, run]);\n pendingClears.set(slot, settled);\n void settled.then(() => {\n if (pendingClears.get(slot) === settled) pendingClears.delete(slot);\n });\n await run;\n },\n };\n}\n"],"mappings":";;;;AAkBA,IAAMA,oBAAgB,IAAI,IAA8B;AAgHxD,SAAgBC,EACZ,GACuB;CACvB,IAAM,EAAE,gBAAa,gBAAa,QAASC,GACrCC,IAAMD,EAAQ,OAAO,kBACrBE,IAAeF,EAAQ,gBAAgB,qBACvCG,IAAQC,EAAqC;EAC/C;EACA,SAAS;EACT,WAAW;EACX,SAAS;EACT,SAAS;CACb,CAAC,GAEKC,IAAO,GAAGH,EAAa,QAAQD,KACjCK,IAAQ,IACRC,IAAc,IACdC,IAA8C,MAC5CC,oBAAW,IAAI,IAAsB;CAE3C,eAAeC,IAAmC;EAC9C,IAAMC,IAAUb,EAAc,IAAIO,CAAI;EACtC,AAAIM,KAAS,MAAMA;CACvB;CAEA,SAASC,IAAkB;EACvB,AAAI,MAAgBC,EAAW,MAC/B,IAAc,IACd,QAAQ,KACJ,0HAEJ;CACJ;CAEA,eAAeC,IAAsB;EAGjC,IAFIR,MACJ,MAAMI,EAAkB,GACpBJ,IAAO;EACX,IAAMS,IAAQZ,EAAM,IAAI;GAAE,IAAIF;GAA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AC;GAKlD,AAJA/B,EAAc,IAAIO,GAAM0B,CAAO,GAC/BA,EAAa,WAAW;IACpB,AAAIjC,EAAc,IAAIO,CAAI,MAAM0B,KAASjC,EAAc,OAAOO,CAAI;GACtE,CAAC,GACD,MAAMwB;EACV;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"offline-persistence.js","names":["pendingClears","currentOwner","ownerFingerprint","getPrincipal","persistQueryClientOffline","options","key","databaseName","store","createOfflineStore","slot","ended","warnedEnded","timer","inFlight","afterPendingClear","pending","warnEnded","isDevBuild","save","snapshot","dehydrate","queryClient","write","cancelTimer","schedule","throttleMs","onCacheEvent","event","unsubscribeCache","endSession","resetClient","hydrate","previous","run","clearOptions","settled"],"sources":["../../src/query/offline-persistence.ts"],"sourcesContent":["import {\n dehydrate,\n hydrate,\n type QueryCacheNotifyEvent,\n type QueryClient,\n} from \"@tanstack/react-query\";\nimport { createOfflineStore } from \"../offline/create-offline-store\";\nimport { isDevBuild } from \"../utils/dev-mode\";\nimport { ownerFingerprint } from \"../utils/owner-fingerprint\";\n\n/**\n * Clears still running, per `databaseName` + `key` slot, across every handle.\n *\n * A handle's `clear()` deletes by key with no ordering against other handles,\n * so a new handle created on login while the previous one is still clearing\n * could `restore()` the previous user's snapshot before the delete lands, or\n * have its first write deleted by it. Every handle's `restore()` and writes\n * wait for the slot's pending clear first; the entry is dropped once settled.\n */\nconst pendingClears = new Map<string, Promise<unknown>>();\n\n/** Options for {@link persistQueryClientOffline}. */\nexport interface OfflineQueryPersistenceOptions {\n /** The `QueryClient` to snapshot and restore. */\n queryClient: QueryClient;\n /** IndexedDB database name for the snapshot. Default `\"TempestQueryCache\"`. */\n databaseName?: string;\n /** Row key under which the snapshot is stored. Default `\"tanstack-query\"`. */\n key?: string;\n /**\n * Minimum gap between snapshot writes, in ms — cache churn is coalesced into\n * one trailing write per window. Default `1000`.\n */\n throttleMs?: number;\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 on every write, which stamps the\n * snapshot with a one-way fingerprint of it (never the id itself), and on\n * `restore()`, which hydrates only a snapshot stamped with the same\n * fingerprint.\n *\n * `clear()` on logout already deletes the snapshot; this covers the session\n * that ends without it — a token that expired, a crash, a tab closed while\n * signed in. Without it, the next account to boot on the browser is shown\n * the previous account's cached responses (#531). A snapshot written before\n * this option was set carries no stamp and is not restored either; it is a\n * cache, so the cost is one cold start.\n *\n * A foreign snapshot is skipped, not deleted: a cookie app that only learns\n * the principal after a `/me` round trip would otherwise wipe its own cache\n * on every cold start. The next write replaces it.\n *\n * Read synchronously. A non-string, non-number value (the `Promise` of an\n * `async` getter) or a getter that throws reads as nobody. Omit it to restore\n * every snapshot, as before 0.82.0.\n */\n getPrincipal?: () => string | number | null | undefined;\n}\n\n/** Options for {@link OfflineQueryPersistence.clear}. */\nexport interface OfflineQueryClearOptions {\n /**\n * Also clear the in-memory `QueryClient` (`queryClient.clear()`) once\n * persistence has stopped and the snapshot is deleted — the one-call logout.\n * Default `false`: the client belongs to the app, which may want to keep\n * public queries (a catalog, feature flags) across sessions and drop only\n * the user-scoped keys with `removeQueries`.\n */\n resetClient?: boolean;\n}\n\n/** Handle returned by {@link persistQueryClientOffline}. */\nexport interface OfflineQueryPersistence {\n /**\n * Load the persisted snapshot into the `QueryClient`. Call once on boot,\n * before rendering queries, so cached data is available offline. A no-op\n * once {@link OfflineQueryPersistence.clear} has been called, and — with\n * `getPrincipal` — for a snapshot written under another principal.\n */\n restore: () => Promise<void>;\n /**\n * Write the current cache snapshot immediately (bypassing the throttle). A\n * no-op once {@link OfflineQueryPersistence.clear} has been called.\n */\n flush: () => Promise<void>;\n /** Stop persisting and drop the pending write. Idempotent. */\n unsubscribe: () => void;\n /**\n * End the persisted session (e.g. on logout) and delete the snapshot.\n *\n * Terminal for this handle: it cancels the pending throttled write, stops\n * persisting cache changes, waits for any write already in flight and only\n * then deletes the row — so neither a write pending in the last throttle\n * window nor cache activity after logout (the next user's first query) can\n * re-persist the previous user's responses. Afterwards `restore`/`flush`\n * are no-ops; to persist a new session, call\n * {@link persistQueryClientOffline} again after login. In a dev build\n * (`isDevBuild()`), the first `restore`, `flush` or added/updated query on\n * an ended handle logs one `console.warn` saying so, because a handle kept\n * at module scope would otherwise stop persisting in silence.\n *\n * Ordered against other handles on the same `databaseName` + `key`: until\n * this clear settles, a new handle's `restore()` and writes wait for it, so\n * a handle created on login without awaiting the logout neither hydrates\n * the previous snapshot nor has its first write deleted.\n *\n * If the delete rejects, `resetClient` still clears the client and the\n * rejection reaches the caller.\n *\n * The in-memory `QueryClient` is cleared only with `resetClient: true`, and\n * then only after persistence has stopped, so the reset itself cannot\n * trigger a write. It is opt-in because the app owns the client and the\n * shape of its logout: it may keep public queries and drop only the\n * user-scoped keys with `removeQueries`. Because persistence is already\n * off, that manual call can come before or after this one.\n *\n * Idempotent and safe to call concurrently; every call deletes the row\n * again.\n *\n * @param options - `resetClient` also clears the in-memory `QueryClient`.\n */\n clear: (options?: OfflineQueryClearOptions) => Promise<void>;\n}\n\ninterface Snapshot {\n id: string;\n state: ReturnType<typeof dehydrate>;\n /** Owner fingerprint when `getPrincipal` was set at write time; absent otherwise. */\n owner?: string | null;\n}\n\n/**\n * Fingerprint whoever `getPrincipal` says is signed in.\n *\n * @param getPrincipal - The app's principal getter.\n * @returns The fingerprint, or `null` for nobody, a non-identity value or a throw.\n */\nfunction currentOwner(getPrincipal: () => unknown): string | null {\n try {\n return ownerFingerprint(\"p\", getPrincipal());\n } catch {\n return null;\n }\n}\n\n/**\n * Persist a TanStack `QueryClient` cache to IndexedDB (via\n * {@link createOfflineStore}) and restore it on boot — so a reload or a cold\n * offline start shows the last-known data instead of empty screens.\n *\n * Self-contained: uses `dehydrate`/`hydrate` from `@tanstack/react-query`\n * directly, so no `@tanstack/react-query-persist-client` dependency is needed.\n * Writes are throttled and subscribe to the query cache; call `unsubscribe` on\n * teardown. Dexie is a peer dependency of the offline store — install it.\n *\n * @param options - The client plus storage/throttle configuration.\n * @returns A handle with `restore`, `flush`, `clear` and `unsubscribe`.\n *\n * `clear()` is terminal for the handle (see {@link OfflineQueryPersistence.clear}):\n * a logout that only deleted the row used to be undone by the pending write or\n * by the next cache event, restoring the previous user's data on the next boot\n * (#440).\n *\n * @example\n * const persistence = persistQueryClientOffline({ queryClient });\n * await persistence.restore();\n *\n * async function logout(): Promise<void> {\n * await persistence.clear({ resetClient: true });\n * }\n */\nexport function persistQueryClientOffline(\n options: OfflineQueryPersistenceOptions,\n): OfflineQueryPersistence {\n const { queryClient, throttleMs = 1000, getPrincipal } = options;\n const key = options.key ?? \"tanstack-query\";\n const databaseName = options.databaseName ?? \"TempestQueryCache\";\n const store = createOfflineStore<Snapshot, string>({\n databaseName,\n version: 1,\n tableName: \"cache\",\n indexes: \"&id\",\n keyPath: \"id\",\n });\n\n const slot = `${databaseName}\\u0000${key}`;\n let ended = false;\n let warnedEnded = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const inFlight = new Set<Promise<unknown>>();\n\n async function afterPendingClear(): Promise<void> {\n const pending = pendingClears.get(slot);\n if (pending) await pending;\n }\n\n function warnEnded(): void {\n if (warnedEnded || !isDevBuild()) return;\n warnedEnded = true;\n console.warn(\n \"[tempest-react-sdk] persistQueryClientOffline: handle ended by clear(); \" +\n \"create a new one after login to keep persisting.\",\n );\n }\n\n async function save(): Promise<void> {\n if (ended) return;\n await afterPendingClear();\n if (ended) return;\n const snapshot: Snapshot = { id: key, state: dehydrate(queryClient) };\n if (getPrincipal) snapshot.owner = currentOwner(getPrincipal);\n const write = store.put(snapshot);\n inFlight.add(write);\n try {\n await write;\n } finally {\n inFlight.delete(write);\n }\n }\n\n function cancelTimer(): void {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n function schedule(): void {\n if (timer || ended) return;\n timer = setTimeout(() => {\n timer = null;\n void save();\n }, throttleMs);\n }\n\n function onCacheEvent(event: QueryCacheNotifyEvent): void {\n if (!ended) {\n schedule();\n return;\n }\n if (event.type !== \"added\" && event.type !== \"updated\") return;\n unsubscribeCache();\n warnEnded();\n }\n\n const unsubscribeCache = queryClient.getQueryCache().subscribe(onCacheEvent);\n\n async function endSession(resetClient: boolean): Promise<void> {\n try {\n await Promise.allSettled([...inFlight]);\n await store.delete(key);\n } finally {\n if (resetClient) queryClient.clear();\n }\n }\n\n return {\n async restore() {\n if (ended) {\n warnEnded();\n return;\n }\n await afterPendingClear();\n if (ended) return;\n const snapshot = await store.get(key);\n if (!snapshot || ended) return;\n if (getPrincipal && snapshot.owner !== currentOwner(getPrincipal)) return;\n hydrate(queryClient, snapshot.state);\n },\n async flush() {\n if (ended) {\n warnEnded();\n return;\n }\n cancelTimer();\n await save();\n },\n unsubscribe() {\n cancelTimer();\n unsubscribeCache();\n },\n async clear(clearOptions = {}) {\n ended = true;\n cancelTimer();\n const previous = pendingClears.get(slot);\n const run = endSession(clearOptions.resetClient ?? false);\n const settled = Promise.allSettled([previous, run]);\n pendingClears.set(slot, settled);\n void settled.then(() => {\n if (pendingClears.get(slot) === settled) pendingClears.delete(slot);\n });\n await run;\n },\n };\n}\n"],"mappings":";;;;;AAmBA,IAAMA,oBAAgB,IAAI,IAA8B;AAsHxD,SAASC,EAAa,GAA4C;CAC9D,IAAI;EACA,OAAOC,EAAiB,KAAKC,EAAa,CAAC;CAC/C,QAAQ;EACJ,OAAO;CACX;AACJ;AA4BA,SAAgBC,EACZ,GACuB;CACvB,IAAM,EAAE,gBAAa,gBAAa,KAAM,oBAAiBC,GACnDC,IAAMD,EAAQ,OAAO,kBACrBE,IAAeF,EAAQ,gBAAgB,qBACvCG,IAAQC,EAAqC;EAC/C;EACA,SAAS;EACT,WAAW;EACX,SAAS;EACT,SAAS;CACb,CAAC,GAEKC,IAAO,GAAGH,EAAa,QAAQD,KACjCK,IAAQ,IACRC,IAAc,IACdC,IAA8C,MAC5CC,oBAAW,IAAI,IAAsB;CAE3C,eAAeC,IAAmC;EAC9C,IAAMC,IAAUhB,EAAc,IAAIU,CAAI;EACtC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aF,EAAS,KAAK;EACvC;EACA,MAAM,QAAQ;GACV,AAAIT,IACAM,EAAU,KAGdO,EAAY,GACZ,MAAML,EAAK;EACf;EACA,cAAc;GAEV,AADAK,EAAY,GACZK,EAAiB;EACrB;EACA,MAAM,MAAM,IAAe,CAAC,GAAG;GAE3B,AADA,IAAQ,IACRL,EAAY;GACZ,IAAMS,IAAWjC,EAAc,IAAIU,CAAI,GACjCwB,IAAMJ,EAAWK,EAAa,eAAe,EAAK,GAClDC,IAAU,QAAQ,WAAW,CAACH,GAAUC,CAAG,CAAC;GAKlD,AAJAlC,EAAc,IAAIU,GAAM0B,CAAO,GAC/BA,EAAa,WAAW;IACpB,AAAIpC,EAAc,IAAIU,CAAI,MAAM0B,KAASpC,EAAc,OAAOU,CAAI;GACtE,CAAC,GACD,MAAMwB;EACV;CACJ;AACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../utils/json-frame.cjs");function t(t,n={}){let{withCredentials:r=!1,namedEvents:i=[],heartbeatEvents:a=[`ping`],maxRetries:o=10,initialBackoff:s=1e3,maxBackoff:c=3e4,parser:l,onOpen:u,onMessage:d,onError:f,onParseError:p,schema:m,onValidationError:h,onUrlError:g,shouldRetryUrl:_=()=>!0,onStatusChange:
|
|
1
|
+
const e=require("../utils/json-frame.cjs");function t(t,n={}){let{withCredentials:r=!1,namedEvents:i=[],heartbeatEvents:a=[`ping`],maxRetries:o=10,initialBackoff:s=1e3,maxBackoff:c=3e4,parser:l,onOpen:u,onMessage:d,onError:f,onParseError:p,schema:m,onValidationError:h,onUrlError:g,shouldRetryUrl:_=()=>!0,sessionKey:v,onStatusChange:y}=n,b=null,x=null,S=0,C=`idle`,w=!1,T=0,E;function D(e){C!==e&&(C=e,y?.(e))}function O(){return v!==void 0&&!Object.is(v(),E)}function k(t,n,r){if(t!==b||a.includes(n))return;if(O()){F();return}let i=e.decodeFrame(typeof r.data==`string`?r.data:``,`createEventStream`,{parser:l,onParseError:p,schema:m,onValidationError:h});i.delivered&&d?.({event:n,data:i.data,id:r.lastEventId||void 0,raw:r})}function A(){if(w)return;if(S>=o){D(`error`);return}let e=Math.min(s*2**S,c);S+=1,x=setTimeout(M,e)}function j(e){g?.(e),_(e)?(D(`closed`),A()):D(`error`)}function M(){if(w)return;if(b&&=(b.close(),null),D(`connecting`),T+=1,E=v?.(),typeof t==`string`){N(t);return}let e=T;Promise.resolve().then(()=>w||e!==T?null:t()).then(t=>{t===null||w||e!==T||(O()?M():N(t))},t=>{!w&&e===T&&j(t)})}function N(e){let t=new EventSource(e,{withCredentials:r});b=t,t.onopen=()=>{S=0,D(`open`),u?.()},t.onmessage=e=>k(t,`message`,e);for(let e of i)t.addEventListener(e,n=>k(t,e,n));for(let e of a)t.addEventListener(e,()=>{});t.onerror=e=>{f?.(e),t.close(),b=null,D(`closed`),A()}}function P(){w=!0,x&&=(clearTimeout(x),null),S=0,b&&=(b.close(),null),D(`closed`)}function F(){x&&=(clearTimeout(x),null),S=0,w=!1,M()}return M(),{close:P,reconnect:F,get status(){return C}}}exports.createEventStream=t;
|
|
2
2
|
//# sourceMappingURL=create-event-stream.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-event-stream.cjs","names":["decodeFrame","require_json_frame","createEventStream","options","source","retryTimer","retries","status","closed","attempt","setStatus","next","onStatusChange","emit","heartbeatEvents","eventName","decoded","event","onMessage","scheduleReconnect","maxRetries","delay","initialBackoff","maxBackoff","connect","failUrl","onUrlError","error","shouldRetryUrl","url","open","current","resolved","es","target","onOpen","name","namedEvents","onError","close","reconnect"],"sources":["../../src/sse/create-event-stream.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — the body is the SSE line protocol — accumulate\n * `data:` lines until a blank line, track `id:` for Last-Event-ID, honour `retry:` —\n * plus the reconnect that uses the id it just tracked.\n */\nimport { decodeFrame } from \"../utils/json-frame\";\nimport type { SchemaIssue, SchemaLike } from \"../utils/schema-like\";\nexport type EventStreamStatus = \"idle\" | \"connecting\" | \"open\" | \"closed\" | \"error\";\n\n/**\n * Where the stream connects: a fixed URL, or a function resolved again before\n * every connection, the first one and each reconnect.\n *\n * The function form exists for short-lived credentials carried in the URL,\n * such as the `?ticket=` of the `tempest-fastapi-sdk` SSE router. `EventSource`\n * cannot send headers, so the credential has to ride in the query, and one that\n * expires makes a fixed URL a trap: the reconnect after the expiry presents the\n * same dead credential, gets a `401`, and burns every retry on it while the user\n * is still signed in.\n */\nexport type EventStreamUrl = string | (() => string | Promise<string>);\n\nexport interface EventStreamMessage<T> {\n /** Server-named event (default `\"message\"`). */\n event: string;\n /** Parsed payload — validated when `schema` is set, JSON-decoded when possible, raw string otherwise. */\n data: T;\n /** Server-supplied id, if any. */\n id?: string;\n /** Raw `MessageEvent` for advanced cases. */\n raw: MessageEvent;\n}\n\nexport interface CreateEventStreamOptions<T> {\n /** Send cookies with the EventSource handshake. Default: false. */\n withCredentials?: boolean;\n /** Subscribe to named events in addition to `message`. */\n namedEvents?: readonly string[];\n /** Treat these named events as heartbeat-only (no callback). Default: `[\"ping\"]`. */\n heartbeatEvents?: readonly string[];\n /** Max reconnect attempts. Default: 10. Pass 0 to disable reconnect. */\n maxRetries?: number;\n /** Initial backoff in ms; doubles per attempt, capped at `maxBackoff`. Default: 1000. */\n initialBackoff?: number;\n /** Maximum backoff in ms. Default: 30000. */\n maxBackoff?: number;\n /** Parse `event.data`. Defaults to JSON with raw-string fallback. */\n parser?: (raw: string) => T;\n /**\n * A frame arrived that is not valid JSON, and no `parser` was supplied.\n *\n * Registering this drops the frame instead of delivering it: the previous\n * behaviour handed `onMessage` the raw `string` announced as your message\n * type, so the failure surfaced later, at the first property access, with\n * nothing left pointing at the parse. Leave it out and that behaviour is\n * kept, with a one-time warning in development builds.\n */\n onParseError?: (error: unknown, raw: string) => void;\n /**\n * Schema every decoded frame must satisfy, from zod, valibot, arktype or\n * anything else exposing `~standard` or `.safeParse`.\n *\n * Without it nothing changes: the payload reaches `onMessage` announced as\n * `T` on the strength of the type argument alone, which is a promise about\n * the server that TypeScript cannot keep. With it, a frame that does not\n * match is **not** delivered — the same rule `onParseError` already follows —\n * and `onValidationError` hears why. The value delivered is the schema's\n * output, so coercions and defaults are honoured.\n *\n * When `parser` is also supplied, it decodes first and the schema validates\n * what it returned.\n *\n * The validation must be synchronous. A frame is decoded inside the\n * `message` handler and delivered from it, so an async schema would deliver\n * frames in whatever order their validations settled; that case is reported\n * through `onValidationError` instead of awaited.\n */\n schema?: SchemaLike<T>;\n /**\n * A frame was decoded but the `schema` refused it, so it was dropped.\n *\n * The one signal that does not depend on how the app's bundler resolves\n * `process`: the one-time development warning behind `onParseError` needs\n * `isDevBuild()` to be able to answer, and this callback is the app's own.\n */\n onValidationError?: (issues: SchemaIssue[], raw: string) => void;\n /**\n * The URL function threw or rejected, so no connection was attempted.\n *\n * `onError` cannot carry this: it receives the `EventSource` `Event`, and a\n * URL that never resolved never had an `EventSource`.\n */\n onUrlError?: (error: unknown) => void;\n /**\n * Whether a URL-resolution failure is worth another attempt. Default: always.\n *\n * Return `false` for failures no backoff can fix — a `401` or a `403` when\n * fetching a ticket is a session decision, not a network blip — and the stream\n * stops at `status: \"error\"` instead of spending `maxRetries` on it.\n */\n shouldRetryUrl?: (error: unknown) => boolean;\n onOpen?: () => void;\n onMessage?: (message: EventStreamMessage<T>) => void;\n onError?: (error: Event) => void;\n onStatusChange?: (status: EventStreamStatus) => void;\n}\n\nexport interface EventStreamController {\n close: () => void;\n /** Force an immediate reconnect, resetting the retry counter. */\n reconnect: () => void;\n /** Current connection status. */\n readonly status: EventStreamStatus;\n}\n\n/**\n * Open a Server-Sent Events stream with automatic exponential-backoff reconnect.\n *\n * Heartbeat events (default `\"ping\"`) keep the socket alive without firing\n * `onMessage`. Pass `withCredentials: true` when the backend authenticates via\n * cookies. Call `close()` from the returned controller to tear down.\n *\n * When `url` is a function it is called before every connection, so a\n * reconnect presents a fresh credential instead of the one that expired. A\n * resolution still pending when `close()` or `reconnect()` runs is discarded.\n *\n * @param url - Full SSE endpoint URL, or a function returning it per connection.\n * @param options - Stream configuration and callbacks.\n * @returns A controller exposing `close`, `reconnect` and the current `status`.\n */\nexport function createEventStream<T = unknown>(\n url: EventStreamUrl,\n options: CreateEventStreamOptions<T> = {},\n): EventStreamController {\n const {\n withCredentials = false,\n namedEvents = [],\n heartbeatEvents = [\"ping\"],\n maxRetries = 10,\n initialBackoff = 1000,\n maxBackoff = 30000,\n parser,\n onOpen,\n onMessage,\n onError,\n onParseError,\n schema,\n onValidationError,\n onUrlError,\n shouldRetryUrl = () => true,\n onStatusChange,\n } = options;\n\n let source: EventSource | null = null;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let retries = 0;\n let status: EventStreamStatus = \"idle\";\n let closed = false;\n let attempt = 0;\n\n function setStatus(next: EventStreamStatus): void {\n if (status === next) return;\n status = next;\n onStatusChange?.(next);\n }\n\n function emit(eventName: string, event: MessageEvent): void {\n if (heartbeatEvents.includes(eventName)) return;\n const decoded = decodeFrame<T>(\n typeof event.data === \"string\" ? event.data : \"\",\n \"createEventStream\",\n { parser, onParseError, schema, onValidationError },\n );\n if (!decoded.delivered) return;\n onMessage?.({\n event: eventName,\n data: decoded.data,\n id: event.lastEventId || undefined,\n raw: event,\n });\n }\n\n function scheduleReconnect(): void {\n if (closed) return;\n if (retries >= maxRetries) {\n setStatus(\"error\");\n return;\n }\n const delay = Math.min(initialBackoff * 2 ** retries, maxBackoff);\n retries += 1;\n retryTimer = setTimeout(connect, delay);\n }\n\n function failUrl(error: unknown): void {\n onUrlError?.(error);\n if (!shouldRetryUrl(error)) {\n setStatus(\"error\");\n return;\n }\n setStatus(\"closed\");\n scheduleReconnect();\n }\n\n function connect(): void {\n if (closed) return;\n if (source) {\n source.close();\n source = null;\n }\n setStatus(\"connecting\");\n attempt += 1;\n if (typeof url === \"string\") {\n open(url);\n return;\n }\n const current = attempt;\n Promise.resolve()\n .then(url)\n .then(\n (resolved) => {\n if (!closed && current === attempt) open(resolved);\n },\n (error: unknown) => {\n if (!closed && current === attempt) failUrl(error);\n },\n );\n }\n\n function open(target: string): void {\n const es = new EventSource(target, { withCredentials });\n source = es;\n\n es.onopen = () => {\n retries = 0;\n setStatus(\"open\");\n onOpen?.();\n };\n\n es.onmessage = (event) => emit(\"message\", event);\n for (const name of namedEvents) {\n es.addEventListener(name, (event) => emit(name, event as MessageEvent));\n }\n for (const name of heartbeatEvents) {\n es.addEventListener(name, () => {\n /* heartbeat — keep socket alive */\n });\n }\n\n es.onerror = (event) => {\n onError?.(event);\n es.close();\n source = null;\n setStatus(\"closed\");\n scheduleReconnect();\n };\n }\n\n function close(): void {\n closed = true;\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n retries = 0;\n if (source) {\n source.close();\n source = null;\n }\n setStatus(\"closed\");\n }\n\n function reconnect(): void {\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n retries = 0;\n closed = false;\n connect();\n }\n\n connect();\n\n return {\n close,\n reconnect,\n get status() {\n return status;\n },\n };\n}\n"],"mappings":"A,2CAkIA,SAAgBE,EACZ,EACA,EAAuC,CAAC,EACnB,CACrB,GAAM,CACF,kBAAkB,GAClB,cAAc,CAAC,EACf,kBAAkB,CAAC,MAAM,EACzB,aAAa,GACb,iBAAiB,IACjB,aAAa,IACb,SACA,SACA,YACA,UACA,eACA,SACA,oBACA,aACA,qBAAuB,GACvB,kBACAC,EAEAC,EAA6B,KAC7BC,EAAmD,KACnDC,EAAU,EACVC,EAA4B,OAC5BC,EAAS,GACTC,EAAU,EAEd,SAASC,EAAU,EAA+B,CAC1CH,IAAWI,IACf,EAASA,EACTC,IAAiBD,CAAI,EACzB,CAEA,SAASE,EAAK,EAAmB,EAA2B,CACxD,GAAIC,EAAgB,SAASC,CAAS,EAAG,OACzC,IAAMC,EAAUhB,EAAAA,YACZ,OAAOiB,EAAM,MAAS,SAAWA,EAAM,KAAO,GAC9C,oBACA,CAAE,SAAQ,eAAc,SAAQ,mBAA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,CAAC,EAGL,EAAG,QAAW,GAAU,CACpBE,IAAUrB,CAAK,EACfgB,EAAG,MAAM,EACT,EAAS,KACTvB,EAAU,QAAQ,EAClBS,EAAkB,CACtB,CACJ,CAEA,SAASoB,GAAc,CACnB,EAAS,GACT,AAEIlC,KADA,aAAaA,CAAU,EACV,MAEjB,EAAU,EACV,AAEID,KADAA,EAAO,MAAM,EACJ,MAEbM,EAAU,QAAQ,CACtB,CAEA,SAAS8B,GAAkB,CACvB,AAEInC,KADA,aAAaA,CAAU,EACV,MAEjB,EAAU,EACV,EAAS,GACTmB,EAAQ,CACZ,CAIA,OAFAA,EAAQ,EAED,CACH,QACA,YACA,IAAI,QAAS,CACT,OAAOjB,CACX,CACJ,CACJ,C"}
|
|
1
|
+
{"version":3,"file":"create-event-stream.cjs","names":["decodeFrame","require_json_frame","createEventStream","options","source","retryTimer","retries","status","closed","attempt","boundKey","setStatus","next","onStatusChange","sessionChanged","sessionKey","emit","from","heartbeatEvents","eventName","reconnect","decoded","event","onMessage","scheduleReconnect","maxRetries","delay","initialBackoff","maxBackoff","connect","failUrl","onUrlError","error","shouldRetryUrl","url","open","current","resolved","es","target","onOpen","name","namedEvents","onError","close"],"sources":["../../src/sse/create-event-stream.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — the body is the SSE line protocol — accumulate\n * `data:` lines until a blank line, track `id:` for Last-Event-ID, honour `retry:` —\n * plus the reconnect that uses the id it just tracked.\n */\nimport { decodeFrame } from \"../utils/json-frame\";\nimport type { SchemaIssue, SchemaLike } from \"../utils/schema-like\";\nexport type EventStreamStatus = \"idle\" | \"connecting\" | \"open\" | \"closed\" | \"error\";\n\n/**\n * Where the stream connects: a fixed URL, or a function resolved again before\n * every connection, the first one and each reconnect.\n *\n * The function form exists for short-lived credentials carried in the URL,\n * such as the `?ticket=` of the `tempest-fastapi-sdk` SSE router. `EventSource`\n * cannot send headers, so the credential has to ride in the query, and one that\n * expires makes a fixed URL a trap: the reconnect after the expiry presents the\n * same dead credential, gets a `401`, and burns every retry on it while the user\n * is still signed in.\n */\nexport type EventStreamUrl = string | (() => string | Promise<string>);\n\n/**\n * Identifies the session a stream belongs to: the signed-in user's id, an\n * auth epoch, `null` when signed out.\n *\n * A primitive on purpose. The hook form lists it in its effect dependencies,\n * and an object built inline would be a new identity on every render, so the\n * stream would reopen on every render.\n */\nexport type SessionKey = string | number | boolean | null | undefined;\n\nexport interface EventStreamMessage<T> {\n /** Server-named event (default `\"message\"`). */\n event: string;\n /** Parsed payload — validated when `schema` is set, JSON-decoded when possible, raw string otherwise. */\n data: T;\n /** Server-supplied id, if any. */\n id?: string;\n /** Raw `MessageEvent` for advanced cases. */\n raw: MessageEvent;\n}\n\nexport interface CreateEventStreamOptions<T> {\n /** Send cookies with the EventSource handshake. Default: false. */\n withCredentials?: boolean;\n /** Subscribe to named events in addition to `message`. */\n namedEvents?: readonly string[];\n /** Treat these named events as heartbeat-only (no callback). Default: `[\"ping\"]`. */\n heartbeatEvents?: readonly string[];\n /** Max reconnect attempts. Default: 10. Pass 0 to disable reconnect. */\n maxRetries?: number;\n /** Initial backoff in ms; doubles per attempt, capped at `maxBackoff`. Default: 1000. */\n initialBackoff?: number;\n /** Maximum backoff in ms. Default: 30000. */\n maxBackoff?: number;\n /** Parse `event.data`. Defaults to JSON with raw-string fallback. */\n parser?: (raw: string) => T;\n /**\n * A frame arrived that is not valid JSON, and no `parser` was supplied.\n *\n * Registering this drops the frame instead of delivering it: the previous\n * behaviour handed `onMessage` the raw `string` announced as your message\n * type, so the failure surfaced later, at the first property access, with\n * nothing left pointing at the parse. Leave it out and that behaviour is\n * kept, with a one-time warning in development builds.\n */\n onParseError?: (error: unknown, raw: string) => void;\n /**\n * Schema every decoded frame must satisfy, from zod, valibot, arktype or\n * anything else exposing `~standard` or `.safeParse`.\n *\n * Without it nothing changes: the payload reaches `onMessage` announced as\n * `T` on the strength of the type argument alone, which is a promise about\n * the server that TypeScript cannot keep. With it, a frame that does not\n * match is **not** delivered — the same rule `onParseError` already follows —\n * and `onValidationError` hears why. The value delivered is the schema's\n * output, so coercions and defaults are honoured.\n *\n * When `parser` is also supplied, it decodes first and the schema validates\n * what it returned.\n *\n * The validation must be synchronous. A frame is decoded inside the\n * `message` handler and delivered from it, so an async schema would deliver\n * frames in whatever order their validations settled; that case is reported\n * through `onValidationError` instead of awaited.\n */\n schema?: SchemaLike<T>;\n /**\n * A frame was decoded but the `schema` refused it, so it was dropped.\n *\n * The one signal that does not depend on how the app's bundler resolves\n * `process`: the one-time development warning behind `onParseError` needs\n * `isDevBuild()` to be able to answer, and this callback is the app's own.\n */\n onValidationError?: (issues: SchemaIssue[], raw: string) => void;\n /**\n * The URL function threw or rejected, so no connection was attempted.\n *\n * `onError` cannot carry this: it receives the `EventSource` `Event`, and a\n * URL that never resolved never had an `EventSource`.\n */\n onUrlError?: (error: unknown) => void;\n /**\n * Read the current session key; the stream belongs to the session that was\n * current when it connected.\n *\n * The server cannot end the stream for you. The `tempest-fastapi-sdk` SSE\n * router checks the ticket only when the stream opens, and neither logout\n * nor refresh-token revocation touches an open stream: it lives until the\n * client leaves. So a tab that switches from user A to user B without\n * closing the stream keeps receiving A's events under B.\n *\n * With this set, the key is read when each connection starts, again when\n * its URL resolved, and before every frame is delivered. A frame that\n * arrives after the key changed is dropped, never delivered, and the stream\n * reconnects for the session now current — with a fresh ticket, for the\n * ticket stream. A URL resolved while the key changed is discarded the same\n * way, since the ticket inside it may belong to either session.\n *\n * The check runs when a frame arrives: a stream that stays quiet holds its\n * connection until the next frame or until `close()`. The hook form closes\n * it as soon as the key changes.\n *\n * Keys are compared with `Object.is`. Leave it out and nothing changes.\n */\n sessionKey?: () => SessionKey;\n /**\n * Whether a URL-resolution failure is worth another attempt. Default: always.\n *\n * Return `false` for failures no backoff can fix — a `401` or a `403` when\n * fetching a ticket is a session decision, not a network blip — and the stream\n * stops at `status: \"error\"` instead of spending `maxRetries` on it.\n */\n shouldRetryUrl?: (error: unknown) => boolean;\n onOpen?: () => void;\n onMessage?: (message: EventStreamMessage<T>) => void;\n onError?: (error: Event) => void;\n onStatusChange?: (status: EventStreamStatus) => void;\n}\n\nexport interface EventStreamController {\n close: () => void;\n /** Force an immediate reconnect, resetting the retry counter. */\n reconnect: () => void;\n /** Current connection status. */\n readonly status: EventStreamStatus;\n}\n\n/**\n * Open a Server-Sent Events stream with automatic exponential-backoff reconnect.\n *\n * Heartbeat events (default `\"ping\"`) keep the socket alive without firing\n * `onMessage`. Pass `withCredentials: true` when the backend authenticates via\n * cookies. Call `close()` from the returned controller to tear down.\n *\n * When `url` is a function it is called before every connection, so a\n * reconnect presents a fresh credential instead of the one that expired. A\n * resolution still pending when `close()` or `reconnect()` runs is discarded, and\n * one that has not started yet is never made: a stream closed in the same tick\n * it was created asks for no URL — no ticket request, for the ticket stream.\n *\n * Pass `sessionKey` to bind the stream to the session it opened under: once\n * the key changes, no frame of the previous session reaches `onMessage`, and\n * the stream reconnects for the new one.\n *\n * @param url - Full SSE endpoint URL, or a function returning it per connection.\n * @param options - Stream configuration and callbacks.\n * @returns A controller exposing `close`, `reconnect` and the current `status`.\n */\nexport function createEventStream<T = unknown>(\n url: EventStreamUrl,\n options: CreateEventStreamOptions<T> = {},\n): EventStreamController {\n const {\n withCredentials = false,\n namedEvents = [],\n heartbeatEvents = [\"ping\"],\n maxRetries = 10,\n initialBackoff = 1000,\n maxBackoff = 30000,\n parser,\n onOpen,\n onMessage,\n onError,\n onParseError,\n schema,\n onValidationError,\n onUrlError,\n shouldRetryUrl = () => true,\n sessionKey,\n onStatusChange,\n } = options;\n\n let source: EventSource | null = null;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let retries = 0;\n let status: EventStreamStatus = \"idle\";\n let closed = false;\n let attempt = 0;\n let boundKey: SessionKey;\n\n function setStatus(next: EventStreamStatus): void {\n if (status === next) return;\n status = next;\n onStatusChange?.(next);\n }\n\n function sessionChanged(): boolean {\n return sessionKey !== undefined && !Object.is(sessionKey(), boundKey);\n }\n\n /**\n * Deliver one frame, unless it no longer belongs to this stream.\n *\n * A frame from a source other than the current one — closed by `close()`,\n * replaced by a reconnect — is ignored: it would otherwise reach `onMessage`\n * after the caller let go of the stream, and the session check below would\n * reopen a controller that `close()` already ended. A frame that arrives\n * after `sessionKey` changed is dropped and the stream reconnects for the\n * session now current.\n *\n * @param from - The `EventSource` the frame came from.\n * @param eventName - The SSE event name.\n * @param event - The raw message event.\n */\n function emit(from: EventSource, eventName: string, event: MessageEvent): void {\n if (from !== source || heartbeatEvents.includes(eventName)) return;\n if (sessionChanged()) {\n reconnect();\n return;\n }\n const decoded = decodeFrame<T>(\n typeof event.data === \"string\" ? event.data : \"\",\n \"createEventStream\",\n { parser, onParseError, schema, onValidationError },\n );\n if (!decoded.delivered) return;\n onMessage?.({\n event: eventName,\n data: decoded.data,\n id: event.lastEventId || undefined,\n raw: event,\n });\n }\n\n function scheduleReconnect(): void {\n if (closed) return;\n if (retries >= maxRetries) {\n setStatus(\"error\");\n return;\n }\n const delay = Math.min(initialBackoff * 2 ** retries, maxBackoff);\n retries += 1;\n retryTimer = setTimeout(connect, delay);\n }\n\n function failUrl(error: unknown): void {\n onUrlError?.(error);\n if (!shouldRetryUrl(error)) {\n setStatus(\"error\");\n return;\n }\n setStatus(\"closed\");\n scheduleReconnect();\n }\n\n function connect(): void {\n if (closed) return;\n if (source) {\n source.close();\n source = null;\n }\n setStatus(\"connecting\");\n attempt += 1;\n boundKey = sessionKey?.();\n if (typeof url === \"string\") {\n open(url);\n return;\n }\n const current = attempt;\n Promise.resolve()\n .then(() => (closed || current !== attempt ? null : url()))\n .then(\n (resolved) => {\n if (resolved === null || closed || current !== attempt) return;\n if (sessionChanged()) {\n connect();\n return;\n }\n open(resolved);\n },\n (error: unknown) => {\n if (!closed && current === attempt) failUrl(error);\n },\n );\n }\n\n function open(target: string): void {\n const es = new EventSource(target, { withCredentials });\n source = es;\n\n es.onopen = () => {\n retries = 0;\n setStatus(\"open\");\n onOpen?.();\n };\n\n es.onmessage = (event) => emit(es, \"message\", event);\n for (const name of namedEvents) {\n es.addEventListener(name, (event) => emit(es, name, event as MessageEvent));\n }\n for (const name of heartbeatEvents) {\n es.addEventListener(name, () => {\n /* heartbeat — keep socket alive */\n });\n }\n\n es.onerror = (event) => {\n onError?.(event);\n es.close();\n source = null;\n setStatus(\"closed\");\n scheduleReconnect();\n };\n }\n\n function close(): void {\n closed = true;\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n retries = 0;\n if (source) {\n source.close();\n source = null;\n }\n setStatus(\"closed\");\n }\n\n function reconnect(): void {\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n retries = 0;\n closed = false;\n connect();\n }\n\n connect();\n\n return {\n close,\n reconnect,\n get status() {\n return status;\n },\n };\n}\n"],"mappings":"A,2CA0KA,SAAgBE,EACZ,EACA,EAAuC,CAAC,EACnB,CACrB,GAAM,CACF,kBAAkB,GAClB,cAAc,CAAC,EACf,kBAAkB,CAAC,MAAM,EACzB,aAAa,GACb,iBAAiB,IACjB,aAAa,IACb,SACA,SACA,YACA,UACA,eACA,SACA,oBACA,aACA,qBAAuB,GACvB,aACA,kBACAC,EAEAC,EAA6B,KAC7BC,EAAmD,KACnDC,EAAU,EACVC,EAA4B,OAC5BC,EAAS,GACTC,EAAU,EACVC,EAEJ,SAASC,EAAU,EAA+B,CAC1CJ,IAAWK,IACf,EAASA,EACTC,IAAiBD,CAAI,EACzB,CAEA,SAASE,GAA0B,CAC/B,OAAOC,IAAe,IAAA,IAAa,CAAC,OAAO,GAAGA,EAAW,EAAGL,CAAQ,CACxE,CAgBA,SAASM,EAAK,EAAmB,EAAmB,EAA2B,CAC3E,GAAIC,IAASb,GAAUc,EAAgB,SAASC,CAAS,EAAG,OAC5D,GAAIL,EAAe,EAAG,CAClBM,EAAU,EACV,MACJ,CACA,IAAMC,EAAUrB,EAAAA,YACZ,OAAOsB,EAAM,MAAS,SAAWA,EAAM,KAAO,GAC9C,oBACA,CAAE,S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