@rocicorp/zero 1.10.0-canary.24 → 1.10.0-canary.26
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/out/analyze-query/src/bin-analyze.js +8 -9
- package/out/analyze-query/src/bin-analyze.js.map +1 -1
- package/out/replicache/src/btree/node.d.ts.map +1 -1
- package/out/replicache/src/btree/node.js +6 -3
- package/out/replicache/src/btree/node.js.map +1 -1
- package/out/replicache/src/btree/read.d.ts +1 -12
- package/out/replicache/src/btree/read.d.ts.map +1 -1
- package/out/replicache/src/btree/read.js +12 -24
- package/out/replicache/src/btree/read.js.map +1 -1
- package/out/replicache/src/dag/gc.d.ts.map +1 -1
- package/out/replicache/src/dag/gc.js +11 -8
- package/out/replicache/src/dag/gc.js.map +1 -1
- package/out/replicache/src/dag/store-impl.d.ts +2 -12
- package/out/replicache/src/dag/store-impl.d.ts.map +1 -1
- package/out/replicache/src/dag/store-impl.js +8 -22
- package/out/replicache/src/dag/store-impl.js.map +1 -1
- package/out/replicache/src/db/rebase.d.ts +2 -14
- package/out/replicache/src/db/rebase.d.ts.map +1 -1
- package/out/replicache/src/db/rebase.js +5 -27
- package/out/replicache/src/db/rebase.js.map +1 -1
- package/out/replicache/src/db/write.js.map +1 -1
- package/out/replicache/src/kv/expo-sqlite/store.d.ts.map +1 -1
- package/out/replicache/src/kv/expo-sqlite/store.js +5 -28
- package/out/replicache/src/kv/expo-sqlite/store.js.map +1 -1
- package/out/replicache/src/kv/idb-store-with-mem-fallback.d.ts +5 -15
- package/out/replicache/src/kv/idb-store-with-mem-fallback.d.ts.map +1 -1
- package/out/replicache/src/kv/idb-store-with-mem-fallback.js +25 -25
- package/out/replicache/src/kv/idb-store-with-mem-fallback.js.map +1 -1
- package/out/replicache/src/kv/idb-store.d.ts +0 -9
- package/out/replicache/src/kv/idb-store.d.ts.map +1 -1
- package/out/replicache/src/kv/idb-store.js +2 -14
- package/out/replicache/src/kv/idb-store.js.map +1 -1
- package/out/replicache/src/kv/mem-store.d.ts +0 -1
- package/out/replicache/src/kv/mem-store.d.ts.map +1 -1
- package/out/replicache/src/kv/mem-store.js +0 -3
- package/out/replicache/src/kv/mem-store.js.map +1 -1
- package/out/replicache/src/kv/op-sqlite/store.d.ts.map +1 -1
- package/out/replicache/src/kv/op-sqlite/store.js +1 -1
- package/out/replicache/src/kv/op-sqlite/store.js.map +1 -1
- package/out/replicache/src/kv/sqlite-store.d.ts +1 -13
- package/out/replicache/src/kv/sqlite-store.d.ts.map +1 -1
- package/out/replicache/src/kv/sqlite-store.js +6 -73
- package/out/replicache/src/kv/sqlite-store.js.map +1 -1
- package/out/replicache/src/kv/store.d.ts +0 -6
- package/out/replicache/src/kv/store.d.ts.map +1 -1
- package/out/replicache/src/persist/collect-idb-databases.d.ts +5 -10
- package/out/replicache/src/persist/collect-idb-databases.d.ts.map +1 -1
- package/out/replicache/src/persist/collect-idb-databases.js +9 -16
- package/out/replicache/src/persist/collect-idb-databases.js.map +1 -1
- package/out/replicache/src/persist/persist.d.ts.map +1 -1
- package/out/replicache/src/persist/persist.js +6 -13
- package/out/replicache/src/persist/persist.js.map +1 -1
- package/out/replicache/src/persist/refresh.js +2 -6
- package/out/replicache/src/persist/refresh.js.map +1 -1
- package/out/replicache/src/replicache-impl.d.ts +3 -14
- package/out/replicache/src/replicache-impl.d.ts.map +1 -1
- package/out/replicache/src/replicache-impl.js +11 -118
- package/out/replicache/src/replicache-impl.js.map +1 -1
- package/out/replicache/src/replicache-options.d.ts +0 -9
- package/out/replicache/src/replicache-options.d.ts.map +1 -1
- package/out/replicache/src/transactions.d.ts.map +1 -1
- package/out/replicache/src/transactions.js +1 -1
- package/out/replicache/src/transactions.js.map +1 -1
- package/out/shared/src/arrays.d.ts +0 -5
- package/out/shared/src/arrays.d.ts.map +1 -1
- package/out/shared/src/arrays.js +24 -8
- package/out/shared/src/arrays.js.map +1 -1
- package/out/shared/src/base64.d.ts +19 -0
- package/out/shared/src/base64.d.ts.map +1 -0
- package/out/shared/src/base64.js +40 -0
- package/out/shared/src/base64.js.map +1 -0
- package/out/shared/src/error.d.ts +0 -11
- package/out/shared/src/error.d.ts.map +1 -1
- package/out/shared/src/error.js +1 -35
- package/out/shared/src/error.js.map +1 -1
- package/out/shared/src/hash.d.ts +0 -1
- package/out/shared/src/hash.d.ts.map +1 -1
- package/out/shared/src/hash.js +10 -87
- package/out/shared/src/hash.js.map +1 -1
- package/out/shared/src/iterables.d.ts +0 -2
- package/out/shared/src/iterables.d.ts.map +1 -1
- package/out/shared/src/iterables.js +1 -18
- package/out/shared/src/iterables.js.map +1 -1
- package/out/shared/src/json.d.ts.map +1 -1
- package/out/shared/src/json.js +2 -2
- package/out/shared/src/json.js.map +1 -1
- package/out/shared/src/map.d.ts +2 -24
- package/out/shared/src/map.d.ts.map +1 -1
- package/out/shared/src/map.js +4 -18
- package/out/shared/src/map.js.map +1 -1
- package/out/shared/src/ring-buffer.d.ts +0 -8
- package/out/shared/src/ring-buffer.d.ts.map +1 -1
- package/out/shared/src/ring-buffer.js +1 -22
- package/out/shared/src/ring-buffer.js.map +1 -1
- package/out/z2s/src/sql.d.ts.map +1 -1
- package/out/z2s/src/sql.js +2 -2
- package/out/z2s/src/sql.js.map +1 -1
- package/out/zero/package.js +3 -2
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/auth/read-authorizer.js +1 -1
- package/out/zero-cache/src/auth/write-authorizer.d.ts.map +1 -1
- package/out/zero-cache/src/auth/write-authorizer.js +0 -1
- package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +2 -42
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +28 -149
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/custom-queries/transform-query.js +1 -1
- package/out/zero-cache/src/db/create.d.ts.map +1 -1
- package/out/zero-cache/src/db/create.js +1 -4
- package/out/zero-cache/src/db/create.js.map +1 -1
- package/out/zero-cache/src/db/lite-tables.d.ts +2 -10
- package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
- package/out/zero-cache/src/db/lite-tables.js +6 -10
- package/out/zero-cache/src/db/lite-tables.js.map +1 -1
- package/out/zero-cache/src/db/specs.d.ts +0 -41
- package/out/zero-cache/src/db/specs.d.ts.map +1 -1
- package/out/zero-cache/src/db/specs.js +3 -30
- package/out/zero-cache/src/db/specs.js.map +1 -1
- package/out/zero-cache/src/observability/metrics.d.ts.map +1 -1
- package/out/zero-cache/src/observability/metrics.js +7 -2
- package/out/zero-cache/src/observability/metrics.js.map +1 -1
- package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/server/change-streamer.js +4 -13
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/server/inspector-delegate.d.ts +2 -18
- package/out/zero-cache/src/server/inspector-delegate.d.ts.map +1 -1
- package/out/zero-cache/src/server/inspector-delegate.js +17 -25
- package/out/zero-cache/src/server/inspector-delegate.js.map +1 -1
- package/out/zero-cache/src/server/main.d.ts.map +1 -1
- package/out/zero-cache/src/server/main.js +1 -8
- package/out/zero-cache/src/server/main.js.map +1 -1
- package/out/zero-cache/src/server/mutator.js +0 -2
- package/out/zero-cache/src/server/mutator.js.map +1 -1
- package/out/zero-cache/src/server/reaper.d.ts.map +1 -1
- package/out/zero-cache/src/server/reaper.js +0 -2
- package/out/zero-cache/src/server/reaper.js.map +1 -1
- package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/server/replicator.js +2 -8
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/server/runner/zero-dispatcher.d.ts.map +1 -1
- package/out/zero-cache/src/server/runner/zero-dispatcher.js +0 -3
- package/out/zero-cache/src/server/runner/zero-dispatcher.js.map +1 -1
- package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/server/syncer.js +1 -5
- package/out/zero-cache/src/server/syncer.js.map +1 -1
- package/out/zero-cache/src/services/analyze.d.ts.map +1 -1
- package/out/zero-cache/src/services/analyze.js +9 -11
- package/out/zero-cache/src/services/analyze.js.map +1 -1
- package/out/zero-cache/src/services/change-source/common/backfill-manager.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/backfill-manager.js +1 -14
- package/out/zero-cache/src/services/change-source/common/backfill-manager.js.map +1 -1
- package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.js +3 -15
- package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.d.ts +1 -11
- package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.js +2 -21
- package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +0 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js +7 -8
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +229 -1513
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +2 -2
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.js +6 -15
- package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +20 -137
- package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/published.js +13 -82
- package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +21 -128
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js +5 -5
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/data.d.ts +0 -2
- package/out/zero-cache/src/services/change-source/protocol/current/data.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts +0 -3
- package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +0 -3
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +1 -3
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +0 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.js +3 -8
- package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
- package/out/zero-cache/src/services/litestream/config-v5.yml +1 -15
- package/out/zero-cache/src/services/mutagen/mutagen.d.ts +0 -5
- package/out/zero-cache/src/services/mutagen/mutagen.d.ts.map +1 -1
- package/out/zero-cache/src/services/mutagen/mutagen.js +1 -7
- package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/pusher.d.ts +119 -119
- package/out/zero-cache/src/services/mutagen/pusher.d.ts.map +1 -1
- package/out/zero-cache/src/services/mutagen/pusher.js +6 -5
- package/out/zero-cache/src/services/mutagen/pusher.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.js +16 -16
- package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js +0 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
- package/out/zero-cache/src/services/replicator/write-worker-client.d.ts +2 -27
- package/out/zero-cache/src/services/replicator/write-worker-client.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/write-worker-client.js +2 -3
- package/out/zero-cache/src/services/replicator/write-worker-client.js.map +1 -1
- package/out/zero-cache/src/services/replicator/write-worker.js +5 -24
- package/out/zero-cache/src/services/replicator/write-worker.js.map +1 -1
- package/out/zero-cache/src/services/run-ast.d.ts +0 -12
- package/out/zero-cache/src/services/run-ast.d.ts.map +1 -1
- package/out/zero-cache/src/services/run-ast.js +15 -27
- package/out/zero-cache/src/services/run-ast.js.map +1 -1
- package/out/zero-cache/src/services/runner.d.ts.map +1 -1
- package/out/zero-cache/src/services/runner.js +1 -1
- package/out/zero-cache/src/services/runner.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.d.ts +0 -45
- package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.js +1 -133
- package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/drain-coordinator.d.ts +1 -14
- package/out/zero-cache/src/services/view-syncer/drain-coordinator.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/drain-coordinator.js +4 -30
- package/out/zero-cache/src/services/view-syncer/drain-coordinator.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts +1 -1
- package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/inspect-handler.js +2 -2
- package/out/zero-cache/src/services/view-syncer/inspect-handler.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +1 -2
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +27 -48
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/query-covering.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/query-covering.js +6 -2
- package/out/zero-cache/src/services/view-syncer/query-covering.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +4 -42
- package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.js +28 -117
- package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts +1 -11
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +95 -466
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/types/processes.d.ts +0 -32
- package/out/zero-cache/src/types/processes.d.ts.map +1 -1
- package/out/zero-cache/src/types/processes.js +4 -43
- package/out/zero-cache/src/types/processes.js.map +1 -1
- package/out/zero-cache/src/types/profiler.d.ts +0 -12
- package/out/zero-cache/src/types/profiler.d.ts.map +1 -1
- package/out/zero-cache/src/types/profiler.js +1 -46
- package/out/zero-cache/src/types/profiler.js.map +1 -1
- package/out/zero-cache/src/types/row-key.d.ts.map +1 -1
- package/out/zero-cache/src/types/row-key.js +5 -5
- package/out/zero-cache/src/types/row-key.js.map +1 -1
- package/out/zero-cache/src/workers/connect-params.d.ts +7 -0
- package/out/zero-cache/src/workers/connect-params.d.ts.map +1 -1
- package/out/zero-cache/src/workers/connect-params.js +20 -1
- package/out/zero-cache/src/workers/connect-params.js.map +1 -1
- package/out/zero-cache/src/workers/connection.d.ts +4 -4
- package/out/zero-cache/src/workers/connection.d.ts.map +1 -1
- package/out/zero-cache/src/workers/connection.js +8 -8
- package/out/zero-cache/src/workers/connection.js.map +1 -1
- package/out/zero-cache/src/workers/replicator.d.ts +0 -1
- package/out/zero-cache/src/workers/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/workers/replicator.js +2 -4
- package/out/zero-cache/src/workers/replicator.js.map +1 -1
- package/out/zero-cache/src/workers/syncer-ws-message-handler.d.ts.map +1 -1
- package/out/zero-cache/src/workers/syncer-ws-message-handler.js +16 -21
- package/out/zero-cache/src/workers/syncer-ws-message-handler.js.map +1 -1
- package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/workers/syncer.js +1 -10
- package/out/zero-cache/src/workers/syncer.js.map +1 -1
- package/out/zero-client/src/client/connection-manager.d.ts +0 -20
- package/out/zero-client/src/client/connection-manager.d.ts.map +1 -1
- package/out/zero-client/src/client/connection-manager.js +13 -77
- package/out/zero-client/src/client/connection-manager.js.map +1 -1
- package/out/zero-client/src/client/connection-status-enum.d.ts +0 -2
- package/out/zero-client/src/client/connection-status-enum.d.ts.map +1 -1
- package/out/zero-client/src/client/connection-status-enum.js +1 -3
- package/out/zero-client/src/client/connection-status-enum.js.map +1 -1
- package/out/zero-client/src/client/connection.d.ts +0 -6
- package/out/zero-client/src/client/connection.d.ts.map +1 -1
- package/out/zero-client/src/client/connection.js +1 -2
- package/out/zero-client/src/client/connection.js.map +1 -1
- package/out/zero-client/src/client/context.d.ts +2 -27
- package/out/zero-client/src/client/context.d.ts.map +1 -1
- package/out/zero-client/src/client/context.js +1 -112
- package/out/zero-client/src/client/context.js.map +1 -1
- package/out/zero-client/src/client/custom.js +2 -2
- package/out/zero-client/src/client/custom.js.map +1 -1
- package/out/zero-client/src/client/error.js +1 -1
- package/out/zero-client/src/client/inspector/lazy-inspector.js +2 -2
- package/out/zero-client/src/client/inspector/lazy-inspector.js.map +1 -1
- package/out/zero-client/src/client/ivm-branch.d.ts.map +1 -1
- package/out/zero-client/src/client/ivm-branch.js +3 -20
- package/out/zero-client/src/client/ivm-branch.js.map +1 -1
- package/out/zero-client/src/client/mutation-tracker.d.ts.map +1 -1
- package/out/zero-client/src/client/mutation-tracker.js +1 -1
- package/out/zero-client/src/client/mutation-tracker.js.map +1 -1
- package/out/zero-client/src/client/mutator-proxy.d.ts.map +1 -1
- package/out/zero-client/src/client/mutator-proxy.js +1 -2
- package/out/zero-client/src/client/mutator-proxy.js.map +1 -1
- package/out/zero-client/src/client/options.d.ts +0 -3
- package/out/zero-client/src/client/options.d.ts.map +1 -1
- package/out/zero-client/src/client/options.js.map +1 -1
- package/out/zero-client/src/client/query-manager.d.ts +0 -2
- package/out/zero-client/src/client/query-manager.d.ts.map +1 -1
- package/out/zero-client/src/client/query-manager.js +14 -50
- package/out/zero-client/src/client/query-manager.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero-rep.d.ts +0 -1
- package/out/zero-client/src/client/zero-rep.d.ts.map +1 -1
- package/out/zero-client/src/client/zero-rep.js +6 -9
- package/out/zero-client/src/client/zero-rep.js.map +1 -1
- package/out/zero-client/src/client/zero.d.ts +3 -18
- package/out/zero-client/src/client/zero.d.ts.map +1 -1
- package/out/zero-client/src/client/zero.js +36 -123
- package/out/zero-client/src/client/zero.js.map +1 -1
- package/out/zero-client/src/types/query-result.d.ts +0 -2
- package/out/zero-client/src/types/query-result.d.ts.map +1 -1
- package/out/zero-protocol/src/analyze-query-result.d.ts +5 -5
- package/out/zero-protocol/src/analyze-query-result.d.ts.map +1 -1
- package/out/zero-protocol/src/analyze-query-result.js +1 -1
- package/out/zero-protocol/src/analyze-query-result.js.map +1 -1
- package/out/zero-protocol/src/ast.d.ts +1 -64
- package/out/zero-protocol/src/ast.d.ts.map +1 -1
- package/out/zero-protocol/src/ast.js +54 -225
- package/out/zero-protocol/src/ast.js.map +1 -1
- package/out/zero-protocol/src/connect.d.ts +13 -0
- package/out/zero-protocol/src/connect.d.ts.map +1 -1
- package/out/zero-protocol/src/connect.js +30 -1
- package/out/zero-protocol/src/connect.js.map +1 -1
- package/out/zero-protocol/src/down.d.ts +2 -2
- package/out/zero-protocol/src/error.d.ts +1 -1
- package/out/zero-protocol/src/inspect-down.d.ts +6 -6
- package/out/zero-protocol/src/poke.d.ts +11 -4
- package/out/zero-protocol/src/poke.d.ts.map +1 -1
- package/out/zero-protocol/src/poke.js +3 -2
- package/out/zero-protocol/src/poke.js.map +1 -1
- package/out/zero-protocol/src/protocol-flag-enum.d.ts +7 -0
- package/out/zero-protocol/src/protocol-flag-enum.d.ts.map +1 -0
- package/out/zero-protocol/src/protocol-flag-enum.js +7 -0
- package/out/zero-protocol/src/protocol-flag-enum.js.map +1 -0
- package/out/zero-protocol/src/protocol-flag.d.ts +14 -0
- package/out/zero-protocol/src/protocol-flag.d.ts.map +1 -0
- package/out/zero-protocol/src/protocol-flag.js +8 -0
- package/out/zero-protocol/src/protocol-flag.js.map +1 -0
- package/out/zero-protocol/src/protocol-version.d.ts +30 -6
- package/out/zero-protocol/src/protocol-version.d.ts.map +1 -1
- package/out/zero-protocol/src/protocol-version.js +1 -1
- package/out/zero-protocol/src/protocol-version.js.map +1 -1
- package/out/zero-protocol/src/query-hash.d.ts +2 -7
- package/out/zero-protocol/src/query-hash.d.ts.map +1 -1
- package/out/zero-protocol/src/query-hash.js +10 -10
- package/out/zero-protocol/src/query-hash.js.map +1 -1
- package/out/zero-react/src/use-query.d.ts +4 -5
- package/out/zero-react/src/use-query.d.ts.map +1 -1
- package/out/zero-react/src/use-query.js +9 -86
- package/out/zero-react/src/use-query.js.map +1 -1
- package/out/zero-solid/src/solid-view.d.ts +0 -17
- package/out/zero-solid/src/solid-view.d.ts.map +1 -1
- package/out/zero-solid/src/solid-view.js +1 -39
- package/out/zero-solid/src/solid-view.js.map +1 -1
- package/out/zero-solid/src/use-query.js +3 -5
- package/out/zero-solid/src/use-query.js.map +1 -1
- package/out/zql/src/builder/builder.d.ts +0 -19
- package/out/zql/src/builder/builder.d.ts.map +1 -1
- package/out/zql/src/builder/builder.js +11 -28
- package/out/zql/src/builder/builder.js.map +1 -1
- package/out/zql/src/builder/debug-delegate.d.ts +1 -6
- package/out/zql/src/builder/debug-delegate.d.ts.map +1 -1
- package/out/zql/src/builder/debug-delegate.js +2 -14
- package/out/zql/src/builder/debug-delegate.js.map +1 -1
- package/out/zql/src/ivm/array-view.d.ts +0 -29
- package/out/zql/src/ivm/array-view.d.ts.map +1 -1
- package/out/zql/src/ivm/array-view.js +12 -63
- package/out/zql/src/ivm/array-view.js.map +1 -1
- package/out/zql/src/ivm/cap.d.ts.map +1 -1
- package/out/zql/src/ivm/cap.js +3 -5
- package/out/zql/src/ivm/cap.js.map +1 -1
- package/out/zql/src/ivm/data.d.ts.map +1 -1
- package/out/zql/src/ivm/data.js +3 -8
- package/out/zql/src/ivm/data.js.map +1 -1
- package/out/zql/src/ivm/exists.d.ts +1 -1
- package/out/zql/src/ivm/exists.d.ts.map +1 -1
- package/out/zql/src/ivm/exists.js.map +1 -1
- package/out/zql/src/ivm/fan-in.d.ts +2 -2
- package/out/zql/src/ivm/fan-in.d.ts.map +1 -1
- package/out/zql/src/ivm/fan-in.js +5 -6
- package/out/zql/src/ivm/fan-in.js.map +1 -1
- package/out/zql/src/ivm/fan-out.d.ts +2 -2
- package/out/zql/src/ivm/fan-out.d.ts.map +1 -1
- package/out/zql/src/ivm/fan-out.js.map +1 -1
- package/out/zql/src/ivm/filter-operators.d.ts +6 -7
- package/out/zql/src/ivm/filter-operators.d.ts.map +1 -1
- package/out/zql/src/ivm/filter-operators.js +12 -29
- package/out/zql/src/ivm/filter-operators.js.map +1 -1
- package/out/zql/src/ivm/filter.d.ts +2 -2
- package/out/zql/src/ivm/filter.d.ts.map +1 -1
- package/out/zql/src/ivm/filter.js +4 -7
- package/out/zql/src/ivm/filter.js.map +1 -1
- package/out/zql/src/ivm/flipped-join.js +2 -2
- package/out/zql/src/ivm/flipped-join.js.map +1 -1
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts +1 -1
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts.map +1 -1
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.js +4 -6
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.js.map +1 -1
- package/out/zql/src/ivm/memory-source.d.ts +3 -15
- package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
- package/out/zql/src/ivm/memory-source.js +23 -57
- package/out/zql/src/ivm/memory-source.js.map +1 -1
- package/out/zql/src/ivm/operator.d.ts +0 -40
- package/out/zql/src/ivm/operator.d.ts.map +1 -1
- package/out/zql/src/ivm/operator.js.map +1 -1
- package/out/zql/src/ivm/take.d.ts.map +1 -1
- package/out/zql/src/ivm/take.js +4 -3
- package/out/zql/src/ivm/take.js.map +1 -1
- package/out/zql/src/ivm/union-fan-in.d.ts.map +1 -1
- package/out/zql/src/ivm/union-fan-in.js +7 -9
- package/out/zql/src/ivm/union-fan-in.js.map +1 -1
- package/out/zql/src/ivm/view-apply-change.d.ts.map +1 -1
- package/out/zql/src/ivm/view-apply-change.js +4 -9
- package/out/zql/src/ivm/view-apply-change.js.map +1 -1
- package/out/zql/src/ivm/view.d.ts +0 -15
- package/out/zql/src/ivm/view.d.ts.map +1 -1
- package/out/zql/src/mutate/mutator-registry.d.ts.map +1 -1
- package/out/zql/src/mutate/mutator-registry.js +2 -2
- package/out/zql/src/mutate/mutator-registry.js.map +1 -1
- package/out/zql/src/planner/planner-builder.d.ts +3 -12
- package/out/zql/src/planner/planner-builder.d.ts.map +1 -1
- package/out/zql/src/planner/planner-builder.js +20 -40
- package/out/zql/src/planner/planner-builder.js.map +1 -1
- package/out/zql/src/planner/planner-connection.d.ts +2 -28
- package/out/zql/src/planner/planner-connection.d.ts.map +1 -1
- package/out/zql/src/planner/planner-connection.js +8 -108
- package/out/zql/src/planner/planner-connection.js.map +1 -1
- package/out/zql/src/planner/planner-debug.d.ts +1 -1
- package/out/zql/src/planner/planner-debug.d.ts.map +1 -1
- package/out/zql/src/planner/planner-debug.js +8 -3
- package/out/zql/src/planner/planner-debug.js.map +1 -1
- package/out/zql/src/planner/planner-fan-out.d.ts +0 -1
- package/out/zql/src/planner/planner-fan-out.d.ts.map +1 -1
- package/out/zql/src/planner/planner-fan-out.js +0 -3
- package/out/zql/src/planner/planner-fan-out.js.map +1 -1
- package/out/zql/src/planner/planner-graph.d.ts +0 -2
- package/out/zql/src/planner/planner-graph.d.ts.map +1 -1
- package/out/zql/src/planner/planner-graph.js +0 -2
- package/out/zql/src/planner/planner-graph.js.map +1 -1
- package/out/zql/src/planner/planner-join.d.ts +0 -2
- package/out/zql/src/planner/planner-join.d.ts.map +1 -1
- package/out/zql/src/planner/planner-join.js +0 -7
- package/out/zql/src/planner/planner-join.js.map +1 -1
- package/out/zql/src/planner/planner-node.d.ts +1 -2
- package/out/zql/src/planner/planner-node.d.ts.map +1 -1
- package/out/zql/src/planner/planner-node.js.map +1 -1
- package/out/zql/src/planner/planner-source.d.ts +2 -2
- package/out/zql/src/planner/planner-source.d.ts.map +1 -1
- package/out/zql/src/planner/planner-source.js +2 -2
- package/out/zql/src/planner/planner-source.js.map +1 -1
- package/out/zql/src/query/query-delegate-base.d.ts +1 -9
- package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
- package/out/zql/src/query/query-delegate-base.js +36 -132
- package/out/zql/src/query/query-delegate-base.js.map +1 -1
- package/out/zql/src/query/query-delegate.d.ts +1 -50
- package/out/zql/src/query/query-delegate.d.ts.map +1 -1
- package/out/zql/src/query/query-impl.d.ts +14 -25
- package/out/zql/src/query/query-impl.d.ts.map +1 -1
- package/out/zql/src/query/query-impl.js +94 -397
- package/out/zql/src/query/query-impl.js.map +1 -1
- package/out/zql/src/query/query-internals.d.ts +11 -21
- package/out/zql/src/query/query-internals.d.ts.map +1 -1
- package/out/zql/src/query/query-internals.js.map +1 -1
- package/out/zql/src/query/query.d.ts +2 -11
- package/out/zql/src/query/query.d.ts.map +1 -1
- package/out/zql/src/query/runnable-query-impl.d.ts +2 -3
- package/out/zql/src/query/runnable-query-impl.d.ts.map +1 -1
- package/out/zql/src/query/runnable-query-impl.js +2 -15
- package/out/zql/src/query/runnable-query-impl.js.map +1 -1
- package/out/zql/src/query/typed-view.d.ts +1 -1
- package/out/zql/src/query/typed-view.d.ts.map +1 -1
- package/out/zqlite/src/db.d.ts +1 -9
- package/out/zqlite/src/db.d.ts.map +1 -1
- package/out/zqlite/src/db.js +2 -8
- package/out/zqlite/src/db.js.map +1 -1
- package/out/zqlite/src/query-builder.d.ts +1 -1
- package/out/zqlite/src/query-builder.d.ts.map +1 -1
- package/out/zqlite/src/query-builder.js +2 -4
- package/out/zqlite/src/query-builder.js.map +1 -1
- package/out/zqlite/src/query-delegate.d.ts.map +1 -1
- package/out/zqlite/src/query-delegate.js +6 -5
- package/out/zqlite/src/query-delegate.js.map +1 -1
- package/out/zqlite/src/sqlite-cost-model.d.ts.map +1 -1
- package/out/zqlite/src/sqlite-cost-model.js +30 -2
- package/out/zqlite/src/sqlite-cost-model.js.map +1 -1
- package/out/zqlite/src/sqlite-stat-fanout.d.ts.map +1 -1
- package/out/zqlite/src/sqlite-stat-fanout.js +5 -4
- package/out/zqlite/src/sqlite-stat-fanout.js.map +1 -1
- package/out/zqlite/src/table-source.d.ts +3 -16
- package/out/zqlite/src/table-source.d.ts.map +1 -1
- package/out/zqlite/src/table-source.js +14 -33
- package/out/zqlite/src/table-source.js.map +1 -1
- package/package.json +3 -2
- package/out/replicache/src/dag/invalid-ref-count-error.d.ts +0 -12
- package/out/replicache/src/dag/invalid-ref-count-error.d.ts.map +0 -1
- package/out/replicache/src/dag/invalid-ref-count-error.js +0 -19
- package/out/replicache/src/dag/invalid-ref-count-error.js.map +0 -1
- package/out/shared/src/xxhash32.d.ts +0 -36
- package/out/shared/src/xxhash32.d.ts.map +0 -1
- package/out/shared/src/xxhash32.js +0 -51
- package/out/shared/src/xxhash32.js.map +0 -1
- package/out/zero-cache/src/db/index-predicate.d.ts +0 -4
- package/out/zero-cache/src/db/index-predicate.d.ts.map +0 -1
- package/out/zero-cache/src/db/index-predicate.js +0 -46
- package/out/zero-cache/src/db/index-predicate.js.map +0 -1
- package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.d.ts +0 -19
- package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.d.ts.map +0 -1
- package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.js +0 -581
- package/out/zero-cache/src/services/change-source/pg/schema/index-predicate.js.map +0 -1
- package/out/zero-cache/src/services/litestream/litestream-checkpointer.js +0 -131
- package/out/zero-cache/src/services/litestream/litestream-checkpointer.js.map +0 -1
- package/out/zero-cache/src/services/litestream/litestream-controller.d.ts +0 -70
- package/out/zero-cache/src/services/litestream/litestream-controller.d.ts.map +0 -1
- package/out/zero-cache/src/services/litestream/litestream-controller.js +0 -101
- package/out/zero-cache/src/services/litestream/litestream-controller.js.map +0 -1
- package/out/zero-cache/src/services/profz.d.ts +0 -7
- package/out/zero-cache/src/services/profz.d.ts.map +0 -1
- package/out/zero-cache/src/services/profz.js +0 -103
- package/out/zero-cache/src/services/profz.js.map +0 -1
- package/out/zero-cache/src/services/view-syncer/hydration-budget.d.ts +0 -33
- package/out/zero-cache/src/services/view-syncer/hydration-budget.d.ts.map +0 -1
- package/out/zero-cache/src/services/view-syncer/hydration-budget.js +0 -62
- package/out/zero-cache/src/services/view-syncer/hydration-budget.js.map +0 -1
- package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.d.ts +0 -51
- package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.d.ts.map +0 -1
- package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.js +0 -78
- package/out/zero-cache/src/services/view-syncer/hydration-circuit-breaker.js.map +0 -1
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.d.ts +0 -95
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.d.ts.map +0 -1
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js +0 -155
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js.map +0 -1
- package/out/zero-protocol/src/query-hash-visitor.d.ts +0 -81
- package/out/zero-protocol/src/query-hash-visitor.d.ts.map +0 -1
- package/out/zero-protocol/src/query-hash-visitor.js +0 -324
- package/out/zero-protocol/src/query-hash-visitor.js.map +0 -1
- package/out/zql/src/builder/correlated-predicate-pushdown.d.ts +0 -43
- package/out/zql/src/builder/correlated-predicate-pushdown.d.ts.map +0 -1
- package/out/zql/src/builder/correlated-predicate-pushdown.js +0 -161
- package/out/zql/src/builder/correlated-predicate-pushdown.js.map +0 -1
- package/out/zql/src/ivm/connection-index.d.ts +0 -68
- package/out/zql/src/ivm/connection-index.d.ts.map +0 -1
- package/out/zql/src/ivm/connection-index.js +0 -149
- package/out/zql/src/ivm/connection-index.js.map +0 -1
- package/out/zql/src/ivm/deferred-input.d.ts +0 -44
- package/out/zql/src/ivm/deferred-input.d.ts.map +0 -1
- package/out/zql/src/ivm/deferred-input.js +0 -89
- package/out/zql/src/ivm/deferred-input.js.map +0 -1
- package/out/zql/src/planner/planner-filter.d.ts +0 -59
- package/out/zql/src/planner/planner-filter.d.ts.map +0 -1
- package/out/zql/src/planner/planner-filter.js +0 -116
- package/out/zql/src/planner/planner-filter.js.map +0 -1
- package/out/zql/src/query/query-transitions.d.ts +0 -171
- package/out/zql/src/query/query-transitions.d.ts.map +0 -1
- package/out/zql/src/query/query-transitions.js +0 -204
- package/out/zql/src/query/query-transitions.js.map +0 -1
|
@@ -7,7 +7,6 @@ import { promiseVoid } from "../../shared/src/resolved-promises.js";
|
|
|
7
7
|
import { deepFreeze } from "./frozen-json.js";
|
|
8
8
|
import { makeIDBName } from "./make-idb-name.js";
|
|
9
9
|
import { AbortError } from "../../shared/src/abort-error.js";
|
|
10
|
-
import { InvalidRefCountError } from "./dag/invalid-ref-count-error.js";
|
|
11
10
|
import { assertHash, emptyHash, newRandomHash } from "./hash.js";
|
|
12
11
|
import { ChunkNotFoundError, mustGetHeadHash } from "./dag/store.js";
|
|
13
12
|
import { StoreImpl } from "./dag/store-impl.js";
|
|
@@ -21,7 +20,7 @@ import { ClientStateNotFoundError, hasClientState, initClientV6 } from "./persis
|
|
|
21
20
|
import { getKVStoreProvider } from "./get-kv-store-provider.js";
|
|
22
21
|
import { createLogContext } from "./log-options.js";
|
|
23
22
|
import { IDBDatabasesStore } from "./persist/idb-databases-store.js";
|
|
24
|
-
import { COLLECT_IDB_INTERVAL, INITIAL_COLLECT_IDB_DELAY,
|
|
23
|
+
import { COLLECT_IDB_INTERVAL, INITIAL_COLLECT_IDB_DELAY, initCollectIDBDatabases } from "./persist/collect-idb-databases.js";
|
|
25
24
|
import { throwIfClosed } from "./transaction-closed-error.js";
|
|
26
25
|
import { getDocumentVisibilityWatcher } from "../../shared/src/document-visible.js";
|
|
27
26
|
import { PullDelegate, PushDelegate } from "./connection-loop-delegates.js";
|
|
@@ -63,12 +62,6 @@ var PERSIST_IDLE_TIMEOUT_MS = 1e3;
|
|
|
63
62
|
var REFRESH_IDLE_TIMEOUT_MS = 1e3;
|
|
64
63
|
var PERSIST_THROTTLE_MS = 500;
|
|
65
64
|
var REFRESH_THROTTLE_MS = 500;
|
|
66
|
-
/**
|
|
67
|
-
* Opening the database blocks everything Replicache does, including Zero's
|
|
68
|
-
* first connect attempt, so a slow open is worth a warning rather than a
|
|
69
|
-
* debug line.
|
|
70
|
-
*/
|
|
71
|
-
var SLOW_DB_OPEN_THRESHOLD_MS = 50;
|
|
72
65
|
var LAZY_STORE_SOURCE_CHUNK_CACHE_SIZE_LIMIT = 100 * 2 ** 20;
|
|
73
66
|
var RECOVER_MUTATIONS_INTERVAL_MS = 300 * 1e3;
|
|
74
67
|
var noop = () => {};
|
|
@@ -90,7 +83,6 @@ var ReplicacheImpl = class {
|
|
|
90
83
|
*/
|
|
91
84
|
isClientGroupDisabled = false;
|
|
92
85
|
#kvStoreProvider;
|
|
93
|
-
#perKVStore;
|
|
94
86
|
lastMutationID = 0;
|
|
95
87
|
/**
|
|
96
88
|
* This is the name Replicache uses for the IndexedDB database where data is
|
|
@@ -99,14 +91,6 @@ var ReplicacheImpl = class {
|
|
|
99
91
|
get idbName() {
|
|
100
92
|
return makeIDBName(this.name, this.schemaVersion);
|
|
101
93
|
}
|
|
102
|
-
/**
|
|
103
|
-
* The KV store backing this instance. Its `kind` reflects the storage
|
|
104
|
-
* currently in use, e.g. `'mem'` after an IndexedDB store fell back to
|
|
105
|
-
* memory.
|
|
106
|
-
*/
|
|
107
|
-
get kvStore() {
|
|
108
|
-
return this.#perKVStore;
|
|
109
|
-
}
|
|
110
94
|
set auth(auth) {
|
|
111
95
|
if (this.#zero) this.#zero.auth = auth;
|
|
112
96
|
this.#auth = auth;
|
|
@@ -128,12 +112,6 @@ var ReplicacheImpl = class {
|
|
|
128
112
|
#online = true;
|
|
129
113
|
#clientID = makeClientID();
|
|
130
114
|
#ready;
|
|
131
|
-
/**
|
|
132
|
-
* Resolves if open fails, for whatever reason. `#ready` never resolves in
|
|
133
|
-
* that case, so `close()` waits on whichever of the two settles first
|
|
134
|
-
* instead of hanging forever.
|
|
135
|
-
*/
|
|
136
|
-
#openFailed = resolver();
|
|
137
115
|
#profileIDPromise;
|
|
138
116
|
#clientGroupIDPromise;
|
|
139
117
|
#mutatorRegistry = {};
|
|
@@ -203,13 +181,9 @@ var ReplicacheImpl = class {
|
|
|
203
181
|
*/
|
|
204
182
|
onSync = null;
|
|
205
183
|
/**
|
|
206
|
-
* `onClientStateNotFound` is called when the persistent client
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
* client has no pending mutations and has not been used for a while.
|
|
210
|
-
* - the persistent store was found to be corrupt. Replicache then tries to
|
|
211
|
-
* drop the database, including any pending mutations, so that a fresh one
|
|
212
|
-
* is created on reload.
|
|
184
|
+
* `onClientStateNotFound` is called when the persistent client has been
|
|
185
|
+
* garbage collected. This can happen if the client has no pending mutations
|
|
186
|
+
* and has not been used for a while.
|
|
213
187
|
*
|
|
214
188
|
* The default behavior is to reload the page (using `location.reload()`). Set
|
|
215
189
|
* this to `null` or provide your own function to prevent the page from
|
|
@@ -272,9 +246,8 @@ var ReplicacheImpl = class {
|
|
|
272
246
|
const kvStoreProvider = getKVStoreProvider(this.#lc, options.kvStore);
|
|
273
247
|
this.#kvStoreProvider = kvStoreProvider;
|
|
274
248
|
const perKVStore = kvStoreProvider.create(this.idbName);
|
|
275
|
-
this.#perKVStore = perKVStore;
|
|
276
249
|
this.#idbDatabases = new IDBDatabasesStore(kvStoreProvider.create);
|
|
277
|
-
this.perdag = new StoreImpl(perKVStore, newRandomHash, assertHash
|
|
250
|
+
this.perdag = new StoreImpl(perKVStore, newRandomHash, assertHash);
|
|
278
251
|
this.memdag = new LazyStore(this.perdag, LAZY_STORE_SOURCE_CHUNK_CACHE_SIZE_LIMIT, newRandomHash, assertHash);
|
|
279
252
|
const readyResolver = resolver();
|
|
280
253
|
this.#ready = readyResolver.promise;
|
|
@@ -294,27 +267,16 @@ var ReplicacheImpl = class {
|
|
|
294
267
|
this.#onPersist = initOnPersistChannel(this.name, this.#closeAbortController.signal, (persistInfo) => {
|
|
295
268
|
this.#handlePersist(persistInfo);
|
|
296
269
|
});
|
|
297
|
-
this.#open(indexes, enableClientGroupForking, enableMutationRecovery, clientMaxAgeMs, profileIDResolver.resolve, clientGroupIDResolver.resolve, readyResolver.resolve, onClientsDeleted)
|
|
298
|
-
this.#openFailed.resolve();
|
|
299
|
-
if (e instanceof InvalidRefCountError) {
|
|
300
|
-
this.#lc.debug?.("Open failed because the persistent store is corrupt");
|
|
301
|
-
return;
|
|
302
|
-
}
|
|
303
|
-
throw e;
|
|
304
|
-
});
|
|
270
|
+
this.#open(indexes, enableClientGroupForking, enableMutationRecovery, clientMaxAgeMs, profileIDResolver.resolve, clientGroupIDResolver.resolve, readyResolver.resolve, onClientsDeleted);
|
|
305
271
|
}
|
|
306
272
|
async #open(indexes, enableClientGroupForking, enableMutationRecovery, clientMaxAgeMs, profileIDResolver, resolveClientGroupID, resolveReady, onClientsDeleted) {
|
|
307
273
|
const { clientID } = this;
|
|
308
|
-
const openStart = performance.now();
|
|
309
274
|
await closingInstances.get(this.name);
|
|
310
275
|
await this.#idbDatabases.getProfileID().then(profileIDResolver);
|
|
311
276
|
await this.#idbDatabases.putDatabase(this.#idbDatabase);
|
|
312
277
|
const [client, headHash, , isNewClientGroup] = await initClientV6(clientID, this.#lc, this.perdag, Object.keys(this.#mutatorRegistry), indexes, 7, enableClientGroupForking);
|
|
313
278
|
resolveClientGroupID(client.clientGroupID);
|
|
314
279
|
await withWrite(this.memdag, (write) => write.setHead(DEFAULT_HEAD_NAME, headHash));
|
|
315
|
-
const dbOpenMs = performance.now() - openStart;
|
|
316
|
-
if (dbOpenMs > SLOW_DB_OPEN_THRESHOLD_MS) this.#lc.warn?.(`Opening the database took ${Math.round(dbOpenMs)}ms`, { name: this.idbName });
|
|
317
|
-
else this.#lc.debug?.("Opened the database in", Math.round(dbOpenMs), "ms");
|
|
318
280
|
await this.#zero?.init(headHash, this.memdag);
|
|
319
281
|
resolveReady();
|
|
320
282
|
if (this.#enablePullAndPushInOpen) {
|
|
@@ -326,7 +288,7 @@ var ReplicacheImpl = class {
|
|
|
326
288
|
this.#clientStateNotFoundOnClient(clientID);
|
|
327
289
|
}, HEARTBEAT_INTERVAL, this.#lc, signal);
|
|
328
290
|
initClientGC(clientID, this.perdag, clientMaxAgeMs, GC_INTERVAL, onClientsDeleted, this.#lc, signal);
|
|
329
|
-
initCollectIDBDatabases(this.#idbDatabases, this.#kvStoreProvider, COLLECT_IDB_INTERVAL, INITIAL_COLLECT_IDB_DELAY, 2 * clientMaxAgeMs, enableMutationRecovery, onClientsDeleted, this.#lc, signal
|
|
291
|
+
initCollectIDBDatabases(this.#idbDatabases, this.#kvStoreProvider, COLLECT_IDB_INTERVAL, INITIAL_COLLECT_IDB_DELAY, 2 * clientMaxAgeMs, enableMutationRecovery, onClientsDeleted, this.#lc, signal);
|
|
330
292
|
initClientGroupGC(this.perdag, enableMutationRecovery, this.#lc, signal);
|
|
331
293
|
initNewClientChannel(this.name, this.idbName, signal, client.clientGroupID, isNewClientGroup, () => {
|
|
332
294
|
this.#fireOnUpdateNeeded(updateNeededReasonNewClientGroup);
|
|
@@ -403,7 +365,7 @@ var ReplicacheImpl = class {
|
|
|
403
365
|
closingInstances.set(this.name, promise);
|
|
404
366
|
this.#closeAbortController.abort();
|
|
405
367
|
getBrowserGlobal("document")?.removeEventListener("visibilitychange", this.#onVisibilityChange);
|
|
406
|
-
await
|
|
368
|
+
await this.#ready;
|
|
407
369
|
const closingPromises = [
|
|
408
370
|
this.memdag.close(),
|
|
409
371
|
this.perdag.close(),
|
|
@@ -429,13 +391,11 @@ var ReplicacheImpl = class {
|
|
|
429
391
|
this.#schedulePersist();
|
|
430
392
|
return;
|
|
431
393
|
}
|
|
432
|
-
|
|
394
|
+
const zeroData = await this.#zero?.getTxData?.(syncHead);
|
|
433
395
|
for (const mutation of replayMutations) {
|
|
434
396
|
if (this.#subscriptions.hasPendingSubscriptionRuns) await Promise.resolve();
|
|
435
397
|
const { meta } = mutation;
|
|
436
|
-
|
|
437
|
-
syncHead = result;
|
|
438
|
-
zeroData = next;
|
|
398
|
+
syncHead = await withWriteNoImplicitCommit(this.memdag, (dagWrite) => rebaseMutationAndCommit(mutation, dagWrite, syncHead, SYNC_HEAD_NAME, this.#mutatorRegistry, lc, isLocalMetaDD31(meta) ? meta.clientID : clientID, 7, zeroData));
|
|
439
399
|
}
|
|
440
400
|
}
|
|
441
401
|
}
|
|
@@ -658,10 +618,7 @@ var ReplicacheImpl = class {
|
|
|
658
618
|
await persistDD31(this.#lc, clientID, this.memdag, this.perdag, this.#mutatorRegistry, () => this.#closed, 7, this.#zero?.getTxData);
|
|
659
619
|
} catch (e) {
|
|
660
620
|
if (e instanceof ClientStateNotFoundError) this.#clientStateNotFoundOnClient(clientID);
|
|
661
|
-
else if (
|
|
662
|
-
await this.#handleInvalidRefCount(e);
|
|
663
|
-
return;
|
|
664
|
-
} else if (this.#closed) this.#lc.debug?.("Exception persisting during close", e);
|
|
621
|
+
else if (this.#closed) this.#lc.debug?.("Exception persisting during close", e);
|
|
665
622
|
else throw e;
|
|
666
623
|
}
|
|
667
624
|
const clientGroupID = await this.#clientGroupIDPromise;
|
|
@@ -681,7 +638,6 @@ var ReplicacheImpl = class {
|
|
|
681
638
|
refreshResult = await refresh(this.#lc, this.memdag, this.perdag, clientID, this.#mutatorRegistry, this.#subscriptions, () => this.closed, 7, this.#zero);
|
|
682
639
|
} catch (e) {
|
|
683
640
|
if (e instanceof ClientStateNotFoundError) this.#clientStateNotFoundOnClient(clientID);
|
|
684
|
-
else if (e instanceof InvalidRefCountError) await this.#handleInvalidRefCount(e);
|
|
685
641
|
else if (this.#closed) this.#lc.debug?.("Exception refreshing during close", e);
|
|
686
642
|
else throw e;
|
|
687
643
|
}
|
|
@@ -694,69 +650,6 @@ var ReplicacheImpl = class {
|
|
|
694
650
|
this.#lc.error?.(`Client state not found on client, clientID: ${clientID}`);
|
|
695
651
|
this.#fireOnClientStateNotFound();
|
|
696
652
|
}
|
|
697
|
-
/**
|
|
698
|
-
* Set once recovery from a corrupt database has started. Every write path
|
|
699
|
-
* into the perdag (open, persist, refresh, heartbeat, GC, ...) can trip on
|
|
700
|
-
* the same corrupt key, so recovery runs once and later reports await it.
|
|
701
|
-
*/
|
|
702
|
-
#corruptDatabaseRecovery;
|
|
703
|
-
/**
|
|
704
|
-
* Installed on the dag store that writes to our database. The store calls
|
|
705
|
-
* it after the failing transaction has been released, so dropping the
|
|
706
|
-
* database from here does not race with the rollback.
|
|
707
|
-
*/
|
|
708
|
-
#onInvalidRefCount = (e) => {
|
|
709
|
-
this.#handleInvalidRefCount(e);
|
|
710
|
-
};
|
|
711
|
-
/**
|
|
712
|
-
* The persistent dag store contains an invalid ref count. This means the
|
|
713
|
-
* store is corrupt (due to some unknown bug) and every subsequent write that
|
|
714
|
-
* touches that chunk would fail the same way. There is no way to repair it,
|
|
715
|
-
* so we treat it like the client state was lost and fire
|
|
716
|
-
* `onClientStateNotFound`.
|
|
717
|
-
*
|
|
718
|
-
* Disabling the client group is not enough: the corrupt ref count stays in
|
|
719
|
-
* the underlying kv store and any later write that touches that chunk (for
|
|
720
|
-
* example rewriting the `clients` chunk when a new client starts) would hit
|
|
721
|
-
* it again. Instead we drop the whole database so that the reload starts
|
|
722
|
-
* from a fresh store. Pending local mutations in this database are lost.
|
|
723
|
-
*
|
|
724
|
-
* This is expected to be exceedingly rare. Other instances sharing the
|
|
725
|
-
* database are not told: they simply hit the same corrupt key (or, once
|
|
726
|
-
* this instance drops the database, a generic storage error) on their own
|
|
727
|
-
* next write and recover the same way then. That's an acceptable delay for
|
|
728
|
-
* something we don't expect to ever happen.
|
|
729
|
-
*/
|
|
730
|
-
#handleInvalidRefCount(e) {
|
|
731
|
-
if (this.#corruptDatabaseRecovery === void 0) {
|
|
732
|
-
this.#lc.error?.(`Client state is corrupt on client, clientID: ${this.clientID}. Dropping database ${this.idbName}`, e);
|
|
733
|
-
this.#corruptDatabaseRecovery = this.#dropDatabaseAndFireOnClientStateNotFound();
|
|
734
|
-
}
|
|
735
|
-
return this.#corruptDatabaseRecovery;
|
|
736
|
-
}
|
|
737
|
-
/**
|
|
738
|
-
* Drops our database, then fires `onClientStateNotFound` so the app can
|
|
739
|
-
* recover, whether or not the drop itself succeeded.
|
|
740
|
-
*
|
|
741
|
-
* Uses its own handle on the databases registry rather than `#idbDatabases`
|
|
742
|
-
* so it works even when `close()` is already closing this instance.
|
|
743
|
-
*/
|
|
744
|
-
async #dropDatabaseAndFireOnClientStateNotFound() {
|
|
745
|
-
const { idbName, clientID } = this;
|
|
746
|
-
let idbDatabases;
|
|
747
|
-
try {
|
|
748
|
-
idbDatabases = new IDBDatabasesStore(this.#kvStoreProvider.create);
|
|
749
|
-
await dropDatabaseInternal(idbName, idbDatabases, this.#kvStoreProvider.drop);
|
|
750
|
-
} catch (dropError) {
|
|
751
|
-
this.#lc.error?.(`Failed to drop database ${idbName}, clientID: ${clientID}`, dropError);
|
|
752
|
-
}
|
|
753
|
-
try {
|
|
754
|
-
await idbDatabases?.close();
|
|
755
|
-
} catch (closeError) {
|
|
756
|
-
this.#lc.debug?.(`Failed to close the databases registry after dropping ${idbName}, clientID: ${clientID}`, closeError);
|
|
757
|
-
}
|
|
758
|
-
this.#fireOnClientStateNotFound();
|
|
759
|
-
}
|
|
760
653
|
async #clientStateNotFoundOnServer() {
|
|
761
654
|
const clientGroupID = await this.#clientGroupIDPromise;
|
|
762
655
|
this.#lc.error?.(`Client state not found on server, clientGroupID: ${clientGroupID}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"replicache-impl.js","names":["#subscriptions","#mutationRecovery","#kvStoreProvider","#perKVStore","#zero","#auth","#idbDatabase","#clientID","#ready","#openFailed","#profileIDPromise","#clientGroupIDPromise","#mutatorRegistry","#requestOptions","#idbDatabases","#lc","#closeAbortController","#persistLock","#enableScheduledPersist","#enableScheduledRefresh","#enableRefresh","#enablePullAndPushInOpen","#onPersist","#queryInternal","#onInvalidRefCount","#pullConnectionLoop","#invokePull","#pushConnectionLoop","#invokePush","#registerMutators","#wrapInOnlineCheck","#wrapInReauthRetries","#isPullDisabled","#isPushDisabled","#handlePersist","#open","#clientStateNotFoundOnClient","#fireOnUpdateNeeded","#onVisibilityChange","#closed","#checkForClientStateNotFoundAndCallHandler","#online","#schedulePersist","#changeSyncCounters","#convertToClientStateNotFoundError","#handleVersionNotSupportedResponse","#clientStateNotFoundOnServer","#handleInvalidRefCount","#fireOnClientStateNotFound","#corruptDatabaseRecovery","#dropDatabaseAndFireOnClientStateNotFound","#schedule","#persistScheduler","#scheduleRefresh","#refreshScheduler","#pushCounter","#pullCounter","#mutate","#register"],"sources":["../../../../replicache/src/replicache-impl.ts"],"sourcesContent":["import {Lock} from '@rocicorp/lock';\nimport type {LogContext} from '@rocicorp/logger';\nimport {consoleLogSink} from '@rocicorp/logger';\nimport {resolver} from '@rocicorp/resolver';\nimport {AbortError} from '../../shared/src/abort-error.ts';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {getBrowserGlobal} from '../../shared/src/browser-env.ts';\nimport {getDocumentVisibilityWatcher} from '../../shared/src/document-visible.ts';\nimport type {JSONValue, ReadonlyJSONValue} from '../../shared/src/json.ts';\nimport {promiseVoid} from '../../shared/src/resolved-promises.ts';\nimport {TESTING} from '../../shared/src/testing.ts';\nimport type {MaybePromise} from '../../shared/src/types.ts';\nimport {PullDelegate, PushDelegate} from './connection-loop-delegates.ts';\nimport {ConnectionLoop, MAX_DELAY_MS, MIN_DELAY_MS} from './connection-loop.ts';\nimport {assertCookie, type Cookie} from './cookies.ts';\nimport {InvalidRefCountError} from './dag/invalid-ref-count-error.ts';\nimport {LazyStore} from './dag/lazy-store.ts';\nimport {StoreImpl} from './dag/store-impl.ts';\nimport {ChunkNotFoundError, mustGetHeadHash, type Store} from './dag/store.ts';\nimport {\n baseSnapshotFromHash,\n DEFAULT_HEAD_NAME,\n isLocalMetaDD31,\n type LocalMeta,\n} from './db/commit.ts';\nimport {readFromDefaultHead} from './db/read.ts';\nimport {rebaseMutationAndCommit} from './db/rebase.ts';\nimport {newWriteLocal} from './db/write.ts';\nimport {\n isClientStateNotFoundResponse,\n isVersionNotSupportedResponse,\n type VersionNotSupportedResponse,\n} from './error-responses.ts';\nimport * as FormatVersion from './format-version-enum.ts';\nimport {deepFreeze} from './frozen-json.ts';\nimport {getDefaultPuller, isDefaultPuller} from './get-default-puller.ts';\nimport {getDefaultPusher, isDefaultPusher} from './get-default-pusher.ts';\nimport {getKVStoreProvider} from './get-kv-store-provider.ts';\nimport {assertHash, emptyHash, type Hash, newRandomHash} from './hash.ts';\nimport type {HTTPRequestInfo} from './http-request-info.ts';\nimport {httpStatusUnauthorized} from './http-status-unauthorized.ts';\nimport type {IndexDefinitions} from './index-defs.ts';\nimport type {Store as KVStore, StoreProvider} from './kv/store.ts';\nimport {createLogContext} from './log-options.ts';\nimport {makeIDBName} from './make-idb-name.ts';\nimport {MutationRecovery} from './mutation-recovery.ts';\nimport {initNewClientChannel} from './new-client-channel.ts';\nimport {\n initOnPersistChannel,\n type OnPersist,\n type PersistInfo,\n} from './on-persist-channel.ts';\nimport {\n type PendingMutation,\n pendingMutationsForAPI,\n} from './pending-mutations.ts';\nimport {\n CLIENT_MAX_INACTIVE_TIME,\n GC_INTERVAL,\n initClientGC,\n} from './persist/client-gc.ts';\nimport {initClientGroupGC} from './persist/client-group-gc.ts';\nimport {disableClientGroup} from './persist/client-groups.ts';\nimport {\n ClientStateNotFoundError,\n initClientV6,\n type OnClientsDeleted,\n hasClientState as persistHasClientState,\n} from './persist/clients.ts';\nimport {\n COLLECT_IDB_INTERVAL,\n dropDatabaseInternal,\n initCollectIDBDatabases,\n INITIAL_COLLECT_IDB_DELAY,\n} from './persist/collect-idb-databases.ts';\nimport {HEARTBEAT_INTERVAL, startHeartbeats} from './persist/heartbeat.ts';\nimport {\n IDBDatabasesStore,\n type IndexedDBDatabase,\n} from './persist/idb-databases-store.ts';\nimport {makeClientID} from './persist/make-client-id.ts';\nimport {persistDD31} from './persist/persist.ts';\nimport {refresh} from './persist/refresh.ts';\nimport {ProcessScheduler} from './process-scheduler.ts';\nimport type {Puller} from './puller.ts';\nimport {type Pusher, PushError} from './pusher.ts';\nimport type {\n MutationTrackingData,\n ReplicacheOptions,\n ZeroOption,\n} from './replicache-options.ts';\nimport {ReportError} from './report-error.ts';\nimport {setIntervalWithSignal} from './set-interval-with-signal.ts';\nimport {\n type SubscribeOptions,\n SubscriptionImpl,\n type SubscriptionsManager,\n SubscriptionsManagerImpl,\n type WatchCallback,\n type WatchCallbackForOptions,\n type WatchNoIndexCallback,\n type WatchOptions,\n WatchSubscription,\n} from './subscriptions.ts';\nimport type {DiffsMap} from './sync/diff.ts';\nimport * as HandlePullResponseResultEnum from './sync/handle-pull-response-result-type-enum.ts';\nimport type {ClientGroupID, ClientID} from './sync/ids.ts';\nimport {PullError} from './sync/pull-error.ts';\nimport {beginPullV1, handlePullResponseV1, maybeEndPull} from './sync/pull.ts';\nimport {push, PUSH_VERSION_DD31} from './sync/push.ts';\nimport {newRequestID} from './sync/request-id.ts';\nimport {SYNC_HEAD_NAME} from './sync/sync-head-name.ts';\nimport {throwIfClosed} from './transaction-closed-error.ts';\nimport type {ReadTransaction, WriteTransaction} from './transactions.ts';\nimport {ReadTransactionImpl, WriteTransactionImpl} from './transactions.ts';\nimport type {\n BeginPullResult,\n MakeMutator,\n MakeMutators,\n MutatorDefs,\n MutatorReturn,\n PokeInternal,\n QueryInternal,\n RequestOptions,\n UpdateNeededReason,\n} from './types.ts';\nimport {version} from './version.ts';\nimport {\n withRead,\n withWrite,\n withWriteNoImplicitCommit,\n} from './with-transactions.ts';\n\n/**\n * The maximum number of time to call out to getAuth before giving up\n * and throwing an error.\n */\nconst MAX_REAUTH_TRIES = 8;\n\nconst PERSIST_IDLE_TIMEOUT_MS = 1000;\nconst REFRESH_IDLE_TIMEOUT_MS = 1000;\n\nconst PERSIST_THROTTLE_MS = 500;\nconst REFRESH_THROTTLE_MS = 500;\n\n/**\n * Opening the database blocks everything Replicache does, including Zero's\n * first connect attempt, so a slow open is worth a warning rather than a\n * debug line.\n */\nconst SLOW_DB_OPEN_THRESHOLD_MS = 50;\n\nconst LAZY_STORE_SOURCE_CHUNK_CACHE_SIZE_LIMIT = 100 * 2 ** 20; // 100 MB\n\nconst RECOVER_MUTATIONS_INTERVAL_MS = 5 * 60 * 1000; // 5 mins\n\nconst noop = () => {\n // noop\n};\n\nconst updateNeededReasonNewClientGroup: UpdateNeededReason = {\n type: 'NewClientGroup',\n} as const;\n\n/** @deprecated Not used any more */\nexport interface MakeSubscriptionsManager {\n (queryInternal: QueryInternal, lc: LogContext): SubscriptionsManager;\n}\n\nexport interface ReplicacheImplOptions {\n /**\n * Defaults to true.\n */\n enableMutationRecovery?: boolean | undefined;\n\n /**\n * Defaults to true.\n */\n enableScheduledPersist?: boolean | undefined;\n\n /**\n * Defaults to true.\n */\n enableScheduledRefresh?: boolean | undefined;\n\n /**\n * Defaults to `() => true`.\n */\n enableRefresh?: (() => boolean) | undefined;\n\n /**\n * Defaults to true.\n */\n enablePullAndPushInOpen?: boolean | undefined;\n\n /**\n * @deprecated Not used anymore.\n */\n makeSubscriptionsManager?: unknown;\n\n /**\n * Default is `true`. If `false` if an exact match client group\n * is not found, a new client group is always made instead of forking\n * from an existing client group.\n */\n enableClientGroupForking?: boolean | undefined;\n\n /**\n * Callback for when Replicache has deleted clients.\n */\n onClientsDeleted?: OnClientsDeleted | undefined;\n\n /**\n * Internal option used by Zero.\n * Replicache will call this to and, if zero is enabled, will\n * invoke various hooks to allow Zero the keep IVM in sync with Replicache's b-trees.\n */\n zero?: ZeroOption | undefined;\n}\n\nexport class ReplicacheImpl<MD extends MutatorDefs = {}> {\n /** The URL to use when doing a pull request. */\n pullURL: string;\n\n /** The URL to use when doing a push request. */\n pushURL: string;\n\n /** The authorization token used when doing a push request. */\n #auth: string;\n\n /** The name of the Replicache database. Populated by {@link ReplicacheOptions#name}. */\n readonly name: string;\n\n readonly #subscriptions: SubscriptionsManager;\n readonly #mutationRecovery: MutationRecovery | undefined;\n\n /**\n * Client groups gets disabled when the server does not know about it.\n * A disabled client group prevents the client from pushing and pulling.\n */\n isClientGroupDisabled = false;\n\n readonly #kvStoreProvider: StoreProvider;\n readonly #perKVStore: KVStore;\n\n lastMutationID: number = 0;\n\n /**\n * This is the name Replicache uses for the IndexedDB database where data is\n * stored.\n */\n get idbName(): string {\n return makeIDBName(this.name, this.schemaVersion);\n }\n\n /**\n * The KV store backing this instance. Its `kind` reflects the storage\n * currently in use, e.g. `'mem'` after an IndexedDB store fell back to\n * memory.\n */\n get kvStore(): KVStore {\n return this.#perKVStore;\n }\n\n set auth(auth: string) {\n if (this.#zero) {\n this.#zero.auth = auth;\n }\n\n this.#auth = auth;\n }\n\n get auth() {\n return this.#auth;\n }\n\n /** The schema version of the data understood by this application. */\n readonly schemaVersion: string;\n\n get #idbDatabase(): IndexedDBDatabase {\n return {\n name: this.idbName,\n replicacheName: this.name,\n replicacheFormatVersion: FormatVersion.Latest,\n schemaVersion: this.schemaVersion,\n };\n }\n #closed = false;\n #online = true;\n readonly #clientID = makeClientID();\n readonly #ready: Promise<void>;\n /**\n * Resolves if open fails, for whatever reason. `#ready` never resolves in\n * that case, so `close()` waits on whichever of the two settles first\n * instead of hanging forever.\n */\n readonly #openFailed = resolver<void>();\n readonly #profileIDPromise: Promise<string>;\n readonly #clientGroupIDPromise: Promise<string>;\n readonly #mutatorRegistry: MutatorDefs = {};\n\n /**\n * The mutators that was registered in the constructor.\n */\n readonly mutate: MakeMutators<MD>;\n\n // Number of pushes/pulls at the moment.\n #pushCounter = 0;\n #pullCounter = 0;\n\n #pullConnectionLoop: ConnectionLoop;\n #pushConnectionLoop: ConnectionLoop;\n\n /**\n * The duration between each periodic {@link pull}. Setting this to `null`\n * disables periodic pull completely. Pull will still happen if you call\n * {@link pull} manually.\n */\n pullInterval: number | null;\n\n /**\n * The delay between when a change is made to Replicache and when Replicache\n * attempts to push that change.\n */\n pushDelay: number;\n\n readonly #requestOptions: Required<RequestOptions>;\n\n /**\n * The function to use to pull data from the server.\n */\n puller: Puller;\n\n /**\n * The function to use to push data to the server.\n */\n pusher: Pusher;\n\n readonly memdag: LazyStore;\n readonly perdag: Store;\n readonly #idbDatabases: IDBDatabasesStore;\n readonly #lc: LogContext;\n readonly #zero: ZeroOption | undefined;\n\n readonly #closeAbortController = new AbortController();\n\n readonly #persistLock = new Lock();\n readonly #enableScheduledPersist: boolean;\n readonly #enableScheduledRefresh: boolean;\n readonly #enableRefresh: () => boolean;\n readonly #enablePullAndPushInOpen: boolean;\n #persistScheduler = new ProcessScheduler(\n () => this.persist(),\n PERSIST_IDLE_TIMEOUT_MS,\n PERSIST_THROTTLE_MS,\n this.#closeAbortController.signal,\n );\n readonly #onPersist: OnPersist;\n #refreshScheduler = new ProcessScheduler(\n () => this.refresh(),\n REFRESH_IDLE_TIMEOUT_MS,\n REFRESH_THROTTLE_MS,\n this.#closeAbortController.signal,\n );\n\n /**\n * The options used to control the {@link pull} and push request behavior. This\n * object is live so changes to it will affect the next pull or push call.\n */\n get requestOptions(): Required<RequestOptions> {\n return this.#requestOptions;\n }\n\n /**\n * `onSync(true)` is called when Replicache transitions from no push or pull\n * happening to at least one happening. `onSync(false)` is called in the\n * opposite case: when Replicache transitions from at least one push or pull\n * happening to none happening.\n *\n * This can be used in a React like app by doing something like the following:\n *\n * ```js\n * const [syncing, setSyncing] = useState(false);\n * useEffect(() => {\n * rep.onSync = setSyncing;\n * }, [rep]);\n * ```\n */\n onSync: ((syncing: boolean) => void) | null = null;\n\n /**\n * `onClientStateNotFound` is called when the persistent client state can no\n * longer be used. This happens when:\n * - the persistent client has been garbage collected. This can happen if the\n * client has no pending mutations and has not been used for a while.\n * - the persistent store was found to be corrupt. Replicache then tries to\n * drop the database, including any pending mutations, so that a fresh one\n * is created on reload.\n *\n * The default behavior is to reload the page (using `location.reload()`). Set\n * this to `null` or provide your own function to prevent the page from\n * reloading automatically.\n */\n onClientStateNotFound: (() => void) | null = reload;\n\n /**\n * `onUpdateNeeded` is called when a code update is needed.\n *\n * A code update can be needed because:\n * - the server no longer supports the {@link pushVersion},\n * {@link pullVersion} or {@link schemaVersion} of the current code.\n * - a new Replicache client has created a new client group, because its code\n * has different mutators, indexes, schema version and/or format version\n * from this Replicache client. This is likely due to the new client having\n * newer code. A code update is needed to be able to locally sync with this\n * new Replicache client (i.e. to sync while offline, the clients can still\n * sync with each other via the server).\n *\n * The default behavior is to reload the page (using `location.reload()`). Set\n * this to `null` or provide your own function to prevent the page from\n * reloading automatically. You may want to provide your own function to\n * display a toast to inform the end user there is a new version of your app\n * available and prompting them to refresh.\n */\n onUpdateNeeded: ((reason: UpdateNeededReason) => void) | null = reload;\n\n /**\n * This gets called when we get an HTTP unauthorized (401) response from the\n * push or pull endpoint. Set this to a function that will ask your user to\n * reauthenticate.\n */\n getAuth: (() => MaybePromise<string | null | undefined>) | null | undefined =\n null;\n\n // These three are used for testing\n onPushInvoked = () => undefined;\n onBeginPull = () => undefined;\n onRecoverMutations = (r: Promise<boolean>) => r;\n\n constructor(\n options: ReplicacheOptions<MD>,\n implOptions: ReplicacheImplOptions = {},\n ) {\n validateOptions(options);\n const {\n name,\n logLevel = 'info',\n logSinks = [consoleLogSink],\n pullURL = '',\n auth,\n pushDelay = 10,\n pushURL = '',\n schemaVersion = '',\n pullInterval = 60000,\n mutators = {} as MD,\n requestOptions = {},\n puller,\n pusher,\n indexes = {},\n clientMaxAgeMs = CLIENT_MAX_INACTIVE_TIME,\n } = options;\n const {\n enableMutationRecovery = true,\n enableScheduledPersist = true,\n enableScheduledRefresh = true,\n enableRefresh = () => true,\n enablePullAndPushInOpen = true,\n enableClientGroupForking = true,\n onClientsDeleted = () => promiseVoid,\n } = implOptions;\n this.#zero = implOptions.zero;\n this.#auth = auth ?? '';\n this.pullURL = pullURL;\n this.pushURL = pushURL;\n this.name = name;\n this.schemaVersion = schemaVersion;\n this.pullInterval = pullInterval;\n this.pushDelay = pushDelay;\n this.puller = puller ?? getDefaultPuller(this);\n this.pusher = pusher ?? getDefaultPusher(this);\n\n this.#enableScheduledPersist = enableScheduledPersist;\n this.#enableScheduledRefresh = enableScheduledRefresh;\n this.#enableRefresh = enableRefresh;\n this.#enablePullAndPushInOpen = enablePullAndPushInOpen;\n\n this.#lc = createLogContext(logLevel, logSinks, {name});\n this.#lc.debug?.('Constructing Replicache', {\n name,\n 'replicache version': version,\n });\n\n this.#subscriptions = new SubscriptionsManagerImpl(\n this.#queryInternal,\n this.#lc,\n this.#closeAbortController.signal,\n );\n\n const kvStoreProvider = getKVStoreProvider(this.#lc, options.kvStore);\n this.#kvStoreProvider = kvStoreProvider;\n\n const perKVStore = kvStoreProvider.create(this.idbName);\n this.#perKVStore = perKVStore;\n\n this.#idbDatabases = new IDBDatabasesStore(kvStoreProvider.create);\n this.perdag = new StoreImpl(\n perKVStore,\n newRandomHash,\n assertHash,\n this.#onInvalidRefCount,\n );\n this.memdag = new LazyStore(\n this.perdag,\n LAZY_STORE_SOURCE_CHUNK_CACHE_SIZE_LIMIT,\n newRandomHash,\n assertHash,\n );\n\n // Use a promise-resolve pair so that we have a promise to use even before\n // we call the Open RPC.\n const readyResolver = resolver<void>();\n this.#ready = readyResolver.promise;\n\n const {minDelayMs = MIN_DELAY_MS, maxDelayMs = MAX_DELAY_MS} =\n requestOptions;\n this.#requestOptions = {maxDelayMs, minDelayMs};\n\n const visibilityWatcher = getDocumentVisibilityWatcher(\n getBrowserGlobal('document'),\n 0,\n this.#closeAbortController.signal,\n );\n\n this.#pullConnectionLoop = new ConnectionLoop(\n this.#lc.withContext('PULL'),\n new PullDelegate(this, () => this.#invokePull()),\n visibilityWatcher,\n );\n\n this.#pushConnectionLoop = new ConnectionLoop(\n this.#lc.withContext('PUSH'),\n new PushDelegate(this, () => this.#invokePush()),\n );\n\n this.mutate = this.#registerMutators(mutators);\n\n const profileIDResolver = resolver<string>();\n this.#profileIDPromise = profileIDResolver.promise;\n const clientGroupIDResolver = resolver<string>();\n this.#clientGroupIDPromise = clientGroupIDResolver.promise;\n\n if (!process.env.DISABLE_MUTATION_RECOVERY) {\n this.#mutationRecovery = new MutationRecovery({\n delegate: this,\n lc: this.#lc,\n enableMutationRecovery,\n wrapInOnlineCheck: this.#wrapInOnlineCheck.bind(this),\n wrapInReauthRetries: this.#wrapInReauthRetries.bind(this),\n isPullDisabled: this.#isPullDisabled.bind(this),\n isPushDisabled: this.#isPushDisabled.bind(this),\n clientGroupIDPromise: this.#clientGroupIDPromise,\n });\n }\n\n this.#onPersist = initOnPersistChannel(\n this.name,\n this.#closeAbortController.signal,\n persistInfo => {\n void this.#handlePersist(persistInfo);\n },\n );\n\n void this.#open(\n indexes,\n enableClientGroupForking,\n enableMutationRecovery,\n clientMaxAgeMs,\n profileIDResolver.resolve,\n clientGroupIDResolver.resolve,\n readyResolver.resolve,\n onClientsDeleted,\n ).catch(e => {\n // Whatever the reason, this open is over: `#ready` stays pending so\n // reads and writes never run against a store that failed to open, but\n // `close()` must still be able to dispose the instance. This must not\n // depend on why the open failed.\n this.#openFailed.resolve();\n if (e instanceof InvalidRefCountError) {\n // #onInvalidRefCount (called from the write's release()) already\n // started recovery: drop the database and fire onClientStateNotFound.\n // Nothing else can be done with this instance.\n this.#lc.debug?.('Open failed because the persistent store is corrupt');\n return;\n }\n throw e;\n });\n }\n\n async #open(\n indexes: IndexDefinitions,\n enableClientGroupForking: boolean,\n enableMutationRecovery: boolean,\n clientMaxAgeMs: number,\n profileIDResolver: (profileID: string) => void,\n resolveClientGroupID: (clientGroupID: ClientGroupID) => void,\n resolveReady: () => void,\n onClientsDeleted: OnClientsDeleted,\n ): Promise<void> {\n const {clientID} = this;\n // Everything up to the head write is what it takes to have a usable\n // database, including waiting out a previous instance of the same name.\n // The timer stops before the replica is loaded into Zero's IVM sources,\n // which is separate work and usually the larger of the two: a number that\n // spanned both would report a slow hydration as a slow disk.\n const openStart = performance.now();\n // If we are currently closing a Replicache instance with the same name,\n // wait for it to finish closing.\n await closingInstances.get(this.name);\n await this.#idbDatabases.getProfileID().then(profileIDResolver);\n await this.#idbDatabases.putDatabase(this.#idbDatabase);\n const [client, headHash, , isNewClientGroup] = await initClientV6(\n clientID,\n this.#lc,\n this.perdag,\n Object.keys(this.#mutatorRegistry),\n indexes,\n FormatVersion.Latest,\n enableClientGroupForking,\n );\n\n resolveClientGroupID(client.clientGroupID);\n await withWrite(this.memdag, write =>\n write.setHead(DEFAULT_HEAD_NAME, headHash),\n );\n\n // Now we have a profileID, a clientID, a clientGroupID and DB!\n const dbOpenMs = performance.now() - openStart;\n if (dbOpenMs > SLOW_DB_OPEN_THRESHOLD_MS) {\n this.#lc.warn?.(`Opening the database took ${Math.round(dbOpenMs)}ms`, {\n name: this.idbName,\n });\n } else {\n this.#lc.debug?.('Opened the database in', Math.round(dbOpenMs), 'ms');\n }\n\n await this.#zero?.init(headHash, this.memdag);\n resolveReady();\n\n if (this.#enablePullAndPushInOpen) {\n this.pull().catch(noop);\n this.push().catch(noop);\n }\n\n const {signal} = this.#closeAbortController;\n\n startHeartbeats(\n clientID,\n this.perdag,\n () => {\n this.#clientStateNotFoundOnClient(clientID);\n },\n HEARTBEAT_INTERVAL,\n this.#lc,\n signal,\n );\n initClientGC(\n clientID,\n this.perdag,\n clientMaxAgeMs,\n GC_INTERVAL,\n onClientsDeleted,\n this.#lc,\n signal,\n );\n initCollectIDBDatabases(\n this.#idbDatabases,\n this.#kvStoreProvider,\n COLLECT_IDB_INTERVAL,\n INITIAL_COLLECT_IDB_DELAY,\n 2 * clientMaxAgeMs,\n enableMutationRecovery,\n onClientsDeleted,\n this.#lc,\n signal,\n // Collection writes deleted clients into every surviving database using\n // its own dag store. When that is our database, a corrupt ref count\n // found there must reach the same recovery as writes through `perdag`.\n // A corrupt foreign database is left for its own instance to discover\n // and recover from on its next write.\n (name, createKVStore) =>\n new StoreImpl(\n createKVStore(name),\n newRandomHash,\n assertHash,\n name === this.idbName ? this.#onInvalidRefCount : undefined,\n ),\n );\n initClientGroupGC(this.perdag, enableMutationRecovery, this.#lc, signal);\n initNewClientChannel(\n this.name,\n this.idbName,\n signal,\n client.clientGroupID,\n isNewClientGroup,\n () => {\n this.#fireOnUpdateNeeded(updateNeededReasonNewClientGroup);\n },\n this.perdag,\n );\n\n setIntervalWithSignal(\n () => this.recoverMutations(),\n RECOVER_MUTATIONS_INTERVAL_MS,\n signal,\n );\n void this.recoverMutations();\n\n getBrowserGlobal('document')?.addEventListener(\n 'visibilitychange',\n this.#onVisibilityChange,\n );\n }\n\n #onVisibilityChange = async () => {\n if (this.#closed) {\n return;\n }\n\n // In case of running in a worker, we don't have a document.\n if (getBrowserGlobal('document')?.visibilityState !== 'visible') {\n return;\n }\n\n await this.#checkForClientStateNotFoundAndCallHandler();\n };\n\n async #checkForClientStateNotFoundAndCallHandler(): Promise<boolean> {\n const {clientID} = this;\n const hasClientState = await withRead(this.perdag, read =>\n persistHasClientState(clientID, read),\n );\n if (!hasClientState) {\n this.#clientStateNotFoundOnClient(clientID);\n }\n return !hasClientState;\n }\n\n /**\n * The browser profile ID for this browser profile. Every instance of Replicache\n * browser-profile-wide shares the same profile ID.\n */\n get profileID(): Promise<string> {\n return this.#profileIDPromise;\n }\n\n /**\n * The client ID for this instance of Replicache. Each instance of Replicache\n * gets a unique client ID.\n */\n get clientID(): string {\n return this.#clientID;\n }\n\n /**\n * The client group ID for this instance of Replicache. Instances of\n * Replicache will have the same client group ID if and only if they have\n * the same name, mutators, indexes, schema version, format version, and\n * browser profile.\n */\n get clientGroupID(): Promise<string> {\n return this.#clientGroupIDPromise;\n }\n\n /**\n * `onOnlineChange` is called when the {@link online} property changes. See\n * {@link online} for more details.\n */\n onOnlineChange: ((online: boolean) => void) | null = null;\n\n /**\n * A rough heuristic for whether the client is currently online. Note that\n * there is no way to know for certain whether a client is online - the next\n * request can always fail. This property returns true if the last sync attempt succeeded,\n * and false otherwise.\n */\n get online(): boolean {\n return this.#online;\n }\n\n /**\n * Whether the Replicache database has been closed. Once Replicache has been\n * closed it no longer syncs and you can no longer read or write data out of\n * it. After it has been closed it is pretty much useless and should not be\n * used any more.\n */\n get closed(): boolean {\n return this.#closed;\n }\n\n /**\n * Closes this Replicache instance.\n *\n * When closed all subscriptions end and no more read or writes are allowed.\n */\n async close(): Promise<void> {\n this.#closed = true;\n const {promise, resolve} = resolver();\n closingInstances.set(this.name, promise);\n\n this.#closeAbortController.abort();\n\n getBrowserGlobal('document')?.removeEventListener(\n 'visibilitychange',\n this.#onVisibilityChange,\n );\n\n await Promise.race([this.#ready, this.#openFailed.promise]);\n const closingPromises = [\n this.memdag.close(),\n this.perdag.close(),\n this.#idbDatabases.close(),\n ];\n\n this.#pullConnectionLoop.close();\n this.#pushConnectionLoop.close();\n\n this.#subscriptions.clear();\n\n await Promise.all(closingPromises);\n closingInstances.delete(this.name);\n resolve();\n }\n\n async maybeEndPull(syncHead: Hash, requestID: string): Promise<void> {\n for (;;) {\n if (this.#closed) {\n return;\n }\n\n await this.#ready;\n const {clientID} = this;\n const lc = this.#lc\n .withContext('maybeEndPull')\n .withContext('requestID', requestID);\n const {replayMutations, diffs, oldMainHead, mainHead} =\n await maybeEndPull<LocalMeta>(\n this.memdag,\n lc,\n syncHead,\n clientID,\n this.#subscriptions,\n FormatVersion.Latest,\n );\n\n if (!replayMutations || replayMutations.length === 0) {\n // All done.\n this.#zero?.advance(oldMainHead, mainHead, diffs.get('') ?? []);\n await this.#subscriptions.fire(diffs);\n void this.#schedulePersist();\n return;\n }\n\n // Replay.\n let zeroData = await this.#zero?.getTxData?.(syncHead);\n for (const mutation of replayMutations) {\n // TODO(greg): I'm not sure why this was in Replicache#_mutate...\n // Ensure that we run initial pending subscribe functions before starting a\n // write transaction.\n if (this.#subscriptions.hasPendingSubscriptionRuns) {\n await Promise.resolve();\n }\n const {meta} = mutation;\n const {result, zeroData: next} = await withWriteNoImplicitCommit(\n this.memdag,\n dagWrite =>\n rebaseMutationAndCommit(\n mutation,\n dagWrite,\n syncHead,\n SYNC_HEAD_NAME,\n this.#mutatorRegistry,\n lc,\n isLocalMetaDD31(meta) ? meta.clientID : clientID,\n FormatVersion.Latest,\n zeroData,\n ),\n );\n syncHead = result;\n // The fork the mutation ran against when it succeeded, or the branch we\n // came in with when it threw.\n zeroData = next;\n }\n }\n }\n\n #invokePull(): Promise<boolean> {\n if (this.#isPullDisabled()) {\n return Promise.resolve(true);\n }\n\n return this.#wrapInOnlineCheck(async () => {\n try {\n this.#changeSyncCounters(0, 1);\n const {syncHead, requestID, ok} = await this.beginPull();\n if (!ok) {\n return false;\n }\n if (syncHead !== emptyHash) {\n await this.maybeEndPull(syncHead, requestID);\n }\n } catch (e) {\n throw await this.#convertToClientStateNotFoundError(e);\n } finally {\n this.#changeSyncCounters(0, -1);\n }\n return true;\n }, 'Pull');\n }\n\n #isPullDisabled() {\n return (\n this.isClientGroupDisabled ||\n (this.pullURL === '' && isDefaultPuller(this.puller))\n );\n }\n\n async #wrapInOnlineCheck(\n f: () => Promise<boolean>,\n name: string,\n ): Promise<boolean> {\n let online = true;\n\n try {\n return await f();\n } catch (e) {\n // The error paths of beginPull and maybeEndPull need to be reworked.\n //\n // We want to distinguish between:\n // a) network requests failed -- we're offline basically\n // b) sync was aborted because one's already in progress\n // c) oh noes - something unexpected happened\n //\n // Right now, all of these come out as errors. We distinguish (b) with a\n // hacky string search. (a) and (c) are not distinguishable currently\n // because repc doesn't provide sufficient information, so we treat all\n // errors that aren't (b) as (a).\n if (e instanceof PushError || e instanceof PullError) {\n online = false;\n this.#lc.debug?.(`${name} threw:\\n`, e, '\\nwith cause:\\n', e.causedBy);\n } else if (e instanceof ReportError) {\n this.#lc.error?.(e);\n } else {\n this.#lc.info?.(`${name} threw:\\n`, e);\n }\n return false;\n } finally {\n if (this.#online !== online) {\n this.#online = online;\n this.onOnlineChange?.(online);\n if (online) {\n void this.recoverMutations();\n }\n }\n }\n }\n\n async #wrapInReauthRetries<R>(\n f: (\n requestID: string,\n requestLc: LogContext,\n ) => Promise<{\n httpRequestInfo: HTTPRequestInfo | undefined;\n result: R;\n }>,\n verb: string,\n lc: LogContext,\n preAuth: () => MaybePromise<void> = noop,\n postAuth: () => MaybePromise<void> = noop,\n ): Promise<{\n result: R;\n authFailure: boolean;\n }> {\n const {clientID} = this;\n let reauthAttempts = 0;\n let lastResult;\n lc = lc.withContext(verb);\n do {\n const requestID = newRequestID(clientID);\n const requestLc = lc.withContext('requestID', requestID);\n const {httpRequestInfo, result} = await f(requestID, requestLc);\n lastResult = result;\n if (!httpRequestInfo) {\n return {\n result,\n authFailure: false,\n };\n }\n const {errorMessage, httpStatusCode} = httpRequestInfo;\n\n if (errorMessage || httpStatusCode !== 200) {\n // TODO(arv): Maybe we should not log the server URL when the error comes\n // from a Pusher/Puller?\n requestLc.error?.(\n `Got a non 200 response doing ${verb}: ${httpStatusCode}` +\n (errorMessage ? `: ${errorMessage}` : ''),\n );\n }\n if (httpStatusCode !== httpStatusUnauthorized) {\n return {\n result,\n authFailure: false,\n };\n }\n if (!this.getAuth) {\n return {\n result,\n authFailure: true,\n };\n }\n let auth;\n try {\n await preAuth();\n auth = await this.getAuth();\n } finally {\n await postAuth();\n }\n if (auth === null || auth === undefined) {\n return {\n result,\n authFailure: true,\n };\n }\n this.auth = auth;\n reauthAttempts++;\n } while (reauthAttempts < MAX_REAUTH_TRIES);\n lc.info?.('Tried to reauthenticate too many times');\n return {\n result: lastResult,\n authFailure: true,\n };\n }\n\n #isPushDisabled() {\n return (\n this.isClientGroupDisabled ||\n (this.pushURL === '' && isDefaultPusher(this.pusher))\n );\n }\n\n async #invokePush(): Promise<boolean> {\n if (TESTING) {\n this.onPushInvoked();\n }\n if (this.#isPushDisabled()) {\n return true;\n }\n\n await this.#ready;\n const profileID = await this.#profileIDPromise;\n const {clientID} = this;\n const clientGroupID = await this.#clientGroupIDPromise;\n return this.#wrapInOnlineCheck(async () => {\n const {result: pusherResult} = await this.#wrapInReauthRetries(\n async (requestID: string, requestLc: LogContext) => {\n try {\n this.#changeSyncCounters(1, 0);\n const pusherResult = await push(\n requestID,\n this.memdag,\n requestLc,\n profileID,\n clientGroupID,\n clientID,\n this.pusher,\n this.schemaVersion,\n PUSH_VERSION_DD31,\n );\n return {\n result: pusherResult,\n httpRequestInfo: pusherResult?.httpRequestInfo,\n };\n } finally {\n this.#changeSyncCounters(-1, 0);\n }\n },\n 'push',\n this.#lc,\n );\n\n if (pusherResult === undefined) {\n // No pending mutations.\n return true;\n }\n\n const {response, httpRequestInfo} = pusherResult;\n\n if (isVersionNotSupportedResponse(response)) {\n this.#handleVersionNotSupportedResponse(response);\n } else if (isClientStateNotFoundResponse(response)) {\n await this.#clientStateNotFoundOnServer();\n }\n\n // No pushResponse means we didn't do a push because there were no\n // pending mutations.\n return httpRequestInfo.httpStatusCode === 200;\n }, 'Push');\n }\n\n #handleVersionNotSupportedResponse(response: VersionNotSupportedResponse) {\n const reason: UpdateNeededReason = {\n type: response.error,\n };\n if (response.versionType) {\n reason.versionType = response.versionType;\n }\n this.#fireOnUpdateNeeded(reason);\n }\n\n /**\n * Push pushes pending changes to the {@link pushURL}.\n *\n * You do not usually need to manually call push. If {@link pushDelay} is\n * non-zero (which it is by default) pushes happen automatically shortly after\n * mutations.\n *\n * If the server endpoint fails push will be continuously retried with an\n * exponential backoff.\n *\n * @param [now=false] If true, push will happen immediately and ignore\n * {@link pushDelay}, {@link RequestOptions.minDelayMs} as well as the\n * exponential backoff in case of errors.\n * @returns A promise that resolves when the next push completes. In case of\n * errors the first error will reject the returned promise. Subsequent errors\n * will not be reflected in the promise.\n */\n push({now = false} = {}): Promise<void> {\n return throwIfError(this.#pushConnectionLoop.send(now));\n }\n\n /**\n * Pull pulls changes from the {@link pullURL}. If there are any changes local\n * changes will get replayed on top of the new server state.\n *\n * If the server endpoint fails pull will be continuously retried with an\n * exponential backoff.\n *\n * @param [now=false] If true, pull will happen immediately and ignore\n * {@link RequestOptions.minDelayMs} as well as the exponential backoff in\n * case of errors.\n * @returns A promise that resolves when the next pull completes. In case of\n * errors the first error will reject the returned promise. Subsequent errors\n * will not be reflected in the promise.\n */\n pull({now = false} = {}): Promise<void> {\n return throwIfError(this.#pullConnectionLoop.send(now));\n }\n\n /**\n * Applies an update from the server to Replicache.\n * Throws an error if cookie does not match. In that case the server thinks\n * this client has a different cookie than it does; the caller should disconnect\n * from the server and re-register, which transmits the cookie the client actually\n * has.\n *\n * @experimental This method is under development and its semantics will change.\n */\n async poke(poke: PokeInternal): Promise<void> {\n await this.#ready;\n // TODO(MP) Previously we created a request ID here and included it with the\n // PullRequest to the server so we could tie events across client and server\n // together. Since the direction is now reversed, creating and adding a request ID\n // here is kind of silly. We should consider creating the request ID\n // on the *server* and passing it down in the poke for inclusion here in the log\n // context\n const {clientID} = this;\n const requestID = newRequestID(clientID);\n const lc = this.#lc\n .withContext('handlePullResponse')\n .withContext('requestID', requestID);\n\n const {pullResponse} = poke;\n\n if (isVersionNotSupportedResponse(pullResponse)) {\n this.#handleVersionNotSupportedResponse(pullResponse);\n return;\n }\n\n if (isClientStateNotFoundResponse(pullResponse)) {\n await this.#clientStateNotFoundOnServer();\n return;\n }\n\n const result = await handlePullResponseV1(\n lc,\n this.memdag,\n deepFreeze(poke.baseCookie),\n pullResponse,\n clientID,\n FormatVersion.Latest,\n );\n\n switch (result.type) {\n case HandlePullResponseResultEnum.Applied:\n await this.maybeEndPull(result.syncHead, requestID);\n break;\n case HandlePullResponseResultEnum.CookieMismatch:\n throw new Error(\n 'unexpected base cookie for poke: ' + JSON.stringify(poke),\n );\n case HandlePullResponseResultEnum.NoOp:\n break;\n }\n }\n\n async beginPull(): Promise<BeginPullResult> {\n if (TESTING) {\n this.onBeginPull();\n }\n await this.#ready;\n const profileID = await this.profileID;\n const {clientID} = this;\n const clientGroupID = await this.#clientGroupIDPromise;\n const {\n result: {beginPullResponse, requestID},\n } = await this.#wrapInReauthRetries(\n async (requestID: string, requestLc: LogContext) => {\n const beginPullResponse = await beginPullV1(\n profileID,\n clientID,\n clientGroupID,\n this.schemaVersion,\n this.puller,\n requestID,\n this.memdag,\n FormatVersion.Latest,\n requestLc,\n );\n return {\n result: {beginPullResponse, requestID},\n httpRequestInfo: beginPullResponse.httpRequestInfo,\n };\n },\n 'pull',\n this.#lc,\n () => this.#changeSyncCounters(0, -1),\n () => this.#changeSyncCounters(0, 1),\n );\n\n const {pullResponse} = beginPullResponse;\n if (isVersionNotSupportedResponse(pullResponse)) {\n this.#handleVersionNotSupportedResponse(pullResponse);\n } else if (isClientStateNotFoundResponse(beginPullResponse.pullResponse)) {\n await this.#clientStateNotFoundOnServer();\n }\n\n const {syncHead, httpRequestInfo} = beginPullResponse;\n return {requestID, syncHead, ok: httpRequestInfo.httpStatusCode === 200};\n }\n\n persist(): Promise<void> {\n // Prevent multiple persist calls from running at the same time.\n return this.#persistLock.withLock(async () => {\n const {clientID} = this;\n await this.#ready;\n if (this.#closed) {\n return;\n }\n try {\n await persistDD31(\n this.#lc,\n clientID,\n this.memdag,\n this.perdag,\n this.#mutatorRegistry,\n () => this.#closed,\n FormatVersion.Latest,\n this.#zero?.getTxData,\n );\n } catch (e) {\n if (e instanceof ClientStateNotFoundError) {\n this.#clientStateNotFoundOnClient(clientID);\n } else if (e instanceof InvalidRefCountError) {\n await this.#handleInvalidRefCount(e);\n // Nothing was persisted and the database is gone. Do not tell this\n // or other instances to refresh from it.\n return;\n } else if (this.#closed) {\n this.#lc.debug?.('Exception persisting during close', e);\n } else {\n throw e;\n }\n }\n\n const clientGroupID = await this.#clientGroupIDPromise;\n assert(clientGroupID, 'Expected clientGroupID to be defined');\n this.#onPersist({clientID, clientGroupID});\n });\n }\n\n async refresh(): Promise<void> {\n await this.#ready;\n const {clientID} = this;\n if (this.#closed || !this.#enableRefresh()) {\n return;\n }\n let refreshResult: Awaited<ReturnType<typeof refresh>>;\n try {\n refreshResult = await refresh(\n this.#lc,\n this.memdag,\n this.perdag,\n clientID,\n this.#mutatorRegistry,\n this.#subscriptions,\n () => this.closed,\n FormatVersion.Latest,\n this.#zero,\n );\n } catch (e) {\n if (e instanceof ClientStateNotFoundError) {\n this.#clientStateNotFoundOnClient(clientID);\n } else if (e instanceof InvalidRefCountError) {\n await this.#handleInvalidRefCount(e);\n } else if (this.#closed) {\n this.#lc.debug?.('Exception refreshing during close', e);\n } else {\n throw e;\n }\n }\n if (refreshResult !== undefined) {\n await this.#subscriptions.fire(refreshResult.diffs);\n }\n }\n\n #fireOnClientStateNotFound() {\n this.onClientStateNotFound?.();\n }\n\n #clientStateNotFoundOnClient(clientID: ClientID) {\n this.#lc.error?.(`Client state not found on client, clientID: ${clientID}`);\n this.#fireOnClientStateNotFound();\n }\n\n /**\n * Set once recovery from a corrupt database has started. Every write path\n * into the perdag (open, persist, refresh, heartbeat, GC, ...) can trip on\n * the same corrupt key, so recovery runs once and later reports await it.\n */\n #corruptDatabaseRecovery: Promise<void> | undefined;\n\n /**\n * Installed on the dag store that writes to our database. The store calls\n * it after the failing transaction has been released, so dropping the\n * database from here does not race with the rollback.\n */\n readonly #onInvalidRefCount = (e: InvalidRefCountError): void => {\n void this.#handleInvalidRefCount(e);\n };\n\n /**\n * The persistent dag store contains an invalid ref count. This means the\n * store is corrupt (due to some unknown bug) and every subsequent write that\n * touches that chunk would fail the same way. There is no way to repair it,\n * so we treat it like the client state was lost and fire\n * `onClientStateNotFound`.\n *\n * Disabling the client group is not enough: the corrupt ref count stays in\n * the underlying kv store and any later write that touches that chunk (for\n * example rewriting the `clients` chunk when a new client starts) would hit\n * it again. Instead we drop the whole database so that the reload starts\n * from a fresh store. Pending local mutations in this database are lost.\n *\n * This is expected to be exceedingly rare. Other instances sharing the\n * database are not told: they simply hit the same corrupt key (or, once\n * this instance drops the database, a generic storage error) on their own\n * next write and recover the same way then. That's an acceptable delay for\n * something we don't expect to ever happen.\n */\n #handleInvalidRefCount(e: InvalidRefCountError): Promise<void> {\n if (this.#corruptDatabaseRecovery === undefined) {\n this.#lc.error?.(\n `Client state is corrupt on client, clientID: ${this.clientID}. Dropping database ${this.idbName}`,\n e,\n );\n this.#corruptDatabaseRecovery =\n this.#dropDatabaseAndFireOnClientStateNotFound();\n }\n return this.#corruptDatabaseRecovery;\n }\n\n /**\n * Drops our database, then fires `onClientStateNotFound` so the app can\n * recover, whether or not the drop itself succeeded.\n *\n * Uses its own handle on the databases registry rather than `#idbDatabases`\n * so it works even when `close()` is already closing this instance.\n */\n async #dropDatabaseAndFireOnClientStateNotFound(): Promise<void> {\n const {idbName, clientID} = this;\n let idbDatabases: IDBDatabasesStore | undefined;\n try {\n idbDatabases = new IDBDatabasesStore(this.#kvStoreProvider.create);\n await dropDatabaseInternal(\n idbName,\n idbDatabases,\n this.#kvStoreProvider.drop,\n );\n } catch (dropError) {\n this.#lc.error?.(\n `Failed to drop database ${idbName}, clientID: ${clientID}`,\n dropError,\n );\n }\n try {\n await idbDatabases?.close();\n } catch (closeError) {\n // Closing the registry handle is best effort. The callback below must\n // fire regardless, and the drop outcome was already logged.\n this.#lc.debug?.(\n `Failed to close the databases registry after dropping ${idbName}, clientID: ${clientID}`,\n closeError,\n );\n }\n this.#fireOnClientStateNotFound();\n }\n\n async #clientStateNotFoundOnServer() {\n const clientGroupID = await this.#clientGroupIDPromise;\n this.#lc.error?.(\n `Client state not found on server, clientGroupID: ${clientGroupID}`,\n );\n await this.disableClientGroup();\n this.#fireOnClientStateNotFound();\n }\n\n async disableClientGroup(): Promise<void> {\n const clientGroupID = await this.#clientGroupIDPromise;\n assert(clientGroupID, 'Expected clientGroupID to be defined');\n this.isClientGroupDisabled = true;\n await withWrite(this.perdag, dagWrite =>\n disableClientGroup(clientGroupID, dagWrite),\n );\n }\n\n #fireOnUpdateNeeded(reason: UpdateNeededReason) {\n this.#lc.debug?.(`Update needed, reason: ${reason}`);\n this.onUpdateNeeded?.(reason);\n }\n\n async #schedulePersist(): Promise<void> {\n if (!this.#enableScheduledPersist) {\n return;\n }\n await this.#schedule('persist', this.#persistScheduler);\n }\n\n async #handlePersist(persistInfo: PersistInfo): Promise<void> {\n this.#lc.debug?.('Handling persist', persistInfo);\n const clientGroupID = await this.#clientGroupIDPromise;\n if (persistInfo.clientGroupID === clientGroupID) {\n void this.#scheduleRefresh();\n }\n }\n\n async #scheduleRefresh(): Promise<void> {\n if (!this.#enableScheduledRefresh) {\n return;\n }\n await this.#schedule('refresh from storage', this.#refreshScheduler);\n }\n\n async #schedule(name: string, scheduler: ProcessScheduler): Promise<void> {\n try {\n await scheduler.schedule();\n } catch (e) {\n if (e instanceof AbortError) {\n this.#lc.debug?.(`Scheduled ${name} did not complete before close.`);\n } else {\n this.#lc.error?.(`Error during ${name}`, e);\n }\n }\n }\n\n /**\n * Runs a refresh as soon as possible through the refresh scheduler.\n */\n runRefresh(): Promise<void> {\n return this.#refreshScheduler.run();\n }\n\n #changeSyncCounters(pushDelta: 0, pullDelta: 1 | -1): void;\n #changeSyncCounters(pushDelta: 1 | -1, pullDelta: 0): void;\n #changeSyncCounters(pushDelta: number, pullDelta: number): void {\n this.#pushCounter += pushDelta;\n this.#pullCounter += pullDelta;\n const delta = pushDelta + pullDelta;\n const counter = this.#pushCounter + this.#pullCounter;\n if ((delta === 1 && counter === 1) || counter === 0) {\n const syncing = counter > 0;\n // Run in a new microtask.\n void Promise.resolve().then(() => this.onSync?.(syncing));\n }\n }\n\n /**\n * Subscribe to the result of a {@link query}. The `body` function is\n * evaluated once and its results are returned via `onData`.\n *\n * Thereafter, each time the the result of `body` changes, `onData` is fired\n * again with the new result.\n *\n * `subscribe()` goes to significant effort to avoid extraneous work\n * re-evaluating subscriptions:\n *\n * 1. subscribe tracks the keys that `body` accesses each time it runs. `body`\n * is only re-evaluated when those keys change.\n * 2. subscribe only re-fires `onData` in the case that a result changes by\n * way of the `isEqual` option which defaults to doing a deep JSON value\n * equality check.\n *\n * Because of (1), `body` must be a pure function of the data in Replicache.\n * `body` must not access anything other than the `tx` parameter passed to it.\n *\n * Although subscribe is as efficient as it can be, it is somewhat constrained\n * by the goal of returning an arbitrary computation of the cache. For even\n * better performance (but worse dx), see {@link experimentalWatch}.\n *\n * If an error occurs in the `body` the `onError` function is called if\n * present. Otherwise, the error is logged at log level 'error'.\n *\n * To cancel the subscription, call the returned function.\n *\n * @param body The function to evaluate to get the value to pass into\n * `onData`.\n * @param options Options is either a function or an object. If it is a\n * function it is equivalent to passing it as the `onData` property of an\n * object.\n */\n subscribe<R>(\n body: (tx: ReadTransaction) => Promise<R>,\n options: SubscribeOptions<R> | ((result: R) => void),\n ): () => void {\n if (typeof options === 'function') {\n options = {onData: options};\n }\n\n const {onData, onError, onDone, isEqual} = options;\n return this.#subscriptions.add(\n new SubscriptionImpl(body, onData, onError, onDone, isEqual),\n );\n }\n\n /**\n * Watches Replicache for changes.\n *\n * The `callback` gets called whenever the underlying data changes and the\n * `key` changes matches the `prefix` of {@link ExperimentalWatchIndexOptions} or\n * {@link ExperimentalWatchNoIndexOptions} if present. If a change\n * occurs to the data but the change does not impact the key space the\n * callback is not called. In other words, the callback is never called with\n * an empty diff.\n *\n * This gets called after commit (a mutation or a rebase).\n *\n * @experimental This method is under development and its semantics will\n * change.\n */\n experimentalWatch(callback: WatchNoIndexCallback): () => void;\n experimentalWatch<Options extends WatchOptions>(\n callback: WatchCallbackForOptions<Options>,\n options?: Options,\n ): () => void;\n experimentalWatch<Options extends WatchOptions>(\n callback: WatchCallbackForOptions<Options>,\n options?: Options,\n ): () => void {\n return this.#subscriptions.add(\n new WatchSubscription(callback as WatchCallback, options),\n );\n }\n\n /**\n * Query is used for read transactions. It is recommended to use transactions\n * to ensure you get a consistent view across multiple calls to `get`, `has`\n * and `scan`.\n */\n query<R>(body: (tx: ReadTransaction) => Promise<R> | R): Promise<R> {\n return this.#queryInternal(body);\n }\n\n get cookie(): Promise<Cookie> {\n return this.#ready.then(() =>\n withRead(this.memdag, async dagRead => {\n const mainHeadHash = await dagRead.getHead(DEFAULT_HEAD_NAME);\n if (!mainHeadHash) {\n throw new Error('Internal no main head found');\n }\n const baseSnapshot = await baseSnapshotFromHash(mainHeadHash, dagRead);\n const baseSnapshotMeta = baseSnapshot.meta;\n const cookie = baseSnapshotMeta.cookieJSON;\n assertCookie(cookie);\n return cookie;\n }),\n );\n }\n\n #queryInternal: QueryInternal = async body => {\n await this.#ready;\n const {clientID} = this;\n return withRead(this.memdag, async dagRead => {\n try {\n const dbRead = await readFromDefaultHead(dagRead, FormatVersion.Latest);\n const tx = new ReadTransactionImpl(clientID, dbRead, this.#lc);\n return await body(tx);\n } catch (ex) {\n throw await this.#convertToClientStateNotFoundError(ex);\n }\n });\n };\n\n #register<Return extends ReadonlyJSONValue | void, Args extends JSONValue>(\n name: string,\n mutatorImpl: (tx: WriteTransaction, args?: Args) => MaybePromise<Return>,\n ): (\n args?: Args,\n ) => Promise<Return> | {client: Promise<Return>; server: Promise<unknown>} {\n this.#mutatorRegistry[name] = mutatorImpl as (\n tx: WriteTransaction,\n args: JSONValue | undefined,\n ) => Promise<void | JSONValue>;\n\n return (\n args?: Args,\n ):\n | Promise<Return>\n | {client: Promise<Return>; server: Promise<unknown>} => {\n // DO NOT track CRUD mutations as they do not receive responses from\n // the server.\n const trackingData =\n name === '_zero_crud' ? undefined : this.#zero?.trackMutation();\n\n const result = this.#mutate(\n trackingData,\n name,\n mutatorImpl,\n args,\n performance.now(),\n );\n\n if (trackingData) {\n return {\n client: result,\n server: trackingData.serverPromise,\n };\n }\n\n return result;\n };\n }\n\n #registerMutators<\n M extends {\n [key: string]: (\n tx: WriteTransaction,\n args?: ReadonlyJSONValue,\n ) => MutatorReturn;\n },\n >(regs: M): MakeMutators<M> {\n type Mut = MakeMutators<M>;\n const rv: Partial<Mut> = Object.create(null);\n for (const k in regs) {\n rv[k] = this.#register(k, regs[k]) as MakeMutator<M[typeof k]>;\n }\n return rv as Mut;\n }\n\n async #mutate<\n R extends ReadonlyJSONValue | void,\n A extends ReadonlyJSONValue,\n >(\n trackingData: MutationTrackingData | undefined,\n name: string,\n mutatorImpl: (tx: WriteTransaction, args?: A) => MaybePromise<R>,\n args: A | undefined,\n timestamp: number,\n ): Promise<R> {\n const frozenArgs = deepFreeze(args ?? null);\n\n // Ensure that we run initial pending subscribe functions before starting a\n // write transaction.\n if (this.#subscriptions.hasPendingSubscriptionRuns) {\n await Promise.resolve();\n }\n\n await this.#ready;\n const {clientID} = this;\n return withWriteNoImplicitCommit(this.memdag, async dagWrite => {\n try {\n let result: R;\n let newHead: Hash;\n let diffs: DiffsMap;\n let headHash: Hash;\n try {\n headHash = await mustGetHeadHash(DEFAULT_HEAD_NAME, dagWrite);\n const originalHash = null;\n\n const dbWrite = await newWriteLocal(\n headHash,\n name,\n frozenArgs,\n originalHash,\n dagWrite,\n timestamp,\n clientID,\n FormatVersion.Latest,\n );\n\n const mutationID = await dbWrite.getMutationID();\n const tx = new WriteTransactionImpl(\n clientID,\n mutationID,\n 'initial',\n await this.#zero?.getTxData(headHash, {\n openLazyRead: dagWrite,\n }),\n dbWrite,\n this.#lc,\n );\n\n if (trackingData) {\n this.#zero?.mutationIDAssigned(\n trackingData.ephemeralID,\n mutationID,\n );\n }\n\n result = await mutatorImpl(tx, args);\n\n throwIfClosed(dbWrite);\n const lastMutationID = await dbWrite.getMutationID();\n [newHead, diffs] = await dbWrite.commitWithDiffs(\n DEFAULT_HEAD_NAME,\n this.#subscriptions,\n );\n\n // Update this after the commit in case the commit fails.\n this.lastMutationID = lastMutationID;\n } catch (e) {\n // If we threw before we could persist the mutation\n // then we need to reject the mutation.\n if (trackingData) {\n this.#zero?.rejectMutation(trackingData.ephemeralID, e);\n }\n throw e;\n }\n\n this.#zero?.advance(headHash, newHead, diffs.get('') ?? []);\n\n // Send is not supposed to reject\n this.#pushConnectionLoop.send(false).catch(() => void 0);\n await this.#subscriptions.fire(diffs);\n void this.#schedulePersist();\n return result;\n } catch (ex) {\n throw await this.#convertToClientStateNotFoundError(ex);\n }\n });\n }\n\n /**\n * In the case we get a ChunkNotFoundError we check if the client got garbage\n * collected and if so change the error to a ClientStateNotFoundError instead\n */\n async #convertToClientStateNotFoundError(ex: unknown): Promise<unknown> {\n if (\n ex instanceof ChunkNotFoundError &&\n (await this.#checkForClientStateNotFoundAndCallHandler())\n ) {\n return new ClientStateNotFoundError(this.clientID);\n }\n\n return ex;\n }\n\n recoverMutations(): Promise<boolean> | void {\n if (!process.env.DISABLE_MUTATION_RECOVERY) {\n // oxlint-disable-next-line no-non-null-assertion\n const result = this.#mutationRecovery!.recoverMutations(\n this.#ready,\n this.perdag,\n this.#idbDatabase,\n this.#idbDatabases,\n this.#kvStoreProvider.create,\n );\n if (TESTING) {\n void this.onRecoverMutations(result);\n }\n return result;\n }\n }\n\n /**\n * List of pending mutations. The order of this is from oldest to newest.\n *\n * Gives a list of local mutations that have `mutationID` >\n * `syncHead.mutationID` that exists on the main client group.\n *\n * @experimental This method is experimental and may change in the future.\n */\n experimentalPendingMutations(): Promise<readonly PendingMutation[]> {\n return withRead(this.memdag, pendingMutationsForAPI);\n }\n}\n\n// This map is used to keep track of closing instances of Replicache. When an\n// instance is opening we wait for any currently closing instances.\nconst closingInstances: Map<string, Promise<unknown>> = new Map();\n\nasync function throwIfError(p: Promise<undefined | {error: unknown}>) {\n const res = await p;\n if (res) {\n throw res.error;\n }\n}\n\nfunction reload(): void {\n if (typeof location !== 'undefined') {\n location.reload();\n }\n}\n\nfunction validateOptions<MD extends MutatorDefs>(\n options: ReplicacheOptions<MD>,\n): void {\n const {name, clientMaxAgeMs} = options;\n if (typeof name !== 'string' || !name) {\n throw new TypeError('name is required and must be non-empty');\n }\n\n if (clientMaxAgeMs !== undefined) {\n const min = Math.max(GC_INTERVAL, HEARTBEAT_INTERVAL);\n if (typeof clientMaxAgeMs !== 'number' || clientMaxAgeMs <= min) {\n throw new TypeError(\n `clientAgeMaxMs must be a number larger than ${min}ms`,\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyIA,IAAM,mBAAmB;AAEzB,IAAM,0BAA0B;AAChC,IAAM,0BAA0B;AAEhC,IAAM,sBAAsB;AAC5B,IAAM,sBAAsB;;;;;;AAO5B,IAAM,4BAA4B;AAElC,IAAM,2CAA2C,MAAM,KAAK;AAE5D,IAAM,gCAAgC,MAAS;AAE/C,IAAM,aAAa,CAEnB;AAEA,IAAM,mCAAuD,EAC3D,MAAM,iBACR;AA0DA,IAAa,iBAAb,MAAyD;;CAEvD;;CAGA;;CAGA;;CAGA;CAEA;CACA;;;;;CAMA,wBAAwB;CAExB;CACA;CAEA,iBAAyB;;;;;CAMzB,IAAI,UAAkB;EACpB,OAAO,YAAY,KAAK,MAAM,KAAK,aAAa;CAClD;;;;;;CAOA,IAAI,UAAmB;EACrB,OAAO,KAAKG;CACd;CAEA,IAAI,KAAK,MAAc;EACrB,IAAI,KAAKC,OACP,KAAKA,MAAM,OAAO;EAGpB,KAAKC,QAAQ;CACf;CAEA,IAAI,OAAO;EACT,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,MAAM;CAClB,IAAI,KACF,MAAM,IAAI;AAEd;AAEA,SAAS,SAAe;CACtB,IAAI,OAAO,aAAa,aACtB,SAAS,OAAO;AAEpB;AAEA,SAAS,gBACP,SACM;CACN,MAAM,EAAC,MAAM,mBAAkB;CAC/B,IAAI,OAAO,SAAS,YAAY,CAAC,MAC/B,MAAM,IAAI,UAAU,wCAAwC;CAG9D,IAAI,mBAAmB,KAAA,GAAW;EAChC,MAAM,MAAM,KAAK,IAAI,aAAa,kBAAkB;EACpD,IAAI,OAAO,mBAAmB,YAAY,kBAAkB,KAC1D,MAAM,IAAI,UACR,+CAA+C,IAAI,GACrD;CAEJ;AACF"}
|
|
1
|
+
{"version":3,"file":"replicache-impl.js","names":["#subscriptions","#mutationRecovery","#kvStoreProvider","#zero","#auth","#idbDatabase","#clientID","#ready","#profileIDPromise","#clientGroupIDPromise","#mutatorRegistry","#requestOptions","#idbDatabases","#lc","#closeAbortController","#persistLock","#enableScheduledPersist","#enableScheduledRefresh","#enableRefresh","#enablePullAndPushInOpen","#onPersist","#queryInternal","#pullConnectionLoop","#invokePull","#pushConnectionLoop","#invokePush","#registerMutators","#wrapInOnlineCheck","#wrapInReauthRetries","#isPullDisabled","#isPushDisabled","#handlePersist","#open","#clientStateNotFoundOnClient","#fireOnUpdateNeeded","#onVisibilityChange","#closed","#checkForClientStateNotFoundAndCallHandler","#online","#schedulePersist","#changeSyncCounters","#convertToClientStateNotFoundError","#handleVersionNotSupportedResponse","#clientStateNotFoundOnServer","#fireOnClientStateNotFound","#schedule","#persistScheduler","#scheduleRefresh","#refreshScheduler","#pushCounter","#pullCounter","#mutate","#register"],"sources":["../../../../replicache/src/replicache-impl.ts"],"sourcesContent":["import {Lock} from '@rocicorp/lock';\nimport type {LogContext} from '@rocicorp/logger';\nimport {consoleLogSink} from '@rocicorp/logger';\nimport {resolver} from '@rocicorp/resolver';\nimport {AbortError} from '../../shared/src/abort-error.ts';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {getBrowserGlobal} from '../../shared/src/browser-env.ts';\nimport {getDocumentVisibilityWatcher} from '../../shared/src/document-visible.ts';\nimport type {JSONValue, ReadonlyJSONValue} from '../../shared/src/json.ts';\nimport {promiseVoid} from '../../shared/src/resolved-promises.ts';\nimport {TESTING} from '../../shared/src/testing.ts';\nimport type {MaybePromise} from '../../shared/src/types.ts';\nimport {PullDelegate, PushDelegate} from './connection-loop-delegates.ts';\nimport {ConnectionLoop, MAX_DELAY_MS, MIN_DELAY_MS} from './connection-loop.ts';\nimport {assertCookie, type Cookie} from './cookies.ts';\nimport {LazyStore} from './dag/lazy-store.ts';\nimport {StoreImpl} from './dag/store-impl.ts';\nimport {ChunkNotFoundError, mustGetHeadHash, type Store} from './dag/store.ts';\nimport {\n baseSnapshotFromHash,\n DEFAULT_HEAD_NAME,\n isLocalMetaDD31,\n type LocalMeta,\n} from './db/commit.ts';\nimport {readFromDefaultHead} from './db/read.ts';\nimport {rebaseMutationAndCommit} from './db/rebase.ts';\nimport {newWriteLocal} from './db/write.ts';\nimport {\n isClientStateNotFoundResponse,\n isVersionNotSupportedResponse,\n type VersionNotSupportedResponse,\n} from './error-responses.ts';\nimport * as FormatVersion from './format-version-enum.ts';\nimport {deepFreeze} from './frozen-json.ts';\nimport {getDefaultPuller, isDefaultPuller} from './get-default-puller.ts';\nimport {getDefaultPusher, isDefaultPusher} from './get-default-pusher.ts';\nimport {getKVStoreProvider} from './get-kv-store-provider.ts';\nimport {assertHash, emptyHash, type Hash, newRandomHash} from './hash.ts';\nimport type {HTTPRequestInfo} from './http-request-info.ts';\nimport {httpStatusUnauthorized} from './http-status-unauthorized.ts';\nimport type {IndexDefinitions} from './index-defs.ts';\nimport type {StoreProvider} from './kv/store.ts';\nimport {createLogContext} from './log-options.ts';\nimport {makeIDBName} from './make-idb-name.ts';\nimport {MutationRecovery} from './mutation-recovery.ts';\nimport {initNewClientChannel} from './new-client-channel.ts';\nimport {\n initOnPersistChannel,\n type OnPersist,\n type PersistInfo,\n} from './on-persist-channel.ts';\nimport {\n type PendingMutation,\n pendingMutationsForAPI,\n} from './pending-mutations.ts';\nimport {\n CLIENT_MAX_INACTIVE_TIME,\n GC_INTERVAL,\n initClientGC,\n} from './persist/client-gc.ts';\nimport {initClientGroupGC} from './persist/client-group-gc.ts';\nimport {disableClientGroup} from './persist/client-groups.ts';\nimport {\n ClientStateNotFoundError,\n initClientV6,\n type OnClientsDeleted,\n hasClientState as persistHasClientState,\n} from './persist/clients.ts';\nimport {\n COLLECT_IDB_INTERVAL,\n initCollectIDBDatabases,\n INITIAL_COLLECT_IDB_DELAY,\n} from './persist/collect-idb-databases.ts';\nimport {HEARTBEAT_INTERVAL, startHeartbeats} from './persist/heartbeat.ts';\nimport {\n IDBDatabasesStore,\n type IndexedDBDatabase,\n} from './persist/idb-databases-store.ts';\nimport {makeClientID} from './persist/make-client-id.ts';\nimport {persistDD31} from './persist/persist.ts';\nimport {refresh} from './persist/refresh.ts';\nimport {ProcessScheduler} from './process-scheduler.ts';\nimport type {Puller} from './puller.ts';\nimport {type Pusher, PushError} from './pusher.ts';\nimport type {\n MutationTrackingData,\n ReplicacheOptions,\n ZeroOption,\n} from './replicache-options.ts';\nimport {ReportError} from './report-error.ts';\nimport {setIntervalWithSignal} from './set-interval-with-signal.ts';\nimport {\n type SubscribeOptions,\n SubscriptionImpl,\n type SubscriptionsManager,\n SubscriptionsManagerImpl,\n type WatchCallback,\n type WatchCallbackForOptions,\n type WatchNoIndexCallback,\n type WatchOptions,\n WatchSubscription,\n} from './subscriptions.ts';\nimport type {DiffsMap} from './sync/diff.ts';\nimport * as HandlePullResponseResultEnum from './sync/handle-pull-response-result-type-enum.ts';\nimport type {ClientGroupID, ClientID} from './sync/ids.ts';\nimport {PullError} from './sync/pull-error.ts';\nimport {beginPullV1, handlePullResponseV1, maybeEndPull} from './sync/pull.ts';\nimport {push, PUSH_VERSION_DD31} from './sync/push.ts';\nimport {newRequestID} from './sync/request-id.ts';\nimport {SYNC_HEAD_NAME} from './sync/sync-head-name.ts';\nimport {throwIfClosed} from './transaction-closed-error.ts';\nimport type {ReadTransaction, WriteTransaction} from './transactions.ts';\nimport {ReadTransactionImpl, WriteTransactionImpl} from './transactions.ts';\nimport type {\n BeginPullResult,\n MakeMutator,\n MakeMutators,\n MutatorDefs,\n MutatorReturn,\n PokeInternal,\n QueryInternal,\n RequestOptions,\n UpdateNeededReason,\n} from './types.ts';\nimport {version} from './version.ts';\nimport {\n withRead,\n withWrite,\n withWriteNoImplicitCommit,\n} from './with-transactions.ts';\n\n/**\n * The maximum number of time to call out to getAuth before giving up\n * and throwing an error.\n */\nconst MAX_REAUTH_TRIES = 8;\n\nconst PERSIST_IDLE_TIMEOUT_MS = 1000;\nconst REFRESH_IDLE_TIMEOUT_MS = 1000;\n\nconst PERSIST_THROTTLE_MS = 500;\nconst REFRESH_THROTTLE_MS = 500;\n\nconst LAZY_STORE_SOURCE_CHUNK_CACHE_SIZE_LIMIT = 100 * 2 ** 20; // 100 MB\n\nconst RECOVER_MUTATIONS_INTERVAL_MS = 5 * 60 * 1000; // 5 mins\n\nconst noop = () => {\n // noop\n};\n\nconst updateNeededReasonNewClientGroup: UpdateNeededReason = {\n type: 'NewClientGroup',\n} as const;\n\n/** @deprecated Not used any more */\nexport interface MakeSubscriptionsManager {\n (queryInternal: QueryInternal, lc: LogContext): SubscriptionsManager;\n}\n\nexport interface ReplicacheImplOptions {\n /**\n * Defaults to true.\n */\n enableMutationRecovery?: boolean | undefined;\n\n /**\n * Defaults to true.\n */\n enableScheduledPersist?: boolean | undefined;\n\n /**\n * Defaults to true.\n */\n enableScheduledRefresh?: boolean | undefined;\n\n /**\n * Defaults to `() => true`.\n */\n enableRefresh?: (() => boolean) | undefined;\n\n /**\n * Defaults to true.\n */\n enablePullAndPushInOpen?: boolean | undefined;\n\n /**\n * @deprecated Not used anymore.\n */\n makeSubscriptionsManager?: unknown;\n\n /**\n * Default is `true`. If `false` if an exact match client group\n * is not found, a new client group is always made instead of forking\n * from an existing client group.\n */\n enableClientGroupForking?: boolean | undefined;\n\n /**\n * Callback for when Replicache has deleted clients.\n */\n onClientsDeleted?: OnClientsDeleted | undefined;\n\n /**\n * Internal option used by Zero.\n * Replicache will call this to and, if zero is enabled, will\n * invoke various hooks to allow Zero the keep IVM in sync with Replicache's b-trees.\n */\n zero?: ZeroOption | undefined;\n}\n\nexport class ReplicacheImpl<MD extends MutatorDefs = {}> {\n /** The URL to use when doing a pull request. */\n pullURL: string;\n\n /** The URL to use when doing a push request. */\n pushURL: string;\n\n /** The authorization token used when doing a push request. */\n #auth: string;\n\n /** The name of the Replicache database. Populated by {@link ReplicacheOptions#name}. */\n readonly name: string;\n\n readonly #subscriptions: SubscriptionsManager;\n readonly #mutationRecovery: MutationRecovery | undefined;\n\n /**\n * Client groups gets disabled when the server does not know about it.\n * A disabled client group prevents the client from pushing and pulling.\n */\n isClientGroupDisabled = false;\n\n readonly #kvStoreProvider: StoreProvider;\n\n lastMutationID: number = 0;\n\n /**\n * This is the name Replicache uses for the IndexedDB database where data is\n * stored.\n */\n get idbName(): string {\n return makeIDBName(this.name, this.schemaVersion);\n }\n\n set auth(auth: string) {\n if (this.#zero) {\n this.#zero.auth = auth;\n }\n\n this.#auth = auth;\n }\n\n get auth() {\n return this.#auth;\n }\n\n /** The schema version of the data understood by this application. */\n readonly schemaVersion: string;\n\n get #idbDatabase(): IndexedDBDatabase {\n return {\n name: this.idbName,\n replicacheName: this.name,\n replicacheFormatVersion: FormatVersion.Latest,\n schemaVersion: this.schemaVersion,\n };\n }\n #closed = false;\n #online = true;\n readonly #clientID = makeClientID();\n readonly #ready: Promise<void>;\n readonly #profileIDPromise: Promise<string>;\n readonly #clientGroupIDPromise: Promise<string>;\n readonly #mutatorRegistry: MutatorDefs = {};\n\n /**\n * The mutators that was registered in the constructor.\n */\n readonly mutate: MakeMutators<MD>;\n\n // Number of pushes/pulls at the moment.\n #pushCounter = 0;\n #pullCounter = 0;\n\n #pullConnectionLoop: ConnectionLoop;\n #pushConnectionLoop: ConnectionLoop;\n\n /**\n * The duration between each periodic {@link pull}. Setting this to `null`\n * disables periodic pull completely. Pull will still happen if you call\n * {@link pull} manually.\n */\n pullInterval: number | null;\n\n /**\n * The delay between when a change is made to Replicache and when Replicache\n * attempts to push that change.\n */\n pushDelay: number;\n\n readonly #requestOptions: Required<RequestOptions>;\n\n /**\n * The function to use to pull data from the server.\n */\n puller: Puller;\n\n /**\n * The function to use to push data to the server.\n */\n pusher: Pusher;\n\n readonly memdag: LazyStore;\n readonly perdag: Store;\n readonly #idbDatabases: IDBDatabasesStore;\n readonly #lc: LogContext;\n readonly #zero: ZeroOption | undefined;\n\n readonly #closeAbortController = new AbortController();\n\n readonly #persistLock = new Lock();\n readonly #enableScheduledPersist: boolean;\n readonly #enableScheduledRefresh: boolean;\n readonly #enableRefresh: () => boolean;\n readonly #enablePullAndPushInOpen: boolean;\n #persistScheduler = new ProcessScheduler(\n () => this.persist(),\n PERSIST_IDLE_TIMEOUT_MS,\n PERSIST_THROTTLE_MS,\n this.#closeAbortController.signal,\n );\n readonly #onPersist: OnPersist;\n #refreshScheduler = new ProcessScheduler(\n () => this.refresh(),\n REFRESH_IDLE_TIMEOUT_MS,\n REFRESH_THROTTLE_MS,\n this.#closeAbortController.signal,\n );\n\n /**\n * The options used to control the {@link pull} and push request behavior. This\n * object is live so changes to it will affect the next pull or push call.\n */\n get requestOptions(): Required<RequestOptions> {\n return this.#requestOptions;\n }\n\n /**\n * `onSync(true)` is called when Replicache transitions from no push or pull\n * happening to at least one happening. `onSync(false)` is called in the\n * opposite case: when Replicache transitions from at least one push or pull\n * happening to none happening.\n *\n * This can be used in a React like app by doing something like the following:\n *\n * ```js\n * const [syncing, setSyncing] = useState(false);\n * useEffect(() => {\n * rep.onSync = setSyncing;\n * }, [rep]);\n * ```\n */\n onSync: ((syncing: boolean) => void) | null = null;\n\n /**\n * `onClientStateNotFound` is called when the persistent client has been\n * garbage collected. This can happen if the client has no pending mutations\n * and has not been used for a while.\n *\n * The default behavior is to reload the page (using `location.reload()`). Set\n * this to `null` or provide your own function to prevent the page from\n * reloading automatically.\n */\n onClientStateNotFound: (() => void) | null = reload;\n\n /**\n * `onUpdateNeeded` is called when a code update is needed.\n *\n * A code update can be needed because:\n * - the server no longer supports the {@link pushVersion},\n * {@link pullVersion} or {@link schemaVersion} of the current code.\n * - a new Replicache client has created a new client group, because its code\n * has different mutators, indexes, schema version and/or format version\n * from this Replicache client. This is likely due to the new client having\n * newer code. A code update is needed to be able to locally sync with this\n * new Replicache client (i.e. to sync while offline, the clients can still\n * sync with each other via the server).\n *\n * The default behavior is to reload the page (using `location.reload()`). Set\n * this to `null` or provide your own function to prevent the page from\n * reloading automatically. You may want to provide your own function to\n * display a toast to inform the end user there is a new version of your app\n * available and prompting them to refresh.\n */\n onUpdateNeeded: ((reason: UpdateNeededReason) => void) | null = reload;\n\n /**\n * This gets called when we get an HTTP unauthorized (401) response from the\n * push or pull endpoint. Set this to a function that will ask your user to\n * reauthenticate.\n */\n getAuth: (() => MaybePromise<string | null | undefined>) | null | undefined =\n null;\n\n // These three are used for testing\n onPushInvoked = () => undefined;\n onBeginPull = () => undefined;\n onRecoverMutations = (r: Promise<boolean>) => r;\n\n constructor(\n options: ReplicacheOptions<MD>,\n implOptions: ReplicacheImplOptions = {},\n ) {\n validateOptions(options);\n const {\n name,\n logLevel = 'info',\n logSinks = [consoleLogSink],\n pullURL = '',\n auth,\n pushDelay = 10,\n pushURL = '',\n schemaVersion = '',\n pullInterval = 60000,\n mutators = {} as MD,\n requestOptions = {},\n puller,\n pusher,\n indexes = {},\n clientMaxAgeMs = CLIENT_MAX_INACTIVE_TIME,\n } = options;\n const {\n enableMutationRecovery = true,\n enableScheduledPersist = true,\n enableScheduledRefresh = true,\n enableRefresh = () => true,\n enablePullAndPushInOpen = true,\n enableClientGroupForking = true,\n onClientsDeleted = () => promiseVoid,\n } = implOptions;\n this.#zero = implOptions.zero;\n this.#auth = auth ?? '';\n this.pullURL = pullURL;\n this.pushURL = pushURL;\n this.name = name;\n this.schemaVersion = schemaVersion;\n this.pullInterval = pullInterval;\n this.pushDelay = pushDelay;\n this.puller = puller ?? getDefaultPuller(this);\n this.pusher = pusher ?? getDefaultPusher(this);\n\n this.#enableScheduledPersist = enableScheduledPersist;\n this.#enableScheduledRefresh = enableScheduledRefresh;\n this.#enableRefresh = enableRefresh;\n this.#enablePullAndPushInOpen = enablePullAndPushInOpen;\n\n this.#lc = createLogContext(logLevel, logSinks, {name});\n this.#lc.debug?.('Constructing Replicache', {\n name,\n 'replicache version': version,\n });\n\n this.#subscriptions = new SubscriptionsManagerImpl(\n this.#queryInternal,\n this.#lc,\n this.#closeAbortController.signal,\n );\n\n const kvStoreProvider = getKVStoreProvider(this.#lc, options.kvStore);\n this.#kvStoreProvider = kvStoreProvider;\n\n const perKVStore = kvStoreProvider.create(this.idbName);\n\n this.#idbDatabases = new IDBDatabasesStore(kvStoreProvider.create);\n this.perdag = new StoreImpl(perKVStore, newRandomHash, assertHash);\n this.memdag = new LazyStore(\n this.perdag,\n LAZY_STORE_SOURCE_CHUNK_CACHE_SIZE_LIMIT,\n newRandomHash,\n assertHash,\n );\n\n // Use a promise-resolve pair so that we have a promise to use even before\n // we call the Open RPC.\n const readyResolver = resolver<void>();\n this.#ready = readyResolver.promise;\n\n const {minDelayMs = MIN_DELAY_MS, maxDelayMs = MAX_DELAY_MS} =\n requestOptions;\n this.#requestOptions = {maxDelayMs, minDelayMs};\n\n const visibilityWatcher = getDocumentVisibilityWatcher(\n getBrowserGlobal('document'),\n 0,\n this.#closeAbortController.signal,\n );\n\n this.#pullConnectionLoop = new ConnectionLoop(\n this.#lc.withContext('PULL'),\n new PullDelegate(this, () => this.#invokePull()),\n visibilityWatcher,\n );\n\n this.#pushConnectionLoop = new ConnectionLoop(\n this.#lc.withContext('PUSH'),\n new PushDelegate(this, () => this.#invokePush()),\n );\n\n this.mutate = this.#registerMutators(mutators);\n\n const profileIDResolver = resolver<string>();\n this.#profileIDPromise = profileIDResolver.promise;\n const clientGroupIDResolver = resolver<string>();\n this.#clientGroupIDPromise = clientGroupIDResolver.promise;\n\n if (!process.env.DISABLE_MUTATION_RECOVERY) {\n this.#mutationRecovery = new MutationRecovery({\n delegate: this,\n lc: this.#lc,\n enableMutationRecovery,\n wrapInOnlineCheck: this.#wrapInOnlineCheck.bind(this),\n wrapInReauthRetries: this.#wrapInReauthRetries.bind(this),\n isPullDisabled: this.#isPullDisabled.bind(this),\n isPushDisabled: this.#isPushDisabled.bind(this),\n clientGroupIDPromise: this.#clientGroupIDPromise,\n });\n }\n\n this.#onPersist = initOnPersistChannel(\n this.name,\n this.#closeAbortController.signal,\n persistInfo => {\n void this.#handlePersist(persistInfo);\n },\n );\n\n void this.#open(\n indexes,\n enableClientGroupForking,\n enableMutationRecovery,\n clientMaxAgeMs,\n profileIDResolver.resolve,\n clientGroupIDResolver.resolve,\n readyResolver.resolve,\n onClientsDeleted,\n );\n }\n\n async #open(\n indexes: IndexDefinitions,\n enableClientGroupForking: boolean,\n enableMutationRecovery: boolean,\n clientMaxAgeMs: number,\n profileIDResolver: (profileID: string) => void,\n resolveClientGroupID: (clientGroupID: ClientGroupID) => void,\n resolveReady: () => void,\n onClientsDeleted: OnClientsDeleted,\n ): Promise<void> {\n const {clientID} = this;\n // If we are currently closing a Replicache instance with the same name,\n // wait for it to finish closing.\n await closingInstances.get(this.name);\n await this.#idbDatabases.getProfileID().then(profileIDResolver);\n await this.#idbDatabases.putDatabase(this.#idbDatabase);\n const [client, headHash, , isNewClientGroup] = await initClientV6(\n clientID,\n this.#lc,\n this.perdag,\n Object.keys(this.#mutatorRegistry),\n indexes,\n FormatVersion.Latest,\n enableClientGroupForking,\n );\n\n resolveClientGroupID(client.clientGroupID);\n await withWrite(this.memdag, write =>\n write.setHead(DEFAULT_HEAD_NAME, headHash),\n );\n\n // Now we have a profileID, a clientID, a clientGroupID and DB!\n await this.#zero?.init(headHash, this.memdag);\n resolveReady();\n\n if (this.#enablePullAndPushInOpen) {\n this.pull().catch(noop);\n this.push().catch(noop);\n }\n\n const {signal} = this.#closeAbortController;\n\n startHeartbeats(\n clientID,\n this.perdag,\n () => {\n this.#clientStateNotFoundOnClient(clientID);\n },\n HEARTBEAT_INTERVAL,\n this.#lc,\n signal,\n );\n initClientGC(\n clientID,\n this.perdag,\n clientMaxAgeMs,\n GC_INTERVAL,\n onClientsDeleted,\n this.#lc,\n signal,\n );\n initCollectIDBDatabases(\n this.#idbDatabases,\n this.#kvStoreProvider,\n COLLECT_IDB_INTERVAL,\n INITIAL_COLLECT_IDB_DELAY,\n 2 * clientMaxAgeMs,\n enableMutationRecovery,\n onClientsDeleted,\n this.#lc,\n signal,\n );\n initClientGroupGC(this.perdag, enableMutationRecovery, this.#lc, signal);\n initNewClientChannel(\n this.name,\n this.idbName,\n signal,\n client.clientGroupID,\n isNewClientGroup,\n () => {\n this.#fireOnUpdateNeeded(updateNeededReasonNewClientGroup);\n },\n this.perdag,\n );\n\n setIntervalWithSignal(\n () => this.recoverMutations(),\n RECOVER_MUTATIONS_INTERVAL_MS,\n signal,\n );\n void this.recoverMutations();\n\n getBrowserGlobal('document')?.addEventListener(\n 'visibilitychange',\n this.#onVisibilityChange,\n );\n }\n\n #onVisibilityChange = async () => {\n if (this.#closed) {\n return;\n }\n\n // In case of running in a worker, we don't have a document.\n if (getBrowserGlobal('document')?.visibilityState !== 'visible') {\n return;\n }\n\n await this.#checkForClientStateNotFoundAndCallHandler();\n };\n\n async #checkForClientStateNotFoundAndCallHandler(): Promise<boolean> {\n const {clientID} = this;\n const hasClientState = await withRead(this.perdag, read =>\n persistHasClientState(clientID, read),\n );\n if (!hasClientState) {\n this.#clientStateNotFoundOnClient(clientID);\n }\n return !hasClientState;\n }\n\n /**\n * The browser profile ID for this browser profile. Every instance of Replicache\n * browser-profile-wide shares the same profile ID.\n */\n get profileID(): Promise<string> {\n return this.#profileIDPromise;\n }\n\n /**\n * The client ID for this instance of Replicache. Each instance of Replicache\n * gets a unique client ID.\n */\n get clientID(): string {\n return this.#clientID;\n }\n\n /**\n * The client group ID for this instance of Replicache. Instances of\n * Replicache will have the same client group ID if and only if they have\n * the same name, mutators, indexes, schema version, format version, and\n * browser profile.\n */\n get clientGroupID(): Promise<string> {\n return this.#clientGroupIDPromise;\n }\n\n /**\n * `onOnlineChange` is called when the {@link online} property changes. See\n * {@link online} for more details.\n */\n onOnlineChange: ((online: boolean) => void) | null = null;\n\n /**\n * A rough heuristic for whether the client is currently online. Note that\n * there is no way to know for certain whether a client is online - the next\n * request can always fail. This property returns true if the last sync attempt succeeded,\n * and false otherwise.\n */\n get online(): boolean {\n return this.#online;\n }\n\n /**\n * Whether the Replicache database has been closed. Once Replicache has been\n * closed it no longer syncs and you can no longer read or write data out of\n * it. After it has been closed it is pretty much useless and should not be\n * used any more.\n */\n get closed(): boolean {\n return this.#closed;\n }\n\n /**\n * Closes this Replicache instance.\n *\n * When closed all subscriptions end and no more read or writes are allowed.\n */\n async close(): Promise<void> {\n this.#closed = true;\n const {promise, resolve} = resolver();\n closingInstances.set(this.name, promise);\n\n this.#closeAbortController.abort();\n\n getBrowserGlobal('document')?.removeEventListener(\n 'visibilitychange',\n this.#onVisibilityChange,\n );\n\n await this.#ready;\n const closingPromises = [\n this.memdag.close(),\n this.perdag.close(),\n this.#idbDatabases.close(),\n ];\n\n this.#pullConnectionLoop.close();\n this.#pushConnectionLoop.close();\n\n this.#subscriptions.clear();\n\n await Promise.all(closingPromises);\n closingInstances.delete(this.name);\n resolve();\n }\n\n async maybeEndPull(syncHead: Hash, requestID: string): Promise<void> {\n for (;;) {\n if (this.#closed) {\n return;\n }\n\n await this.#ready;\n const {clientID} = this;\n const lc = this.#lc\n .withContext('maybeEndPull')\n .withContext('requestID', requestID);\n const {replayMutations, diffs, oldMainHead, mainHead} =\n await maybeEndPull<LocalMeta>(\n this.memdag,\n lc,\n syncHead,\n clientID,\n this.#subscriptions,\n FormatVersion.Latest,\n );\n\n if (!replayMutations || replayMutations.length === 0) {\n // All done.\n this.#zero?.advance(oldMainHead, mainHead, diffs.get('') ?? []);\n await this.#subscriptions.fire(diffs);\n void this.#schedulePersist();\n return;\n }\n\n // Replay.\n const zeroData = await this.#zero?.getTxData?.(syncHead);\n for (const mutation of replayMutations) {\n // TODO(greg): I'm not sure why this was in Replicache#_mutate...\n // Ensure that we run initial pending subscribe functions before starting a\n // write transaction.\n if (this.#subscriptions.hasPendingSubscriptionRuns) {\n await Promise.resolve();\n }\n const {meta} = mutation;\n syncHead = await withWriteNoImplicitCommit(this.memdag, dagWrite =>\n rebaseMutationAndCommit(\n mutation,\n dagWrite,\n syncHead,\n SYNC_HEAD_NAME,\n this.#mutatorRegistry,\n lc,\n isLocalMetaDD31(meta) ? meta.clientID : clientID,\n FormatVersion.Latest,\n zeroData,\n ),\n );\n }\n }\n }\n\n #invokePull(): Promise<boolean> {\n if (this.#isPullDisabled()) {\n return Promise.resolve(true);\n }\n\n return this.#wrapInOnlineCheck(async () => {\n try {\n this.#changeSyncCounters(0, 1);\n const {syncHead, requestID, ok} = await this.beginPull();\n if (!ok) {\n return false;\n }\n if (syncHead !== emptyHash) {\n await this.maybeEndPull(syncHead, requestID);\n }\n } catch (e) {\n throw await this.#convertToClientStateNotFoundError(e);\n } finally {\n this.#changeSyncCounters(0, -1);\n }\n return true;\n }, 'Pull');\n }\n\n #isPullDisabled() {\n return (\n this.isClientGroupDisabled ||\n (this.pullURL === '' && isDefaultPuller(this.puller))\n );\n }\n\n async #wrapInOnlineCheck(\n f: () => Promise<boolean>,\n name: string,\n ): Promise<boolean> {\n let online = true;\n\n try {\n return await f();\n } catch (e) {\n // The error paths of beginPull and maybeEndPull need to be reworked.\n //\n // We want to distinguish between:\n // a) network requests failed -- we're offline basically\n // b) sync was aborted because one's already in progress\n // c) oh noes - something unexpected happened\n //\n // Right now, all of these come out as errors. We distinguish (b) with a\n // hacky string search. (a) and (c) are not distinguishable currently\n // because repc doesn't provide sufficient information, so we treat all\n // errors that aren't (b) as (a).\n if (e instanceof PushError || e instanceof PullError) {\n online = false;\n this.#lc.debug?.(`${name} threw:\\n`, e, '\\nwith cause:\\n', e.causedBy);\n } else if (e instanceof ReportError) {\n this.#lc.error?.(e);\n } else {\n this.#lc.info?.(`${name} threw:\\n`, e);\n }\n return false;\n } finally {\n if (this.#online !== online) {\n this.#online = online;\n this.onOnlineChange?.(online);\n if (online) {\n void this.recoverMutations();\n }\n }\n }\n }\n\n async #wrapInReauthRetries<R>(\n f: (\n requestID: string,\n requestLc: LogContext,\n ) => Promise<{\n httpRequestInfo: HTTPRequestInfo | undefined;\n result: R;\n }>,\n verb: string,\n lc: LogContext,\n preAuth: () => MaybePromise<void> = noop,\n postAuth: () => MaybePromise<void> = noop,\n ): Promise<{\n result: R;\n authFailure: boolean;\n }> {\n const {clientID} = this;\n let reauthAttempts = 0;\n let lastResult;\n lc = lc.withContext(verb);\n do {\n const requestID = newRequestID(clientID);\n const requestLc = lc.withContext('requestID', requestID);\n const {httpRequestInfo, result} = await f(requestID, requestLc);\n lastResult = result;\n if (!httpRequestInfo) {\n return {\n result,\n authFailure: false,\n };\n }\n const {errorMessage, httpStatusCode} = httpRequestInfo;\n\n if (errorMessage || httpStatusCode !== 200) {\n // TODO(arv): Maybe we should not log the server URL when the error comes\n // from a Pusher/Puller?\n requestLc.error?.(\n `Got a non 200 response doing ${verb}: ${httpStatusCode}` +\n (errorMessage ? `: ${errorMessage}` : ''),\n );\n }\n if (httpStatusCode !== httpStatusUnauthorized) {\n return {\n result,\n authFailure: false,\n };\n }\n if (!this.getAuth) {\n return {\n result,\n authFailure: true,\n };\n }\n let auth;\n try {\n await preAuth();\n auth = await this.getAuth();\n } finally {\n await postAuth();\n }\n if (auth === null || auth === undefined) {\n return {\n result,\n authFailure: true,\n };\n }\n this.auth = auth;\n reauthAttempts++;\n } while (reauthAttempts < MAX_REAUTH_TRIES);\n lc.info?.('Tried to reauthenticate too many times');\n return {\n result: lastResult,\n authFailure: true,\n };\n }\n\n #isPushDisabled() {\n return (\n this.isClientGroupDisabled ||\n (this.pushURL === '' && isDefaultPusher(this.pusher))\n );\n }\n\n async #invokePush(): Promise<boolean> {\n if (TESTING) {\n this.onPushInvoked();\n }\n if (this.#isPushDisabled()) {\n return true;\n }\n\n await this.#ready;\n const profileID = await this.#profileIDPromise;\n const {clientID} = this;\n const clientGroupID = await this.#clientGroupIDPromise;\n return this.#wrapInOnlineCheck(async () => {\n const {result: pusherResult} = await this.#wrapInReauthRetries(\n async (requestID: string, requestLc: LogContext) => {\n try {\n this.#changeSyncCounters(1, 0);\n const pusherResult = await push(\n requestID,\n this.memdag,\n requestLc,\n profileID,\n clientGroupID,\n clientID,\n this.pusher,\n this.schemaVersion,\n PUSH_VERSION_DD31,\n );\n return {\n result: pusherResult,\n httpRequestInfo: pusherResult?.httpRequestInfo,\n };\n } finally {\n this.#changeSyncCounters(-1, 0);\n }\n },\n 'push',\n this.#lc,\n );\n\n if (pusherResult === undefined) {\n // No pending mutations.\n return true;\n }\n\n const {response, httpRequestInfo} = pusherResult;\n\n if (isVersionNotSupportedResponse(response)) {\n this.#handleVersionNotSupportedResponse(response);\n } else if (isClientStateNotFoundResponse(response)) {\n await this.#clientStateNotFoundOnServer();\n }\n\n // No pushResponse means we didn't do a push because there were no\n // pending mutations.\n return httpRequestInfo.httpStatusCode === 200;\n }, 'Push');\n }\n\n #handleVersionNotSupportedResponse(response: VersionNotSupportedResponse) {\n const reason: UpdateNeededReason = {\n type: response.error,\n };\n if (response.versionType) {\n reason.versionType = response.versionType;\n }\n this.#fireOnUpdateNeeded(reason);\n }\n\n /**\n * Push pushes pending changes to the {@link pushURL}.\n *\n * You do not usually need to manually call push. If {@link pushDelay} is\n * non-zero (which it is by default) pushes happen automatically shortly after\n * mutations.\n *\n * If the server endpoint fails push will be continuously retried with an\n * exponential backoff.\n *\n * @param [now=false] If true, push will happen immediately and ignore\n * {@link pushDelay}, {@link RequestOptions.minDelayMs} as well as the\n * exponential backoff in case of errors.\n * @returns A promise that resolves when the next push completes. In case of\n * errors the first error will reject the returned promise. Subsequent errors\n * will not be reflected in the promise.\n */\n push({now = false} = {}): Promise<void> {\n return throwIfError(this.#pushConnectionLoop.send(now));\n }\n\n /**\n * Pull pulls changes from the {@link pullURL}. If there are any changes local\n * changes will get replayed on top of the new server state.\n *\n * If the server endpoint fails pull will be continuously retried with an\n * exponential backoff.\n *\n * @param [now=false] If true, pull will happen immediately and ignore\n * {@link RequestOptions.minDelayMs} as well as the exponential backoff in\n * case of errors.\n * @returns A promise that resolves when the next pull completes. In case of\n * errors the first error will reject the returned promise. Subsequent errors\n * will not be reflected in the promise.\n */\n pull({now = false} = {}): Promise<void> {\n return throwIfError(this.#pullConnectionLoop.send(now));\n }\n\n /**\n * Applies an update from the server to Replicache.\n * Throws an error if cookie does not match. In that case the server thinks\n * this client has a different cookie than it does; the caller should disconnect\n * from the server and re-register, which transmits the cookie the client actually\n * has.\n *\n * @experimental This method is under development and its semantics will change.\n */\n async poke(poke: PokeInternal): Promise<void> {\n await this.#ready;\n // TODO(MP) Previously we created a request ID here and included it with the\n // PullRequest to the server so we could tie events across client and server\n // together. Since the direction is now reversed, creating and adding a request ID\n // here is kind of silly. We should consider creating the request ID\n // on the *server* and passing it down in the poke for inclusion here in the log\n // context\n const {clientID} = this;\n const requestID = newRequestID(clientID);\n const lc = this.#lc\n .withContext('handlePullResponse')\n .withContext('requestID', requestID);\n\n const {pullResponse} = poke;\n\n if (isVersionNotSupportedResponse(pullResponse)) {\n this.#handleVersionNotSupportedResponse(pullResponse);\n return;\n }\n\n if (isClientStateNotFoundResponse(pullResponse)) {\n await this.#clientStateNotFoundOnServer();\n return;\n }\n\n const result = await handlePullResponseV1(\n lc,\n this.memdag,\n deepFreeze(poke.baseCookie),\n pullResponse,\n clientID,\n FormatVersion.Latest,\n );\n\n switch (result.type) {\n case HandlePullResponseResultEnum.Applied:\n await this.maybeEndPull(result.syncHead, requestID);\n break;\n case HandlePullResponseResultEnum.CookieMismatch:\n throw new Error(\n 'unexpected base cookie for poke: ' + JSON.stringify(poke),\n );\n case HandlePullResponseResultEnum.NoOp:\n break;\n }\n }\n\n async beginPull(): Promise<BeginPullResult> {\n if (TESTING) {\n this.onBeginPull();\n }\n await this.#ready;\n const profileID = await this.profileID;\n const {clientID} = this;\n const clientGroupID = await this.#clientGroupIDPromise;\n const {\n result: {beginPullResponse, requestID},\n } = await this.#wrapInReauthRetries(\n async (requestID: string, requestLc: LogContext) => {\n const beginPullResponse = await beginPullV1(\n profileID,\n clientID,\n clientGroupID,\n this.schemaVersion,\n this.puller,\n requestID,\n this.memdag,\n FormatVersion.Latest,\n requestLc,\n );\n return {\n result: {beginPullResponse, requestID},\n httpRequestInfo: beginPullResponse.httpRequestInfo,\n };\n },\n 'pull',\n this.#lc,\n () => this.#changeSyncCounters(0, -1),\n () => this.#changeSyncCounters(0, 1),\n );\n\n const {pullResponse} = beginPullResponse;\n if (isVersionNotSupportedResponse(pullResponse)) {\n this.#handleVersionNotSupportedResponse(pullResponse);\n } else if (isClientStateNotFoundResponse(beginPullResponse.pullResponse)) {\n await this.#clientStateNotFoundOnServer();\n }\n\n const {syncHead, httpRequestInfo} = beginPullResponse;\n return {requestID, syncHead, ok: httpRequestInfo.httpStatusCode === 200};\n }\n\n persist(): Promise<void> {\n // Prevent multiple persist calls from running at the same time.\n return this.#persistLock.withLock(async () => {\n const {clientID} = this;\n await this.#ready;\n if (this.#closed) {\n return;\n }\n try {\n await persistDD31(\n this.#lc,\n clientID,\n this.memdag,\n this.perdag,\n this.#mutatorRegistry,\n () => this.#closed,\n FormatVersion.Latest,\n this.#zero?.getTxData,\n );\n } catch (e) {\n if (e instanceof ClientStateNotFoundError) {\n this.#clientStateNotFoundOnClient(clientID);\n } else if (this.#closed) {\n this.#lc.debug?.('Exception persisting during close', e);\n } else {\n throw e;\n }\n }\n\n const clientGroupID = await this.#clientGroupIDPromise;\n assert(clientGroupID, 'Expected clientGroupID to be defined');\n this.#onPersist({clientID, clientGroupID});\n });\n }\n\n async refresh(): Promise<void> {\n await this.#ready;\n const {clientID} = this;\n if (this.#closed || !this.#enableRefresh()) {\n return;\n }\n let refreshResult: Awaited<ReturnType<typeof refresh>>;\n try {\n refreshResult = await refresh(\n this.#lc,\n this.memdag,\n this.perdag,\n clientID,\n this.#mutatorRegistry,\n this.#subscriptions,\n () => this.closed,\n FormatVersion.Latest,\n this.#zero,\n );\n } catch (e) {\n if (e instanceof ClientStateNotFoundError) {\n this.#clientStateNotFoundOnClient(clientID);\n } else if (this.#closed) {\n this.#lc.debug?.('Exception refreshing during close', e);\n } else {\n throw e;\n }\n }\n if (refreshResult !== undefined) {\n await this.#subscriptions.fire(refreshResult.diffs);\n }\n }\n\n #fireOnClientStateNotFound() {\n this.onClientStateNotFound?.();\n }\n\n #clientStateNotFoundOnClient(clientID: ClientID) {\n this.#lc.error?.(`Client state not found on client, clientID: ${clientID}`);\n this.#fireOnClientStateNotFound();\n }\n\n async #clientStateNotFoundOnServer() {\n const clientGroupID = await this.#clientGroupIDPromise;\n this.#lc.error?.(\n `Client state not found on server, clientGroupID: ${clientGroupID}`,\n );\n await this.disableClientGroup();\n this.#fireOnClientStateNotFound();\n }\n\n async disableClientGroup(): Promise<void> {\n const clientGroupID = await this.#clientGroupIDPromise;\n assert(clientGroupID, 'Expected clientGroupID to be defined');\n this.isClientGroupDisabled = true;\n await withWrite(this.perdag, dagWrite =>\n disableClientGroup(clientGroupID, dagWrite),\n );\n }\n\n #fireOnUpdateNeeded(reason: UpdateNeededReason) {\n this.#lc.debug?.(`Update needed, reason: ${reason}`);\n this.onUpdateNeeded?.(reason);\n }\n\n async #schedulePersist(): Promise<void> {\n if (!this.#enableScheduledPersist) {\n return;\n }\n await this.#schedule('persist', this.#persistScheduler);\n }\n\n async #handlePersist(persistInfo: PersistInfo): Promise<void> {\n this.#lc.debug?.('Handling persist', persistInfo);\n const clientGroupID = await this.#clientGroupIDPromise;\n if (persistInfo.clientGroupID === clientGroupID) {\n void this.#scheduleRefresh();\n }\n }\n\n async #scheduleRefresh(): Promise<void> {\n if (!this.#enableScheduledRefresh) {\n return;\n }\n await this.#schedule('refresh from storage', this.#refreshScheduler);\n }\n\n async #schedule(name: string, scheduler: ProcessScheduler): Promise<void> {\n try {\n await scheduler.schedule();\n } catch (e) {\n if (e instanceof AbortError) {\n this.#lc.debug?.(`Scheduled ${name} did not complete before close.`);\n } else {\n this.#lc.error?.(`Error during ${name}`, e);\n }\n }\n }\n\n /**\n * Runs a refresh as soon as possible through the refresh scheduler.\n */\n runRefresh(): Promise<void> {\n return this.#refreshScheduler.run();\n }\n\n #changeSyncCounters(pushDelta: 0, pullDelta: 1 | -1): void;\n #changeSyncCounters(pushDelta: 1 | -1, pullDelta: 0): void;\n #changeSyncCounters(pushDelta: number, pullDelta: number): void {\n this.#pushCounter += pushDelta;\n this.#pullCounter += pullDelta;\n const delta = pushDelta + pullDelta;\n const counter = this.#pushCounter + this.#pullCounter;\n if ((delta === 1 && counter === 1) || counter === 0) {\n const syncing = counter > 0;\n // Run in a new microtask.\n void Promise.resolve().then(() => this.onSync?.(syncing));\n }\n }\n\n /**\n * Subscribe to the result of a {@link query}. The `body` function is\n * evaluated once and its results are returned via `onData`.\n *\n * Thereafter, each time the the result of `body` changes, `onData` is fired\n * again with the new result.\n *\n * `subscribe()` goes to significant effort to avoid extraneous work\n * re-evaluating subscriptions:\n *\n * 1. subscribe tracks the keys that `body` accesses each time it runs. `body`\n * is only re-evaluated when those keys change.\n * 2. subscribe only re-fires `onData` in the case that a result changes by\n * way of the `isEqual` option which defaults to doing a deep JSON value\n * equality check.\n *\n * Because of (1), `body` must be a pure function of the data in Replicache.\n * `body` must not access anything other than the `tx` parameter passed to it.\n *\n * Although subscribe is as efficient as it can be, it is somewhat constrained\n * by the goal of returning an arbitrary computation of the cache. For even\n * better performance (but worse dx), see {@link experimentalWatch}.\n *\n * If an error occurs in the `body` the `onError` function is called if\n * present. Otherwise, the error is logged at log level 'error'.\n *\n * To cancel the subscription, call the returned function.\n *\n * @param body The function to evaluate to get the value to pass into\n * `onData`.\n * @param options Options is either a function or an object. If it is a\n * function it is equivalent to passing it as the `onData` property of an\n * object.\n */\n subscribe<R>(\n body: (tx: ReadTransaction) => Promise<R>,\n options: SubscribeOptions<R> | ((result: R) => void),\n ): () => void {\n if (typeof options === 'function') {\n options = {onData: options};\n }\n\n const {onData, onError, onDone, isEqual} = options;\n return this.#subscriptions.add(\n new SubscriptionImpl(body, onData, onError, onDone, isEqual),\n );\n }\n\n /**\n * Watches Replicache for changes.\n *\n * The `callback` gets called whenever the underlying data changes and the\n * `key` changes matches the `prefix` of {@link ExperimentalWatchIndexOptions} or\n * {@link ExperimentalWatchNoIndexOptions} if present. If a change\n * occurs to the data but the change does not impact the key space the\n * callback is not called. In other words, the callback is never called with\n * an empty diff.\n *\n * This gets called after commit (a mutation or a rebase).\n *\n * @experimental This method is under development and its semantics will\n * change.\n */\n experimentalWatch(callback: WatchNoIndexCallback): () => void;\n experimentalWatch<Options extends WatchOptions>(\n callback: WatchCallbackForOptions<Options>,\n options?: Options,\n ): () => void;\n experimentalWatch<Options extends WatchOptions>(\n callback: WatchCallbackForOptions<Options>,\n options?: Options,\n ): () => void {\n return this.#subscriptions.add(\n new WatchSubscription(callback as WatchCallback, options),\n );\n }\n\n /**\n * Query is used for read transactions. It is recommended to use transactions\n * to ensure you get a consistent view across multiple calls to `get`, `has`\n * and `scan`.\n */\n query<R>(body: (tx: ReadTransaction) => Promise<R> | R): Promise<R> {\n return this.#queryInternal(body);\n }\n\n get cookie(): Promise<Cookie> {\n return this.#ready.then(() =>\n withRead(this.memdag, async dagRead => {\n const mainHeadHash = await dagRead.getHead(DEFAULT_HEAD_NAME);\n if (!mainHeadHash) {\n throw new Error('Internal no main head found');\n }\n const baseSnapshot = await baseSnapshotFromHash(mainHeadHash, dagRead);\n const baseSnapshotMeta = baseSnapshot.meta;\n const cookie = baseSnapshotMeta.cookieJSON;\n assertCookie(cookie);\n return cookie;\n }),\n );\n }\n\n #queryInternal: QueryInternal = async body => {\n await this.#ready;\n const {clientID} = this;\n return withRead(this.memdag, async dagRead => {\n try {\n const dbRead = await readFromDefaultHead(dagRead, FormatVersion.Latest);\n const tx = new ReadTransactionImpl(clientID, dbRead, this.#lc);\n return await body(tx);\n } catch (ex) {\n throw await this.#convertToClientStateNotFoundError(ex);\n }\n });\n };\n\n #register<Return extends ReadonlyJSONValue | void, Args extends JSONValue>(\n name: string,\n mutatorImpl: (tx: WriteTransaction, args?: Args) => MaybePromise<Return>,\n ): (\n args?: Args,\n ) => Promise<Return> | {client: Promise<Return>; server: Promise<unknown>} {\n this.#mutatorRegistry[name] = mutatorImpl as (\n tx: WriteTransaction,\n args: JSONValue | undefined,\n ) => Promise<void | JSONValue>;\n\n return (\n args?: Args,\n ):\n | Promise<Return>\n | {client: Promise<Return>; server: Promise<unknown>} => {\n // DO NOT track CRUD mutations as they do not receive responses from\n // the server.\n const trackingData =\n name === '_zero_crud' ? undefined : this.#zero?.trackMutation();\n\n const result = this.#mutate(\n trackingData,\n name,\n mutatorImpl,\n args,\n performance.now(),\n );\n\n if (trackingData) {\n return {\n client: result,\n server: trackingData.serverPromise,\n };\n }\n\n return result;\n };\n }\n\n #registerMutators<\n M extends {\n [key: string]: (\n tx: WriteTransaction,\n args?: ReadonlyJSONValue,\n ) => MutatorReturn;\n },\n >(regs: M): MakeMutators<M> {\n type Mut = MakeMutators<M>;\n const rv: Partial<Mut> = Object.create(null);\n for (const k in regs) {\n rv[k] = this.#register(k, regs[k]) as MakeMutator<M[typeof k]>;\n }\n return rv as Mut;\n }\n\n async #mutate<\n R extends ReadonlyJSONValue | void,\n A extends ReadonlyJSONValue,\n >(\n trackingData: MutationTrackingData | undefined,\n name: string,\n mutatorImpl: (tx: WriteTransaction, args?: A) => MaybePromise<R>,\n args: A | undefined,\n timestamp: number,\n ): Promise<R> {\n const frozenArgs = deepFreeze(args ?? null);\n\n // Ensure that we run initial pending subscribe functions before starting a\n // write transaction.\n if (this.#subscriptions.hasPendingSubscriptionRuns) {\n await Promise.resolve();\n }\n\n await this.#ready;\n const {clientID} = this;\n return withWriteNoImplicitCommit(this.memdag, async dagWrite => {\n try {\n let result: R;\n let newHead: Hash;\n let diffs: DiffsMap;\n let headHash: Hash;\n try {\n headHash = await mustGetHeadHash(DEFAULT_HEAD_NAME, dagWrite);\n const originalHash = null;\n\n const dbWrite = await newWriteLocal(\n headHash,\n name,\n frozenArgs,\n originalHash,\n dagWrite,\n timestamp,\n clientID,\n FormatVersion.Latest,\n );\n\n const mutationID = await dbWrite.getMutationID();\n const tx = new WriteTransactionImpl(\n clientID,\n mutationID,\n 'initial',\n await this.#zero?.getTxData(headHash, {\n openLazyRead: dagWrite,\n }),\n dbWrite,\n this.#lc,\n );\n\n if (trackingData) {\n this.#zero?.mutationIDAssigned(\n trackingData.ephemeralID,\n mutationID,\n );\n }\n\n result = await mutatorImpl(tx, args);\n\n throwIfClosed(dbWrite);\n const lastMutationID = await dbWrite.getMutationID();\n [newHead, diffs] = await dbWrite.commitWithDiffs(\n DEFAULT_HEAD_NAME,\n this.#subscriptions,\n );\n\n // Update this after the commit in case the commit fails.\n this.lastMutationID = lastMutationID;\n } catch (e) {\n // If we threw before we could persist the mutation\n // then we need to reject the mutation.\n if (trackingData) {\n this.#zero?.rejectMutation(trackingData.ephemeralID, e);\n }\n throw e;\n }\n\n this.#zero?.advance(headHash, newHead, diffs.get('') ?? []);\n\n // Send is not supposed to reject\n this.#pushConnectionLoop.send(false).catch(() => void 0);\n await this.#subscriptions.fire(diffs);\n void this.#schedulePersist();\n return result;\n } catch (ex) {\n throw await this.#convertToClientStateNotFoundError(ex);\n }\n });\n }\n\n /**\n * In the case we get a ChunkNotFoundError we check if the client got garbage\n * collected and if so change the error to a ClientStateNotFoundError instead\n */\n async #convertToClientStateNotFoundError(ex: unknown): Promise<unknown> {\n if (\n ex instanceof ChunkNotFoundError &&\n (await this.#checkForClientStateNotFoundAndCallHandler())\n ) {\n return new ClientStateNotFoundError(this.clientID);\n }\n\n return ex;\n }\n\n recoverMutations(): Promise<boolean> | void {\n if (!process.env.DISABLE_MUTATION_RECOVERY) {\n // oxlint-disable-next-line no-non-null-assertion\n const result = this.#mutationRecovery!.recoverMutations(\n this.#ready,\n this.perdag,\n this.#idbDatabase,\n this.#idbDatabases,\n this.#kvStoreProvider.create,\n );\n if (TESTING) {\n void this.onRecoverMutations(result);\n }\n return result;\n }\n }\n\n /**\n * List of pending mutations. The order of this is from oldest to newest.\n *\n * Gives a list of local mutations that have `mutationID` >\n * `syncHead.mutationID` that exists on the main client group.\n *\n * @experimental This method is experimental and may change in the future.\n */\n experimentalPendingMutations(): Promise<readonly PendingMutation[]> {\n return withRead(this.memdag, pendingMutationsForAPI);\n }\n}\n\n// This map is used to keep track of closing instances of Replicache. When an\n// instance is opening we wait for any currently closing instances.\nconst closingInstances: Map<string, Promise<unknown>> = new Map();\n\nasync function throwIfError(p: Promise<undefined | {error: unknown}>) {\n const res = await p;\n if (res) {\n throw res.error;\n }\n}\n\nfunction reload(): void {\n if (typeof location !== 'undefined') {\n location.reload();\n }\n}\n\nfunction validateOptions<MD extends MutatorDefs>(\n options: ReplicacheOptions<MD>,\n): void {\n const {name, clientMaxAgeMs} = options;\n if (typeof name !== 'string' || !name) {\n throw new TypeError('name is required and must be non-empty');\n }\n\n if (clientMaxAgeMs !== undefined) {\n const min = Math.max(GC_INTERVAL, HEARTBEAT_INTERVAL);\n if (typeof clientMaxAgeMs !== 'number' || clientMaxAgeMs <= min) {\n throw new TypeError(\n `clientAgeMaxMs must be a number larger than ${min}ms`,\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuIA,IAAM,mBAAmB;AAEzB,IAAM,0BAA0B;AAChC,IAAM,0BAA0B;AAEhC,IAAM,sBAAsB;AAC5B,IAAM,sBAAsB;AAE5B,IAAM,2CAA2C,MAAM,KAAK;AAE5D,IAAM,gCAAgC,MAAS;AAE/C,IAAM,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AsB;CACrD;AACF;AAIA,IAAM,mCAAkD,IAAI,IAAI;AAEhE,eAAe,aAAa,GAA0C;CACpE,MAAM,MAAM,MAAM;CAClB,IAAI,KACF,MAAM,IAAI;AAEd;AAEA,SAAS,SAAe;CACtB,IAAI,OAAO,aAAa,aACtB,SAAS,OAAO;AAEpB;AAEA,SAAS,gBACP,SACM;CACN,MAAM,EAAC,MAAM,mBAAkB;CAC/B,IAAI,OAAO,SAAS,YAAY,CAAC,MAC/B,MAAM,IAAI,UAAU,wCAAwC;CAG9D,IAAI,mBAAmB,KAAA,GAAW;EAChC,MAAM,MAAM,KAAK,IAAI,aAAa,kBAAkB;EACpD,IAAI,OAAO,mBAAmB,YAAY,kBAAkB,KAC1D,MAAM,IAAI,UACR,+CAA+C,IAAI,GACrD;CAEJ;AACF"}
|
|
@@ -236,15 +236,6 @@ export interface ZeroTxData {
|
|
|
236
236
|
ivmSources: unknown;
|
|
237
237
|
token: string | undefined;
|
|
238
238
|
context: unknown;
|
|
239
|
-
/**
|
|
240
|
-
* A cheap copy, used for one mutation's speculative writes.
|
|
241
|
-
*
|
|
242
|
-
* Replaying a mutation writes to two places: Replicache's `Write` and the
|
|
243
|
-
* IVM sources held here. If the mutator throws, the `Write` is discarded,
|
|
244
|
-
* and the fork lets the IVM writes be discarded with it. The caller adopts
|
|
245
|
-
* the fork when the mutator succeeds and drops it when it throws.
|
|
246
|
-
*/
|
|
247
|
-
fork(): ZeroTxData;
|
|
248
239
|
}
|
|
249
240
|
export type ZeroReadOptions = {
|
|
250
241
|
openLazyRead?: Read | undefined;
|